babylon.viewer.max.js 5.9 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355105356105357105358105359105360105361105362105363105364105365105366105367105368105369105370105371105372105373105374105375105376105377105378105379105380105381105382105383105384105385105386105387105388105389105390105391105392105393105394105395105396105397105398105399105400105401105402105403105404105405105406105407105408105409105410105411105412105413105414105415105416105417105418105419105420105421105422105423105424105425105426105427105428105429105430105431105432105433105434105435105436105437105438105439105440105441105442105443105444105445105446105447105448105449105450105451105452105453105454105455105456105457105458105459105460105461105462105463105464105465105466105467105468105469105470105471105472105473105474105475105476105477105478105479105480105481105482105483105484105485105486105487105488105489105490105491105492105493105494105495105496105497105498105499105500105501105502105503105504105505105506105507105508105509105510105511105512105513105514105515105516105517105518105519105520105521105522105523105524105525105526105527105528105529105530105531105532105533105534105535105536105537105538105539105540105541105542105543105544105545105546105547105548105549105550105551105552105553105554105555105556105557105558105559105560105561105562105563105564105565105566105567105568105569105570105571105572105573105574105575105576105577105578105579105580105581105582105583105584105585105586105587105588105589105590105591105592105593105594105595105596105597105598105599105600105601105602105603105604105605105606105607105608105609105610105611105612105613105614105615105616105617105618105619105620105621105622105623105624105625105626105627105628105629105630105631105632105633105634105635105636105637105638105639105640105641105642105643105644105645105646105647105648105649105650105651105652105653105654105655105656105657105658105659105660105661105662105663105664105665105666105667105668105669105670105671105672105673105674105675105676105677105678105679105680105681105682105683105684105685105686105687105688105689105690105691105692105693105694105695105696105697105698105699105700105701105702105703105704105705105706105707105708105709105710105711105712105713105714105715105716105717105718105719105720105721105722105723105724105725105726105727105728105729105730105731105732105733105734105735105736105737105738105739105740105741105742105743105744105745105746105747105748105749105750105751105752105753105754105755105756105757105758105759105760105761105762105763105764105765105766105767105768105769105770105771105772105773105774105775105776105777105778105779105780105781105782105783105784105785105786105787105788105789105790105791105792105793105794105795105796105797105798105799105800105801105802105803105804105805105806105807105808105809105810105811105812105813105814105815105816105817105818105819105820105821105822105823105824105825105826105827105828105829105830105831105832105833105834105835105836105837105838105839105840105841105842105843105844105845105846105847105848105849105850105851105852105853105854105855105856105857105858105859105860105861105862105863105864105865105866105867105868105869105870105871105872105873105874105875105876105877105878105879105880105881105882105883105884105885105886105887105888105889105890105891105892105893105894105895105896105897105898105899105900105901105902105903105904105905105906105907105908105909105910105911105912105913105914105915105916105917105918105919105920105921105922105923105924105925105926105927105928105929105930105931105932105933105934105935105936105937105938105939105940105941105942105943105944105945105946105947105948105949105950105951105952105953105954105955105956105957105958105959105960105961105962105963105964105965105966105967105968105969105970105971105972105973105974105975105976105977105978105979105980105981105982105983105984105985105986105987105988105989105990105991105992105993105994105995105996105997105998105999106000106001106002106003106004106005106006106007106008106009106010106011106012106013106014106015106016106017106018106019106020106021106022106023106024106025106026106027106028106029106030106031106032106033106034106035106036106037106038106039106040106041106042106043106044106045106046106047106048106049106050106051106052106053106054106055106056106057106058106059106060106061106062106063106064106065106066106067106068106069106070106071106072106073106074106075106076106077106078106079106080106081106082106083106084106085106086106087106088106089106090106091106092106093106094106095106096106097106098106099106100106101106102106103106104106105106106106107106108106109106110106111106112106113106114106115106116106117106118106119106120106121106122106123106124106125106126106127106128106129106130106131106132106133106134106135106136106137106138106139106140106141106142106143106144106145106146106147106148106149106150106151106152106153106154106155106156106157106158106159106160106161106162106163106164106165106166106167106168106169106170106171106172106173106174106175106176106177106178106179106180106181106182106183106184106185106186106187106188106189106190106191106192106193106194106195106196106197106198106199106200106201106202106203106204106205106206106207106208106209106210106211106212106213106214106215106216106217106218106219106220106221106222106223106224106225106226106227106228106229106230106231106232106233106234106235106236106237106238106239106240106241106242106243106244106245106246106247106248106249106250106251106252106253106254106255106256106257106258106259106260106261106262106263106264106265106266106267106268106269106270106271106272106273106274106275106276106277106278106279106280106281106282106283106284106285106286106287106288106289106290106291106292106293106294106295106296106297106298106299106300106301106302106303106304106305106306106307106308106309106310106311106312106313106314106315106316106317106318106319106320106321106322106323106324106325106326106327106328106329106330106331106332106333106334106335106336106337106338106339106340106341106342106343106344106345106346106347106348106349106350106351106352106353106354106355106356106357106358106359106360106361106362106363106364106365106366106367106368106369106370106371106372106373106374106375106376106377106378106379106380106381106382106383106384106385106386106387106388106389106390106391106392106393106394106395106396106397106398106399106400106401106402106403106404106405106406106407106408106409106410106411106412106413106414106415106416106417106418106419106420106421106422106423106424106425106426106427106428106429106430106431106432106433106434106435106436106437106438106439106440106441106442106443106444106445106446106447106448106449106450106451106452106453106454106455106456106457106458106459106460106461106462106463106464106465106466106467106468106469106470106471106472106473106474106475106476106477106478106479106480106481106482106483106484106485106486106487106488106489106490106491106492106493106494106495106496106497106498106499106500106501106502106503106504106505106506106507106508106509106510106511106512106513106514106515106516106517106518106519106520106521106522106523106524106525106526106527106528106529106530106531106532106533106534106535106536106537106538106539106540106541106542106543106544106545106546106547106548106549106550106551106552106553106554106555106556106557106558106559106560106561106562106563106564106565106566106567106568106569106570106571106572106573106574106575106576106577106578106579106580106581106582106583106584106585106586106587106588106589106590106591106592106593106594106595106596106597106598106599106600106601106602106603106604106605106606106607106608106609106610106611106612106613106614106615106616106617106618106619106620106621106622106623106624106625106626106627106628106629106630106631106632106633106634106635106636106637106638106639106640106641106642106643106644106645106646106647106648106649106650106651106652106653106654106655106656106657106658106659106660106661106662106663106664106665106666106667106668106669106670106671106672106673106674106675106676106677106678106679106680106681106682106683106684106685106686106687106688106689106690106691106692106693106694106695106696106697106698106699106700106701106702106703106704106705106706106707106708106709106710106711106712106713106714106715106716106717106718106719106720106721106722106723106724106725106726106727106728106729106730106731106732106733106734106735106736106737106738106739106740106741106742106743106744106745106746106747106748106749106750106751106752106753106754106755106756106757106758106759106760106761106762106763106764106765106766106767106768106769106770106771106772106773106774106775106776106777106778106779106780106781106782106783106784106785106786106787106788106789106790106791106792106793106794106795106796106797106798106799106800106801106802106803106804106805106806106807106808106809106810106811106812106813106814106815106816106817106818106819106820106821106822106823106824106825106826106827106828106829106830106831106832106833106834106835106836106837106838106839106840106841106842106843106844106845106846106847106848106849106850106851106852106853106854106855106856106857106858106859106860106861106862106863106864106865106866106867106868106869106870106871106872106873106874106875106876106877106878106879106880106881106882106883106884106885106886106887106888106889106890106891106892106893106894106895106896106897106898106899106900106901106902106903106904106905106906106907106908106909106910106911106912106913106914106915106916106917106918106919106920106921106922106923106924106925106926106927106928106929106930106931106932106933106934106935106936106937106938106939106940106941106942106943106944106945106946106947106948106949106950106951106952106953106954106955106956106957106958106959106960106961106962106963106964106965106966106967106968106969106970106971106972106973106974106975106976106977106978106979106980106981106982106983106984106985106986106987106988106989106990106991106992106993106994106995106996106997106998106999107000107001107002107003107004107005107006107007107008107009107010107011107012107013107014107015107016107017107018107019107020107021107022107023107024107025107026107027107028107029107030107031107032107033107034107035107036107037107038107039107040107041107042107043107044107045107046107047107048107049107050107051107052107053107054107055107056107057107058107059107060107061107062107063107064107065107066107067107068107069107070107071107072107073107074107075107076107077107078107079107080107081107082107083107084107085107086107087107088107089107090107091107092107093107094107095107096107097107098107099107100107101107102107103107104107105107106107107107108107109107110107111107112107113107114107115107116107117107118107119107120107121107122107123107124107125107126107127107128107129107130107131107132107133107134107135107136107137107138107139107140107141107142107143107144107145107146107147107148107149107150107151107152107153107154107155107156107157107158107159107160107161107162107163107164107165107166107167107168107169107170107171107172107173107174107175107176107177107178107179107180107181107182107183107184107185107186107187107188107189107190107191107192107193107194107195107196107197107198107199107200107201107202107203107204107205107206107207107208107209107210107211107212107213107214107215107216107217107218107219107220107221107222107223107224107225107226107227107228107229107230107231107232107233107234107235107236107237107238107239107240107241107242107243107244107245107246107247107248107249107250107251107252107253107254107255107256107257107258107259107260107261107262107263107264107265107266107267107268107269107270107271107272107273107274107275107276107277107278107279107280107281107282107283107284107285107286107287107288107289107290107291107292107293107294107295107296107297107298107299107300107301107302107303107304107305107306107307107308107309107310107311107312107313107314107315107316107317107318107319107320107321107322107323107324107325107326107327107328107329107330107331107332107333107334107335107336107337107338107339107340107341107342107343107344107345107346107347107348107349107350107351107352107353107354107355107356107357107358107359107360107361107362107363107364107365107366107367107368107369107370107371107372107373107374107375107376107377107378107379107380107381107382107383107384107385107386107387107388107389107390107391107392107393107394107395107396107397107398107399107400107401107402107403107404107405107406107407107408107409107410107411107412107413107414107415107416107417107418107419107420107421107422107423107424107425107426107427107428107429107430107431107432107433107434107435107436107437107438107439107440107441107442107443107444107445107446107447107448107449107450107451107452107453107454107455107456107457107458107459107460107461107462107463107464107465107466107467107468107469107470107471107472107473107474107475107476107477107478107479107480107481107482107483107484107485107486107487107488107489107490107491107492107493107494107495107496107497107498107499107500107501107502107503107504107505107506107507107508107509107510107511107512107513107514107515107516107517107518107519107520107521107522107523107524107525107526107527107528107529107530107531107532107533107534107535107536107537107538107539107540107541107542107543107544107545107546107547107548107549107550107551107552107553107554107555107556107557107558107559107560107561107562107563107564107565107566107567107568107569107570107571107572107573107574107575107576107577107578107579107580107581107582107583107584107585107586107587107588107589107590107591107592107593107594107595107596107597107598107599107600107601107602107603107604107605107606107607107608107609107610107611107612107613107614107615107616107617107618107619107620107621107622107623107624107625107626107627107628107629107630107631107632107633107634107635107636107637107638107639107640107641107642107643107644107645107646107647107648107649107650107651107652107653107654107655107656107657107658107659107660107661107662107663107664107665107666107667107668107669107670107671107672107673107674107675107676107677107678107679107680107681107682107683107684107685107686107687107688107689107690107691107692107693107694107695107696107697107698107699107700107701107702107703107704107705107706107707107708107709107710107711107712107713107714107715107716107717107718107719107720107721107722107723107724107725107726107727107728107729107730107731107732107733107734107735107736107737107738107739107740107741107742107743107744107745107746107747107748107749107750107751107752107753107754107755107756107757107758107759107760107761107762107763107764107765107766107767107768107769107770107771107772107773107774107775107776107777107778107779107780107781107782107783107784107785107786107787107788107789107790107791107792107793107794107795107796107797107798107799107800107801107802107803107804107805107806107807107808107809107810107811107812107813107814107815107816107817107818107819107820107821107822107823107824107825107826107827107828107829107830107831107832107833107834107835107836107837107838107839107840107841107842107843107844107845107846107847107848107849107850107851107852107853107854107855107856107857107858107859107860107861107862107863107864107865107866107867107868107869107870107871107872107873107874107875107876107877107878107879107880107881107882107883107884107885107886107887107888107889107890107891107892107893107894107895107896107897107898107899107900107901107902107903107904107905107906107907107908107909107910107911107912107913107914107915107916107917107918107919107920107921107922107923107924107925107926107927107928107929107930107931107932107933107934107935107936107937107938107939107940107941107942107943107944107945107946107947107948107949107950107951107952107953107954107955107956107957107958107959107960107961107962107963107964107965107966107967107968107969107970107971107972107973107974107975107976107977107978107979107980107981107982107983107984107985107986107987107988107989107990107991107992107993107994107995107996107997107998107999108000108001108002108003108004108005108006108007108008108009108010108011108012108013108014108015108016108017108018108019108020108021108022108023108024108025108026108027108028108029108030108031108032108033108034108035108036108037108038108039108040108041108042108043108044108045108046108047108048108049108050108051108052108053108054108055108056108057108058108059108060108061108062108063108064108065108066108067108068108069108070108071108072108073108074108075108076108077108078108079108080108081108082108083108084108085108086108087108088108089108090108091108092108093108094108095108096108097108098108099108100108101108102108103108104108105108106108107108108108109108110108111108112108113108114108115108116108117108118108119108120108121108122108123108124108125108126108127108128108129108130108131108132108133108134108135108136108137108138108139108140108141108142108143108144108145108146108147108148108149108150108151108152108153108154108155108156108157108158108159108160108161108162108163108164108165108166108167108168108169108170108171108172108173108174108175108176108177108178108179108180108181108182108183108184108185108186108187108188108189108190108191108192108193108194108195108196108197108198108199108200108201108202108203108204108205108206108207108208108209108210108211108212108213108214108215108216108217108218108219108220108221108222108223108224108225108226108227108228108229108230108231108232108233108234108235108236108237108238108239108240108241108242108243108244108245108246108247108248108249108250108251108252108253108254108255108256108257108258108259108260108261108262108263108264108265108266108267108268108269108270108271108272108273108274108275108276108277108278108279108280108281108282108283108284108285108286108287108288108289108290108291108292108293108294108295108296108297108298108299108300108301108302108303108304108305108306108307108308108309108310108311108312108313108314108315108316108317108318108319108320108321108322108323108324108325108326108327108328108329108330108331108332108333108334108335108336108337108338108339108340108341108342108343108344108345108346108347108348108349108350108351108352108353108354108355108356108357108358108359108360108361108362108363108364108365108366108367108368108369108370108371108372108373108374108375108376108377108378108379108380108381108382108383108384108385108386108387108388108389108390108391108392108393108394108395108396108397108398108399108400108401108402108403108404108405108406108407108408108409108410108411108412108413108414108415108416108417108418108419108420108421108422108423108424108425108426108427108428108429108430108431108432108433108434108435108436108437108438108439108440108441108442108443108444108445108446108447108448108449108450108451108452108453108454108455108456108457108458108459108460108461108462108463108464108465108466108467108468108469108470108471108472108473108474108475108476108477108478108479108480108481108482108483108484108485108486108487108488108489108490108491108492108493108494108495108496108497108498108499108500108501108502108503108504108505108506108507108508108509108510108511108512108513108514108515108516108517108518108519108520108521108522108523108524108525108526108527108528108529108530108531108532108533108534108535108536108537108538108539108540108541108542108543108544108545108546108547108548108549108550108551108552108553108554108555108556108557108558108559108560108561108562108563108564108565108566108567108568108569108570108571108572108573108574108575108576108577108578108579108580108581108582108583108584108585108586108587108588108589108590108591108592108593108594108595108596108597108598108599108600108601108602108603108604108605108606108607108608108609108610108611108612108613108614108615108616108617108618108619108620108621108622108623108624108625108626108627108628108629108630108631108632108633108634108635108636108637108638108639108640108641108642108643108644108645108646108647108648108649108650108651108652108653108654108655108656108657108658108659108660108661108662108663108664108665108666108667108668108669108670108671108672108673108674108675108676108677108678108679108680108681108682108683108684108685108686108687108688108689108690108691108692108693108694108695108696108697108698108699108700108701108702108703108704108705108706108707108708108709108710108711108712108713108714108715108716108717108718108719108720108721108722108723108724108725108726108727108728108729108730108731108732108733108734108735108736108737108738108739108740108741108742108743108744108745108746108747108748108749108750108751108752108753108754108755108756108757108758108759108760108761108762108763108764108765108766108767108768108769108770108771108772108773108774108775108776108777108778108779108780108781108782108783108784108785108786108787108788108789108790108791108792108793108794108795108796108797108798108799108800108801108802108803108804108805108806108807108808108809108810108811108812108813108814108815108816108817108818108819108820108821108822108823108824108825108826108827108828108829108830108831108832108833108834108835108836108837108838108839108840108841108842108843108844108845108846108847108848108849108850108851108852108853108854108855108856108857108858108859108860108861108862108863108864108865108866108867108868108869108870108871108872108873108874108875108876108877108878108879108880108881108882108883108884108885108886108887108888108889108890108891108892108893108894108895108896108897108898108899108900108901108902108903108904108905108906108907108908108909108910108911108912108913108914108915108916108917108918108919108920108921108922108923108924108925108926108927108928108929108930108931108932108933108934108935108936108937108938108939108940108941108942108943108944108945108946108947108948108949108950108951108952108953108954108955108956108957108958108959108960108961108962108963108964108965108966108967108968108969108970108971108972108973108974108975108976108977108978108979108980108981108982108983108984108985108986108987108988108989108990108991108992108993108994108995108996108997108998108999109000109001109002109003109004109005109006109007109008109009109010109011109012109013109014109015109016109017109018109019109020109021109022109023109024109025109026109027109028109029109030109031109032109033109034109035109036109037109038109039109040109041109042109043109044109045109046109047109048109049109050109051109052109053109054109055109056109057109058109059109060109061109062109063109064109065109066109067109068109069109070109071109072109073109074109075109076109077109078109079109080109081109082109083109084109085109086109087109088109089109090109091109092109093109094109095109096109097109098109099109100109101109102109103109104109105109106109107109108109109109110109111109112109113109114109115109116109117109118109119109120109121109122109123109124109125109126109127109128109129109130109131109132109133109134109135109136109137109138109139109140109141109142109143109144109145109146109147109148109149109150109151109152109153109154109155109156109157109158109159109160109161109162109163109164109165109166109167109168109169109170109171109172109173109174109175109176109177109178109179109180109181109182109183109184109185109186109187109188109189109190109191109192109193109194109195109196109197109198109199109200109201109202109203109204109205109206109207109208109209109210109211109212109213109214109215109216109217109218109219109220109221109222109223109224109225109226109227109228109229109230109231109232109233109234109235109236109237109238109239109240109241109242109243109244109245109246109247109248109249109250109251109252109253109254109255109256109257109258109259109260109261109262109263109264109265109266109267109268109269109270109271109272109273109274109275109276109277109278109279109280109281109282109283109284109285109286109287109288109289109290109291109292109293109294109295109296109297109298109299109300109301109302109303109304109305109306109307109308109309109310109311109312109313109314109315109316109317109318109319109320109321109322109323109324109325109326109327109328109329109330109331109332109333109334109335109336109337109338109339109340109341109342109343109344109345109346109347109348109349109350109351109352109353109354109355109356109357109358109359109360109361109362109363109364109365109366109367109368109369109370109371109372109373109374109375109376109377109378109379109380109381109382109383109384109385109386109387109388109389109390109391109392109393109394109395109396109397109398109399109400109401109402109403109404109405109406109407109408109409109410109411109412109413109414109415109416109417109418109419109420109421109422109423109424109425109426109427109428109429109430109431109432109433109434109435109436109437109438109439109440109441109442109443109444109445109446109447109448109449109450109451109452109453109454109455109456109457109458109459109460109461109462109463109464109465109466109467109468109469109470109471109472109473109474109475109476109477109478109479109480109481109482109483109484109485109486109487109488109489109490109491109492109493109494109495109496109497109498109499109500109501109502109503109504109505109506109507109508109509109510109511109512109513109514109515109516109517109518109519109520109521109522109523109524109525109526109527109528109529109530109531109532109533109534109535109536109537109538109539109540109541109542109543109544109545109546109547109548109549109550109551109552109553109554109555109556109557109558109559109560109561109562109563109564109565109566109567109568109569109570109571109572109573109574109575109576109577109578109579109580109581109582109583109584109585109586109587109588109589109590109591109592109593109594109595109596109597109598109599109600109601109602109603109604109605109606109607109608109609109610109611109612109613109614109615109616109617109618109619109620109621109622109623109624109625109626109627109628109629109630109631109632109633109634109635109636109637109638109639109640109641109642109643109644109645109646109647109648109649109650109651109652109653109654109655109656109657109658109659109660109661109662109663109664109665109666109667109668109669109670109671109672109673109674109675109676109677109678109679109680109681109682109683109684109685109686109687109688109689109690109691109692109693109694109695109696109697109698109699109700109701109702109703109704109705109706109707109708109709109710109711109712109713109714109715109716109717109718109719109720109721109722109723109724109725109726109727109728109729109730109731109732109733109734109735109736109737109738109739109740109741109742109743109744109745109746109747109748109749109750109751109752109753109754109755109756109757109758109759109760109761109762109763109764109765109766109767109768109769109770109771109772109773109774109775109776109777109778109779109780109781109782109783109784109785109786109787109788109789109790109791109792109793109794109795109796109797109798109799109800109801109802109803109804109805109806109807109808109809109810109811109812109813109814109815109816109817109818109819109820109821109822109823109824109825109826109827109828109829109830109831109832109833109834109835109836109837109838109839109840109841109842109843109844109845109846109847109848109849109850109851109852109853109854109855109856109857109858109859109860109861109862109863109864109865109866109867109868109869109870109871109872109873109874109875109876109877109878109879109880109881109882109883109884109885109886109887109888109889109890109891109892109893109894109895109896109897109898109899109900109901109902109903109904109905109906109907109908109909109910109911109912109913109914109915109916109917109918109919109920109921109922109923109924109925109926109927109928109929109930109931109932109933109934109935109936109937109938109939109940109941109942109943109944109945109946109947109948109949109950109951109952109953109954109955109956109957109958109959109960109961109962109963109964109965109966109967109968109969109970109971109972109973109974109975109976109977109978109979109980109981109982109983109984109985109986109987109988109989109990109991109992109993109994109995109996109997109998109999110000110001110002110003110004110005110006110007110008110009110010110011110012110013110014110015110016110017110018110019110020110021110022110023110024110025110026110027110028110029110030110031110032110033110034110035110036110037110038110039110040110041110042110043110044110045110046110047110048110049110050110051110052110053110054110055110056110057110058110059110060110061110062110063110064110065110066110067110068110069110070110071110072110073110074110075110076110077110078110079110080110081110082110083110084110085110086110087110088110089110090110091110092110093110094110095110096110097110098110099110100110101110102110103110104110105110106110107110108110109110110110111110112110113110114110115110116110117110118110119110120110121110122110123110124110125110126110127110128110129110130110131110132110133110134110135110136110137110138110139110140110141110142110143110144110145110146110147110148110149110150110151110152110153110154110155110156110157110158110159110160110161110162110163110164110165110166110167110168110169110170110171110172110173110174110175110176110177110178110179110180110181110182110183110184110185110186110187110188110189110190110191110192110193110194110195110196110197110198110199110200110201110202110203110204110205110206110207110208110209110210110211110212110213110214110215110216110217110218110219110220110221110222110223110224110225110226110227110228110229110230110231110232110233110234110235110236110237110238110239110240110241110242110243110244110245110246110247110248110249110250110251110252110253110254110255110256110257110258110259110260110261110262110263110264110265110266110267110268110269110270110271110272110273110274110275110276110277110278110279110280110281110282110283110284110285110286110287110288110289110290110291110292110293110294110295110296110297110298110299110300110301110302110303110304110305110306110307110308110309110310110311110312110313110314110315110316110317110318110319110320110321110322110323110324110325110326110327110328110329110330110331110332110333110334110335110336110337110338110339110340110341110342110343110344110345110346110347110348110349110350110351110352110353110354110355110356110357110358110359110360110361110362110363110364110365110366110367110368110369110370110371110372110373110374110375110376110377110378110379110380110381110382110383110384110385110386110387110388110389110390110391110392110393110394110395110396110397110398110399110400110401110402110403110404110405110406110407110408110409110410110411110412110413110414110415110416110417110418110419110420110421110422110423110424110425110426110427110428110429110430110431110432110433110434110435110436110437110438110439110440110441110442110443110444110445110446110447110448110449110450110451110452110453110454110455110456110457110458110459110460110461110462110463110464110465110466110467110468110469110470110471110472110473110474110475110476110477110478110479110480110481110482110483110484110485110486110487110488110489110490110491110492110493110494110495110496110497110498110499110500110501110502110503110504110505110506110507110508110509110510110511110512110513110514110515110516110517110518110519110520110521110522110523110524110525110526110527110528110529110530110531110532110533110534110535110536110537110538110539110540110541110542110543110544110545110546110547110548110549110550110551110552110553110554110555110556110557110558110559110560110561110562110563110564110565110566110567110568110569110570110571110572110573110574110575110576110577110578110579110580110581110582110583110584110585110586110587110588110589110590110591110592110593110594110595110596110597110598110599110600110601110602110603110604110605110606110607110608110609110610110611110612110613110614110615110616110617110618110619110620110621110622110623110624110625110626110627110628110629110630110631110632110633110634110635110636110637110638110639110640110641110642110643110644110645110646110647110648110649110650110651110652110653110654110655110656110657110658110659110660110661110662110663110664110665110666110667110668110669110670110671110672110673110674110675110676110677110678110679110680110681110682110683110684110685110686110687110688110689110690110691110692110693110694110695110696110697110698110699110700110701110702110703110704110705110706110707110708110709110710110711110712110713110714110715110716110717110718110719110720110721110722110723110724110725110726110727110728110729110730110731110732110733110734110735110736110737110738110739110740110741110742110743110744110745110746110747110748110749110750110751110752110753110754110755110756110757110758110759110760110761110762110763110764110765110766110767110768110769110770110771110772110773110774110775110776110777110778110779110780110781110782110783110784110785110786110787110788110789110790110791110792110793110794110795110796110797110798110799110800110801110802110803110804110805110806110807110808110809110810110811110812110813110814110815110816110817110818110819110820110821110822110823110824110825110826110827110828110829110830110831110832110833110834110835110836110837110838110839110840110841110842110843110844110845110846110847110848110849110850110851110852110853110854110855110856110857110858110859110860110861110862110863110864110865110866110867110868110869110870110871110872110873110874110875110876110877110878110879110880110881110882110883110884110885110886110887110888110889110890110891110892110893110894110895110896110897110898110899110900110901110902110903110904110905110906110907110908110909110910110911110912110913110914110915110916110917110918110919110920110921110922110923110924110925110926110927110928110929110930110931110932110933110934110935110936110937110938110939110940110941110942110943110944110945110946110947110948110949110950110951110952110953110954110955110956110957110958110959110960110961110962110963110964110965110966110967110968110969110970110971110972110973110974110975110976110977110978110979110980110981110982110983110984110985110986110987110988110989110990110991110992110993110994110995110996110997110998110999111000111001111002111003111004111005111006111007111008111009111010111011111012111013111014111015111016111017111018111019111020111021111022111023111024111025111026111027111028111029111030111031111032111033111034111035111036111037111038111039111040111041111042111043111044111045111046111047111048111049111050111051111052111053111054111055111056111057111058111059111060111061111062111063111064111065111066111067111068111069111070111071111072111073111074111075111076111077111078111079111080111081111082111083111084111085111086111087111088111089111090111091111092111093111094111095111096111097111098111099111100111101111102111103111104111105111106111107111108111109111110111111111112111113111114111115111116111117111118111119111120111121111122111123111124111125111126111127111128111129111130111131111132111133111134111135111136111137111138111139111140111141111142111143111144111145111146111147111148111149111150111151111152111153111154111155111156111157111158111159111160111161111162111163111164111165111166111167111168111169111170111171111172111173111174111175111176111177111178111179111180111181111182111183111184111185111186111187111188111189111190111191111192111193111194111195111196111197111198111199111200111201111202111203111204111205111206111207111208111209111210111211111212111213111214111215111216111217111218111219111220111221111222111223111224111225111226111227111228111229111230111231111232111233111234111235111236111237111238111239111240111241111242111243111244111245111246111247111248111249111250111251111252111253111254111255111256111257111258111259111260111261111262111263111264111265111266111267111268111269111270111271111272111273111274111275111276111277111278111279111280111281111282111283111284111285111286111287111288111289111290111291111292111293111294111295111296111297111298111299111300111301111302111303111304111305111306111307111308111309111310111311111312111313111314111315111316111317111318111319111320111321111322111323111324111325111326111327111328111329111330111331111332111333111334111335111336111337111338111339111340111341111342111343111344111345111346111347111348111349111350111351111352111353111354111355111356111357111358111359111360111361111362111363111364111365111366111367111368111369111370111371111372111373111374111375111376111377111378111379111380111381111382111383111384111385111386111387111388111389111390111391111392111393111394111395111396111397111398111399111400111401111402111403111404111405111406111407111408111409111410111411111412111413111414111415111416111417111418111419111420111421111422111423111424111425111426111427111428111429111430111431111432111433111434111435111436111437111438111439111440111441111442111443111444111445111446111447111448111449111450111451111452111453111454111455111456111457111458111459111460111461111462111463111464111465111466111467111468111469111470111471111472111473111474111475111476111477111478111479111480111481111482111483111484111485111486111487111488111489111490111491111492111493111494111495111496111497111498111499111500111501111502111503111504111505111506111507111508111509111510111511111512111513111514111515111516111517111518111519111520111521111522111523111524111525111526111527111528111529111530111531111532111533111534111535111536111537111538111539111540111541111542111543111544111545111546111547111548111549111550111551111552111553111554111555111556111557111558111559111560111561111562111563111564111565111566111567111568111569111570111571111572111573111574111575111576111577111578111579111580111581111582111583111584111585111586111587111588111589111590111591111592111593111594111595111596111597111598111599111600111601111602111603111604111605111606111607111608111609111610111611111612111613111614111615111616111617111618111619111620111621111622111623111624111625111626111627111628111629111630111631111632111633111634111635111636111637111638111639111640111641111642111643111644111645111646111647111648111649111650111651111652111653111654111655111656111657111658111659111660111661111662111663111664111665111666111667111668111669111670111671111672111673111674111675111676111677111678111679111680111681111682111683111684111685111686111687111688111689111690111691111692111693111694111695111696111697111698111699111700111701111702111703111704111705111706111707111708111709111710111711111712111713111714111715111716111717111718111719111720111721111722111723111724111725111726111727111728111729111730111731111732111733111734111735111736111737111738111739111740111741111742111743111744111745111746111747111748111749111750111751111752111753111754111755111756111757111758111759111760111761111762111763111764111765111766111767111768111769111770111771111772111773111774111775111776111777111778111779111780111781111782111783111784111785111786111787111788111789111790111791111792111793111794111795111796111797111798111799111800111801111802111803111804111805111806111807111808111809111810111811111812111813111814111815111816111817111818111819111820111821111822111823111824111825111826111827111828111829111830111831111832111833111834111835111836111837111838111839111840111841111842111843111844111845111846111847111848111849111850111851111852111853111854111855111856111857111858111859111860111861111862111863111864111865111866111867111868111869111870111871111872111873111874111875111876111877111878111879111880111881111882111883111884111885111886111887111888111889111890111891111892111893111894111895111896111897111898111899111900111901111902111903111904111905111906111907111908111909111910111911111912111913111914111915111916111917111918111919111920111921111922111923111924111925111926111927111928111929111930111931111932111933111934111935111936111937111938111939111940111941111942111943111944111945111946111947111948111949111950111951111952111953111954111955111956111957111958111959111960111961111962111963111964111965111966111967111968111969111970111971111972111973111974111975111976111977111978111979111980111981111982111983111984111985111986111987111988111989111990111991111992111993111994111995111996111997111998111999112000112001112002112003112004112005112006112007112008112009112010112011112012112013112014112015112016112017112018112019112020112021112022112023112024112025112026112027112028112029112030112031112032112033112034112035112036112037112038112039112040112041112042112043112044112045112046112047112048112049112050112051112052112053112054112055112056112057112058112059112060112061112062112063112064112065112066112067112068112069112070112071112072112073112074112075112076112077112078112079112080112081112082112083112084112085112086112087112088112089112090112091112092112093112094112095112096112097112098112099112100112101112102112103112104112105112106112107112108112109112110112111112112112113112114112115112116112117112118112119112120112121112122112123112124112125112126112127112128112129112130112131112132112133112134112135112136112137112138112139112140112141112142112143112144112145112146112147112148112149112150112151112152112153112154112155112156112157112158112159112160112161112162112163112164112165112166112167112168112169112170112171112172112173112174112175112176112177112178112179112180112181112182112183112184112185112186112187112188112189112190112191112192112193112194112195112196112197112198112199112200112201112202112203112204112205112206112207112208112209112210112211112212112213112214112215112216112217112218112219112220112221112222112223112224112225112226112227112228112229112230112231112232112233112234112235112236112237112238112239112240112241112242112243112244112245112246112247112248112249112250112251112252112253112254112255112256112257112258112259112260112261112262112263112264112265112266112267112268112269112270112271112272112273112274112275112276112277112278112279112280112281112282112283112284112285112286112287112288112289112290112291112292112293112294112295112296112297112298112299112300112301112302112303112304112305112306112307112308112309112310112311112312112313112314112315112316112317112318112319112320112321112322112323112324112325112326112327112328112329112330112331112332112333112334112335112336112337112338112339112340112341112342112343112344112345112346112347112348112349112350112351112352112353112354112355112356112357112358112359112360112361112362112363112364112365112366112367112368112369112370112371112372112373112374112375112376112377112378112379112380112381112382112383112384112385112386112387112388112389112390112391112392112393112394112395112396112397112398112399112400112401112402112403112404112405112406112407112408112409112410112411112412112413112414112415112416112417112418112419112420112421112422112423112424112425112426112427112428112429112430112431112432112433112434112435112436112437112438112439112440112441112442112443112444112445112446112447112448112449112450112451112452112453112454112455112456112457112458112459112460112461112462112463112464112465112466112467112468112469112470112471112472112473112474112475112476112477112478112479112480112481112482112483112484112485112486112487112488112489112490112491112492112493112494112495112496112497112498112499112500112501112502112503112504112505112506112507112508112509112510112511112512112513112514112515112516112517112518112519112520112521112522112523112524112525112526112527112528112529112530112531112532112533112534112535112536112537112538112539112540112541112542112543112544112545112546112547112548112549112550112551112552112553112554112555112556112557112558112559112560112561112562112563112564112565112566112567112568112569112570112571112572112573112574112575112576112577112578112579112580112581112582112583112584112585112586112587112588112589112590112591112592112593112594112595112596112597112598112599112600112601112602112603112604112605112606112607112608112609112610112611112612112613112614112615112616112617112618112619112620112621112622112623112624112625112626112627112628112629112630112631112632112633112634112635112636112637112638112639112640112641112642112643112644112645112646112647112648112649112650112651112652112653112654112655112656112657112658112659112660112661112662112663112664112665112666112667112668112669112670112671112672112673112674112675112676112677112678112679112680112681112682112683112684112685112686112687112688112689112690112691112692112693112694112695112696112697112698112699112700112701112702112703112704112705112706112707112708112709112710112711112712112713112714112715112716112717112718112719112720112721112722112723112724112725112726112727112728112729112730112731112732112733112734112735112736112737112738112739112740112741112742112743112744112745112746112747112748112749112750112751112752112753112754112755112756112757112758112759112760112761112762112763112764112765112766112767112768112769112770112771112772112773112774112775112776112777112778112779112780112781112782112783112784112785112786112787112788112789112790112791112792112793112794112795112796112797112798112799112800112801112802112803112804112805112806112807112808112809112810112811112812112813112814112815112816112817112818112819112820112821112822112823112824112825112826112827112828112829112830112831112832112833112834112835112836112837112838112839112840112841112842112843112844112845112846112847112848112849112850112851112852112853112854112855112856112857112858112859112860112861112862112863112864112865112866112867112868112869112870112871112872112873112874112875112876112877112878112879112880112881112882112883112884112885112886112887112888112889112890112891112892112893112894112895112896112897112898112899112900112901112902112903112904112905112906112907112908112909112910112911112912112913112914112915112916112917112918112919112920112921112922112923112924112925112926112927112928112929112930112931112932112933112934112935112936112937112938112939112940112941112942112943112944112945112946112947112948112949112950112951112952112953112954112955112956112957112958112959112960112961112962112963112964112965112966112967112968112969112970112971112972112973112974112975112976112977112978112979112980112981112982112983112984112985112986112987112988112989112990112991112992112993112994112995112996112997112998112999113000113001113002113003113004113005113006113007113008113009113010113011113012113013113014113015113016113017113018113019113020113021113022113023113024113025113026113027113028113029113030113031113032113033113034113035113036113037113038113039113040113041113042113043113044113045113046113047113048113049113050113051113052113053113054113055113056113057113058113059113060113061113062113063113064113065113066113067113068113069113070113071113072113073113074113075113076113077113078113079113080113081113082113083113084113085113086113087113088113089113090113091113092113093113094113095113096113097113098113099113100113101113102113103113104113105113106113107113108113109113110113111113112113113113114113115113116113117113118113119113120113121113122113123113124113125113126113127113128113129113130113131113132113133113134113135113136113137113138113139113140113141113142113143113144113145113146113147113148113149113150113151113152113153113154113155113156113157113158113159113160113161113162113163113164113165113166113167113168113169113170113171113172113173113174113175113176113177113178113179113180113181113182113183113184113185113186113187113188113189113190113191113192113193113194113195113196113197113198113199113200113201113202113203113204113205113206113207113208113209113210113211113212113213113214113215113216113217113218113219113220113221113222113223113224113225113226113227113228113229113230113231113232113233113234113235113236113237113238113239113240113241113242113243113244113245113246113247113248113249113250113251113252113253113254113255113256113257113258113259113260113261113262113263113264113265113266113267113268113269113270113271113272113273113274113275113276113277113278113279113280113281113282113283113284113285113286113287113288113289113290113291113292113293113294113295113296113297113298113299113300113301113302113303113304113305113306113307113308113309113310113311113312113313113314113315113316113317113318113319113320113321113322113323113324113325113326113327113328113329113330113331113332113333113334113335113336113337113338113339113340113341113342113343113344113345113346113347113348113349113350113351113352113353113354113355113356113357113358113359113360113361113362113363113364113365113366113367113368113369113370113371113372113373113374113375113376113377113378113379113380113381113382113383113384113385113386113387113388113389113390113391113392113393113394113395113396113397113398113399113400113401113402113403113404113405113406113407113408113409113410113411113412113413113414113415113416113417113418113419113420113421113422113423113424113425113426113427113428113429113430113431113432113433113434113435113436113437113438113439113440113441113442113443113444113445113446113447113448113449113450113451113452113453113454113455113456113457113458113459113460113461113462113463113464113465113466113467113468113469113470113471113472113473113474113475113476113477113478113479113480113481113482113483113484113485113486113487113488113489113490113491113492113493113494113495113496113497113498113499113500113501113502113503113504113505113506113507113508113509113510113511113512113513113514113515113516113517113518113519113520113521113522113523113524113525113526113527113528113529113530113531113532113533113534113535113536113537113538113539113540113541113542113543113544113545113546113547113548113549113550113551113552113553113554113555113556113557113558113559113560113561113562113563113564113565113566113567113568113569113570113571113572113573113574113575113576113577113578113579113580113581113582113583113584113585113586113587113588113589113590113591113592113593113594113595113596113597113598113599113600113601113602113603113604113605113606113607113608113609113610113611113612113613113614113615113616113617113618113619113620113621113622113623113624113625113626113627113628113629113630113631113632113633113634113635113636113637113638113639113640113641113642113643113644113645113646113647113648113649113650113651113652113653113654113655113656113657113658113659113660113661113662113663113664113665113666113667113668113669113670113671113672113673113674113675113676113677113678113679113680113681113682113683113684113685113686113687113688113689113690113691113692113693113694113695113696113697113698113699113700113701113702113703113704113705113706113707113708113709113710113711113712113713113714113715113716113717113718113719113720113721113722113723113724113725113726113727113728113729113730113731113732113733113734113735113736113737113738113739113740113741113742113743113744113745113746113747113748113749113750113751113752113753113754113755113756113757113758113759113760113761113762113763113764113765113766113767113768113769113770113771113772113773113774113775113776113777113778113779113780113781113782113783113784113785113786113787113788113789113790113791113792113793113794113795113796113797113798113799113800113801113802113803113804113805113806113807113808113809113810113811113812113813113814113815113816113817113818113819113820113821113822113823113824113825113826113827113828113829113830113831113832113833113834113835113836113837113838113839113840113841113842113843113844113845113846113847113848113849113850113851113852113853113854113855113856113857113858113859113860113861113862113863113864113865113866113867113868113869113870113871113872113873113874113875113876113877113878113879113880113881113882113883113884113885113886113887113888113889113890113891113892113893113894113895113896113897113898113899113900113901113902113903113904113905113906113907113908113909113910113911113912113913113914113915113916113917113918113919113920113921113922113923113924113925113926113927113928113929113930113931113932113933113934113935113936113937113938113939113940113941113942113943113944113945113946113947113948113949113950113951113952113953113954113955113956113957113958113959113960113961113962113963113964113965113966113967113968113969113970113971113972113973113974113975113976113977113978113979113980113981113982113983113984113985113986113987113988113989113990113991113992113993113994113995113996113997113998113999114000114001114002114003114004114005114006114007114008114009114010114011114012114013114014114015114016114017114018114019114020114021114022114023114024114025114026114027114028114029114030114031114032114033114034114035114036114037114038114039114040114041114042114043114044114045114046114047114048114049114050114051114052114053114054114055114056114057114058114059114060114061114062114063114064114065114066114067114068114069114070114071114072114073114074114075114076114077114078114079114080114081114082114083114084114085114086114087114088114089114090114091114092114093114094114095114096114097114098114099114100114101114102114103114104114105114106114107114108114109114110114111114112114113114114114115114116114117114118114119114120114121114122114123114124114125114126114127114128114129114130114131114132114133114134114135114136114137114138114139114140114141114142114143114144114145114146114147114148114149114150114151114152114153114154114155114156114157114158114159114160114161114162114163114164114165114166114167114168114169114170114171114172114173114174114175114176114177114178114179114180114181114182114183114184114185114186114187114188114189114190114191114192114193114194114195114196114197114198114199114200114201114202114203114204114205114206114207114208114209114210114211114212114213114214114215114216114217114218114219114220114221114222114223114224114225114226114227114228114229114230114231114232114233114234114235114236114237114238114239114240114241114242114243114244114245114246114247114248114249114250114251114252114253114254114255114256114257114258114259114260114261114262114263114264114265114266114267114268114269114270114271114272114273114274114275114276114277114278114279114280114281114282114283114284114285114286114287114288114289114290114291114292114293114294114295114296114297114298114299114300114301114302114303114304114305114306114307114308114309114310114311114312114313114314114315114316114317114318114319114320114321114322114323114324114325114326114327114328114329114330114331114332114333114334114335114336114337114338114339114340114341114342114343114344114345114346114347114348114349114350114351114352114353114354114355114356114357114358114359114360114361114362114363114364114365114366114367114368114369114370114371114372114373114374114375114376114377114378114379114380114381114382114383114384114385114386114387114388114389114390114391114392114393114394114395114396114397114398114399114400114401114402114403114404114405114406114407114408114409114410114411114412114413114414114415114416114417114418114419114420114421114422114423114424114425114426114427114428114429114430114431114432114433114434114435114436114437114438114439114440114441114442114443114444114445114446114447114448114449114450114451114452114453114454114455114456114457114458114459114460114461114462114463114464114465114466114467114468114469114470114471114472114473114474114475114476114477114478114479114480114481114482114483114484114485114486114487114488114489114490114491114492114493114494114495114496114497114498114499114500114501114502114503114504114505114506114507114508114509114510114511114512114513114514114515114516114517114518114519114520114521114522114523114524114525114526114527114528114529114530114531114532114533114534114535114536114537114538114539114540114541114542114543114544114545114546114547114548114549114550114551114552114553114554114555114556114557114558114559114560114561114562114563114564114565114566114567114568114569114570114571114572114573114574114575114576114577114578114579114580114581114582114583114584114585114586114587114588114589114590114591114592114593114594114595114596114597114598114599114600114601114602114603114604114605114606114607114608114609114610114611114612114613114614114615114616114617114618114619114620114621114622114623114624114625114626114627114628114629114630114631114632114633114634114635114636114637114638114639114640114641114642114643114644114645114646114647114648114649114650114651114652114653114654114655114656114657114658114659114660114661114662114663114664114665114666114667114668114669114670114671114672114673114674114675114676114677114678114679114680114681114682114683114684114685114686114687114688114689114690114691114692114693114694114695114696114697114698114699114700114701114702114703114704114705114706114707114708114709114710114711114712114713114714114715114716114717114718114719114720114721114722114723114724114725114726114727114728114729114730114731114732114733114734114735114736114737114738114739114740114741114742114743114744114745114746114747114748114749114750114751114752114753114754114755114756114757114758114759114760114761114762114763114764114765114766114767114768114769114770114771114772114773114774114775114776114777114778114779114780114781114782114783114784114785114786114787114788114789114790114791114792114793114794114795114796114797114798114799114800114801114802114803114804114805114806114807114808114809114810114811114812114813114814114815114816114817114818114819114820114821114822114823114824114825114826114827114828114829114830114831114832114833114834114835114836114837114838114839114840114841114842114843114844114845114846114847114848114849114850114851114852114853114854114855114856114857114858114859114860114861114862114863114864114865114866114867114868114869114870114871114872114873114874114875114876114877114878114879114880114881114882114883114884114885114886114887114888114889114890114891114892114893114894114895114896114897114898114899114900114901114902114903114904114905114906114907114908114909114910114911114912114913114914114915114916114917114918114919114920114921114922114923114924114925114926114927114928114929114930114931114932114933114934114935114936114937114938114939114940114941114942114943114944114945114946114947114948114949114950114951114952114953114954114955114956114957114958114959114960114961114962114963114964114965114966114967114968114969114970114971114972114973114974114975114976114977114978114979114980114981114982114983114984114985114986114987114988114989114990114991114992114993114994114995114996114997114998114999115000115001115002115003115004115005115006115007115008115009115010115011115012115013115014115015115016115017115018115019115020115021115022115023115024115025115026115027115028115029115030115031115032115033115034115035115036115037115038115039115040115041115042115043115044115045115046115047115048115049115050115051115052115053115054115055115056115057115058115059115060115061115062115063115064115065115066115067115068115069115070115071115072115073115074115075115076115077115078115079115080115081115082115083115084115085115086115087115088115089115090115091115092115093115094115095115096115097115098115099115100115101115102115103115104115105115106115107115108115109115110115111115112115113115114115115115116115117115118115119115120115121115122115123115124115125115126115127115128115129115130115131115132115133115134115135115136115137115138115139115140115141115142115143115144115145115146115147115148115149115150115151115152115153115154115155115156115157115158115159115160115161115162115163115164115165115166115167115168115169115170115171115172115173115174115175115176115177115178115179115180115181115182115183115184115185115186115187115188115189115190115191115192115193115194115195115196115197115198115199115200115201115202115203115204115205115206115207115208115209115210115211115212115213115214115215115216115217115218115219115220115221115222115223115224115225115226115227115228115229115230115231115232115233115234115235115236115237115238115239115240115241115242115243115244115245115246115247115248115249115250115251115252115253115254115255115256115257115258115259115260115261115262115263115264115265115266115267115268115269115270115271115272115273115274115275115276115277115278115279115280115281115282115283115284115285115286115287115288115289115290115291115292115293115294115295115296115297115298115299115300115301115302115303115304115305115306115307115308115309115310115311115312115313115314115315115316115317115318115319115320115321115322115323115324115325115326115327115328115329115330115331115332115333115334115335115336115337115338115339115340115341115342115343115344115345115346115347115348115349115350115351115352115353115354115355115356115357115358115359115360115361115362115363115364115365115366115367115368115369115370115371115372115373115374115375115376115377115378115379115380115381115382115383115384115385115386115387115388115389115390115391115392115393115394115395115396115397115398115399115400115401115402115403115404115405115406115407115408115409115410115411115412115413115414115415115416115417115418115419115420115421115422115423115424115425115426115427115428115429115430115431115432115433115434115435115436115437115438115439115440115441115442115443115444115445115446115447115448115449115450115451115452115453115454115455115456115457115458115459115460115461115462115463115464115465115466115467115468115469115470115471115472115473115474115475115476115477115478115479115480115481115482115483115484115485115486115487115488115489115490115491115492115493115494115495115496115497115498115499115500115501115502115503115504115505115506115507115508115509115510115511115512115513115514115515115516115517115518115519115520115521115522115523115524115525115526115527115528115529115530115531115532115533115534115535115536115537115538115539115540115541115542115543115544115545115546115547115548115549115550115551115552115553115554115555115556115557115558115559115560115561115562115563115564115565115566115567115568115569115570115571115572115573115574115575115576115577115578115579115580115581115582115583115584115585115586115587115588115589115590115591115592115593115594115595115596115597115598115599115600115601115602115603115604115605115606115607115608115609115610115611115612115613115614115615115616115617115618115619115620115621115622115623115624115625115626115627115628115629115630115631115632115633115634115635115636115637115638115639115640115641115642115643115644115645115646115647115648115649115650115651115652115653115654115655115656115657115658115659115660115661115662115663115664115665115666115667115668115669115670115671115672115673115674115675115676115677115678115679115680115681115682115683115684115685115686115687115688115689115690115691115692115693115694115695115696115697115698115699115700115701115702115703115704115705115706115707115708115709115710115711115712115713115714115715115716115717115718115719115720115721115722115723115724115725115726115727115728115729115730115731115732115733115734115735115736115737115738115739115740115741115742115743115744115745115746115747115748115749115750115751115752115753115754115755115756115757115758115759115760115761115762115763115764115765115766115767115768115769115770115771115772115773115774115775115776115777115778115779115780115781115782115783115784115785115786115787115788115789115790115791115792115793115794115795115796115797115798115799115800115801115802115803115804115805115806115807115808115809115810115811115812115813115814115815115816115817115818115819115820115821115822115823115824115825115826115827115828115829115830115831115832115833115834115835115836115837115838115839115840115841115842115843115844115845115846115847115848115849115850115851115852115853115854115855115856115857115858115859115860115861115862115863115864115865115866115867115868115869115870115871115872115873115874115875115876115877115878115879115880115881115882115883115884115885115886115887115888115889115890115891115892115893115894115895115896115897115898115899115900115901115902115903115904115905115906115907115908115909115910115911115912115913115914115915115916115917115918115919115920115921115922115923115924115925115926115927115928115929115930115931115932115933115934115935115936115937115938115939115940115941115942115943115944115945115946115947115948115949115950115951115952115953115954115955115956115957115958115959115960115961115962115963115964115965115966115967115968115969115970115971115972115973115974115975115976115977115978115979115980115981115982115983115984115985115986115987115988115989115990115991115992115993115994115995115996115997115998115999116000116001116002116003116004116005116006116007116008116009116010116011116012116013116014116015116016116017116018116019116020116021116022116023116024116025116026116027116028116029116030116031116032116033116034116035116036116037116038116039116040116041116042116043116044116045116046116047116048116049116050116051116052116053116054116055116056116057116058116059116060116061116062116063116064116065116066116067116068116069116070116071116072116073116074116075116076116077116078116079116080116081116082116083116084116085116086116087116088116089116090116091116092116093116094116095116096116097116098116099116100116101116102116103116104116105116106116107116108116109116110116111116112116113116114116115116116116117116118116119116120116121116122116123116124116125116126116127116128116129116130116131116132116133116134116135116136116137116138116139116140116141116142116143116144116145116146116147116148116149116150116151116152116153116154116155116156116157116158116159116160116161116162116163116164116165116166116167116168116169116170116171116172116173116174116175116176116177116178116179116180116181116182116183116184116185116186116187116188116189116190116191116192116193116194116195116196116197116198116199116200116201116202116203116204116205116206116207116208116209116210116211116212116213116214116215116216116217116218116219116220116221116222116223116224116225116226116227116228116229116230116231116232116233116234116235116236116237116238116239116240116241116242116243116244116245116246116247116248116249116250116251116252116253116254116255116256116257116258116259116260116261116262116263116264116265116266116267116268116269116270116271116272116273116274116275116276116277116278116279116280116281116282116283116284116285116286116287116288116289116290116291116292116293116294116295116296116297116298116299116300116301116302116303116304116305116306116307116308116309116310116311116312116313116314116315116316116317116318116319116320116321116322116323116324116325116326116327116328116329116330116331116332116333116334116335116336116337116338116339116340116341116342116343116344116345116346116347116348116349116350116351116352116353116354116355116356116357116358116359116360116361116362116363116364116365116366116367116368116369116370116371116372116373116374116375116376116377116378116379116380116381116382116383116384116385116386116387116388116389116390116391116392116393116394116395116396116397116398116399116400116401116402116403116404116405116406116407116408116409116410116411116412116413116414116415116416116417116418116419116420116421116422116423116424116425116426116427116428116429116430116431116432116433116434116435116436116437116438116439116440116441116442116443116444116445116446116447116448116449116450116451116452116453116454116455116456116457116458116459116460116461116462116463116464116465116466116467116468116469116470116471116472116473116474116475116476116477116478116479116480116481116482116483116484116485116486116487116488116489116490116491116492116493116494116495116496116497116498116499116500116501116502116503116504116505116506116507116508116509116510116511116512116513116514116515116516116517116518116519116520116521116522116523116524116525116526116527116528116529116530116531116532116533116534116535116536116537116538116539116540116541116542116543116544116545116546116547116548116549116550116551116552116553116554116555116556116557116558116559116560116561116562116563116564116565116566116567116568116569116570116571116572116573116574116575116576116577116578116579116580116581116582116583116584116585116586116587116588116589116590116591116592116593116594116595116596116597116598116599116600116601116602116603116604116605116606116607116608116609116610116611116612116613116614116615116616116617116618116619116620116621116622116623116624116625116626116627116628116629116630116631116632116633116634116635116636116637116638116639116640116641116642116643116644116645116646116647116648116649116650116651116652116653116654116655116656116657116658116659116660116661116662116663116664116665116666116667116668116669116670116671116672116673116674116675116676116677116678116679116680116681116682116683116684116685116686116687116688116689116690116691116692116693116694116695116696116697116698116699116700116701116702116703116704116705116706116707116708116709116710116711116712116713116714116715116716116717116718116719116720116721116722116723116724116725116726116727116728116729116730116731116732116733116734116735116736116737116738116739116740116741116742116743116744116745116746116747116748116749116750116751116752116753116754116755116756116757116758116759116760116761116762116763116764116765116766116767116768116769116770116771116772116773116774116775116776116777116778116779116780116781116782116783116784116785116786116787116788116789116790116791116792116793116794116795116796116797116798116799116800116801116802116803116804116805116806116807116808116809116810116811116812116813116814116815116816116817116818116819116820116821116822116823116824116825116826116827116828116829116830116831116832116833116834116835116836116837116838116839116840116841116842116843116844116845116846116847116848116849116850116851116852116853116854116855116856116857116858116859116860116861116862116863116864116865116866116867116868116869116870116871116872116873116874116875116876116877116878116879116880116881116882116883116884116885116886116887116888116889116890116891116892116893116894116895116896116897116898116899116900116901116902116903116904116905116906116907116908116909116910116911116912116913116914116915116916116917116918116919116920116921116922116923116924116925116926116927116928116929116930116931116932116933116934116935116936116937116938116939116940116941116942116943116944116945116946116947116948116949116950116951116952116953116954116955116956116957116958116959116960116961116962116963116964116965116966116967116968116969116970116971116972116973116974116975116976116977116978116979116980116981116982116983116984116985116986116987116988116989116990116991116992116993116994116995116996116997116998116999117000117001117002117003117004117005117006117007117008117009117010117011117012117013117014117015117016117017117018117019117020117021117022117023117024117025117026117027117028117029117030117031117032117033117034117035117036117037117038117039117040117041117042117043117044117045117046117047117048117049117050117051117052117053117054117055117056117057117058117059117060117061117062117063117064117065117066117067117068117069117070117071117072117073117074117075117076117077117078117079117080117081117082117083117084117085117086117087117088117089117090117091117092117093117094117095117096117097117098117099117100117101117102117103117104117105117106117107117108117109117110117111117112117113117114117115117116117117117118117119117120117121117122117123117124117125117126117127117128117129117130117131117132117133117134117135117136117137117138117139117140117141117142117143117144117145117146117147117148117149117150117151117152117153117154117155117156117157117158117159117160117161117162117163117164117165117166117167117168117169117170117171117172117173117174117175117176117177117178117179117180117181117182117183117184117185117186117187117188117189117190117191117192117193117194117195117196117197117198117199117200117201117202117203117204117205117206117207117208117209117210117211117212117213117214117215117216117217117218117219117220117221117222117223117224117225117226117227117228117229117230117231117232117233117234117235117236117237117238117239117240117241117242117243117244117245117246117247117248117249117250117251117252117253117254117255117256117257117258117259117260117261117262117263117264117265117266117267117268117269117270117271117272117273117274117275117276117277117278117279117280117281117282117283117284117285117286117287117288117289117290117291117292117293117294117295117296117297117298117299117300117301117302117303117304117305117306117307117308117309117310117311117312117313117314117315117316117317117318117319117320117321117322117323117324117325117326117327117328117329117330117331117332117333117334117335117336117337117338117339117340117341117342117343117344117345117346117347117348117349117350117351117352117353117354117355117356117357117358117359117360117361117362117363117364117365117366117367117368117369117370117371117372117373117374117375117376117377117378117379117380117381117382117383117384117385117386117387117388117389117390117391117392117393117394117395117396117397117398117399117400117401117402117403117404117405117406117407117408117409117410117411117412117413117414117415117416117417117418117419117420117421117422117423117424117425117426117427117428117429117430117431117432117433117434117435117436117437117438117439117440117441117442117443117444117445117446117447117448117449117450117451117452117453117454117455117456117457117458117459117460117461117462117463117464117465117466117467117468117469117470117471117472117473117474117475117476117477117478117479117480117481117482117483117484117485117486117487117488117489117490117491117492117493117494117495117496117497117498117499117500117501117502117503117504117505117506117507117508117509117510117511117512117513117514117515117516117517117518117519117520117521117522117523117524117525117526117527117528117529117530117531117532117533117534117535117536117537117538117539117540117541117542117543117544117545117546117547117548117549117550117551117552117553117554117555117556117557117558117559117560117561117562117563117564117565117566117567117568117569117570117571117572117573117574117575117576117577117578117579117580117581117582117583117584117585117586117587117588117589117590117591117592117593117594117595117596117597117598117599117600117601117602117603117604117605117606117607117608117609117610117611117612117613117614117615117616117617117618117619117620117621117622117623117624117625117626117627117628117629117630117631117632117633117634117635117636117637117638117639117640117641117642117643117644117645117646117647117648117649117650117651117652117653117654117655117656117657117658117659117660117661117662117663117664117665117666117667117668117669117670117671117672117673117674117675117676117677117678117679117680117681117682117683117684117685117686117687117688117689117690117691117692117693117694117695117696117697117698117699117700117701117702117703117704117705117706117707117708117709117710117711117712117713117714117715117716117717117718117719117720117721117722117723117724117725117726117727117728117729117730117731117732117733117734117735117736117737117738117739117740117741117742117743117744117745117746117747117748117749117750117751117752117753117754117755117756117757117758117759117760117761117762117763117764117765117766117767117768117769117770117771117772117773117774117775117776117777117778117779117780117781117782117783117784117785117786117787117788117789117790117791117792117793117794117795117796117797117798117799117800117801117802117803117804117805117806117807117808117809117810117811117812117813117814117815117816117817117818117819117820117821117822117823117824117825117826117827117828117829117830117831117832117833117834117835117836117837117838117839117840117841117842117843117844117845117846117847117848117849117850117851117852117853117854117855117856117857117858117859117860117861117862117863117864117865117866117867117868117869117870117871117872117873117874117875117876117877117878117879117880117881117882117883117884117885117886117887117888117889117890117891117892117893117894117895117896117897117898117899117900117901117902117903117904117905117906117907117908117909117910117911117912117913117914117915117916117917117918117919117920117921117922117923117924117925117926117927117928117929117930117931117932117933117934117935117936117937117938117939117940117941117942117943117944117945117946117947117948117949117950117951117952117953117954117955117956117957117958117959117960117961117962117963117964117965117966117967117968117969117970117971117972117973117974117975117976117977117978117979117980117981117982117983117984117985117986117987117988117989117990117991117992117993117994117995117996117997117998117999118000118001118002118003118004118005118006118007118008118009118010118011118012118013118014118015118016118017118018118019118020118021118022118023118024118025118026118027118028118029118030118031118032118033118034118035118036118037118038118039118040118041118042118043118044118045118046118047118048118049118050118051118052118053118054118055118056118057118058118059118060118061118062118063118064118065118066118067118068118069118070118071118072118073118074118075118076118077118078118079118080118081118082118083118084118085118086118087118088118089118090118091118092118093118094118095118096118097118098118099118100118101118102118103118104118105118106118107118108118109118110118111118112118113118114118115118116118117118118118119118120118121118122118123118124118125118126118127118128118129118130118131118132118133118134118135118136118137118138118139118140118141118142118143118144118145118146118147118148118149118150118151118152118153118154118155118156118157118158118159118160118161118162118163118164118165118166118167118168118169118170118171118172118173118174118175118176118177118178118179118180118181118182118183118184118185118186118187118188118189118190118191118192118193118194118195118196118197118198118199118200118201118202118203118204118205118206118207118208118209118210118211118212118213118214118215118216118217118218118219118220118221118222118223118224118225118226118227118228118229118230118231118232118233118234118235118236118237118238118239118240118241118242118243118244118245118246118247118248118249118250118251118252118253118254118255118256118257118258118259118260118261118262118263118264118265118266118267118268118269118270118271118272118273118274118275118276118277118278118279118280118281118282118283118284118285118286118287118288118289118290118291118292118293118294118295118296118297118298118299118300118301118302118303118304118305118306118307118308118309118310118311118312118313118314118315118316118317118318118319118320118321118322118323118324118325118326118327118328118329118330118331118332118333118334118335118336118337118338118339118340118341118342118343118344118345118346118347118348118349118350118351118352118353118354118355118356118357118358118359118360118361118362118363118364118365118366118367118368118369118370118371118372118373118374118375118376118377118378118379118380118381118382118383118384118385118386118387118388118389118390118391118392118393118394118395118396118397118398118399118400118401118402118403118404118405118406118407118408118409118410118411118412118413118414118415118416118417118418118419118420118421118422118423118424118425118426118427118428118429118430118431118432118433118434118435118436118437118438118439118440118441118442118443118444118445118446118447118448118449118450118451118452118453118454118455118456118457118458118459118460118461118462118463118464118465118466118467118468118469118470118471118472118473118474118475118476118477118478118479118480118481118482118483118484118485118486118487118488118489118490118491118492118493118494118495118496118497118498118499118500118501118502118503118504118505118506118507118508118509118510118511118512118513118514118515118516118517118518118519118520118521118522118523118524118525118526118527118528118529118530118531118532118533118534118535118536118537118538118539118540118541118542118543118544118545118546118547118548118549118550118551118552118553118554118555118556118557118558118559118560118561118562118563118564118565118566118567118568118569118570118571118572118573118574118575118576118577118578118579118580118581118582118583118584118585118586118587118588118589118590118591118592118593118594118595118596118597118598118599118600118601118602118603118604118605118606118607118608118609118610118611118612118613118614118615118616118617118618118619118620118621118622118623118624118625118626118627118628118629118630118631118632118633118634118635118636118637118638118639118640118641118642118643118644118645118646118647118648118649118650118651118652118653118654118655118656118657118658118659118660118661118662118663118664118665118666118667118668118669118670118671118672118673118674118675118676118677118678118679118680118681118682118683118684118685118686118687118688118689118690118691118692118693118694118695118696118697118698118699118700118701118702118703118704118705118706118707118708118709118710118711118712118713118714118715118716118717118718118719118720118721118722118723118724118725118726118727118728118729118730118731118732118733118734118735118736118737118738118739118740118741118742118743118744118745118746118747118748118749118750118751118752118753118754118755118756118757118758118759118760118761118762118763118764118765118766118767118768118769118770118771118772118773118774118775118776118777118778118779118780118781118782118783118784118785118786118787118788118789118790118791118792118793118794118795118796118797118798118799118800118801118802118803118804118805118806118807118808118809118810118811118812118813118814118815118816118817118818118819118820118821118822118823118824118825118826118827118828118829118830118831118832118833118834118835118836118837118838118839118840118841118842118843118844118845118846118847118848118849118850118851118852118853118854118855118856118857118858118859118860118861118862118863118864118865118866118867118868118869118870118871118872118873118874118875118876118877118878118879118880118881118882118883118884118885118886118887118888118889118890118891118892118893118894118895118896118897118898118899118900118901118902118903118904118905118906118907118908118909118910118911118912118913118914118915118916118917118918118919118920118921118922118923118924118925118926118927118928118929118930118931118932118933118934118935118936118937118938118939118940118941118942118943118944118945118946118947118948118949118950118951118952118953118954118955118956118957118958118959118960118961118962118963118964118965118966118967118968118969118970118971118972118973118974118975118976118977118978118979118980118981118982118983118984118985118986118987118988118989118990118991118992118993118994118995118996118997118998118999119000119001119002119003119004119005119006119007119008119009119010119011119012119013119014119015119016119017119018119019119020119021119022119023119024119025119026119027119028119029119030119031119032119033119034119035119036119037119038119039119040119041119042119043119044119045119046119047119048119049119050119051119052119053119054119055119056119057119058119059119060119061119062119063119064119065119066119067119068119069119070119071119072119073119074119075119076119077119078119079119080119081119082119083119084119085119086119087119088119089119090119091119092119093119094119095119096119097119098119099119100119101119102119103119104119105119106119107119108119109119110119111119112119113119114119115119116119117119118119119119120119121119122119123119124119125119126119127119128119129119130119131119132119133119134119135119136119137119138119139119140119141119142119143119144119145119146119147119148119149119150119151119152119153119154119155119156119157119158119159119160119161119162119163119164119165119166119167119168119169119170119171119172119173119174119175119176119177119178119179119180119181119182119183119184119185119186119187119188119189119190119191119192119193119194119195119196119197119198119199119200119201119202119203119204119205119206119207119208119209119210119211119212119213119214119215119216119217119218119219119220119221119222119223119224119225119226119227119228119229119230119231119232119233119234119235119236119237119238119239119240119241119242119243119244119245119246119247119248119249119250119251119252119253119254119255119256119257119258119259119260119261119262119263119264119265119266119267119268119269119270119271119272119273119274119275119276119277119278119279119280119281119282119283119284119285119286119287119288119289119290119291119292119293119294119295119296119297119298119299119300119301119302119303119304119305119306119307119308119309119310119311119312119313119314119315119316119317119318119319119320119321119322119323119324119325119326119327119328119329119330119331119332119333119334119335119336119337119338119339119340119341119342119343119344119345119346119347119348119349119350119351119352119353119354119355119356119357119358119359119360119361119362119363119364119365119366119367119368119369119370119371119372119373119374119375119376119377119378119379119380119381119382119383119384119385119386119387119388119389119390119391119392119393119394119395119396119397119398119399119400119401119402119403119404119405119406119407119408119409119410119411119412119413119414119415119416119417119418119419119420119421119422119423119424119425119426119427119428119429119430119431119432119433119434119435119436119437119438119439119440119441119442119443119444119445119446119447119448119449119450119451119452119453119454119455119456119457119458119459119460119461119462119463119464119465119466119467119468119469119470119471119472119473119474119475119476119477119478119479119480119481119482119483119484119485119486119487119488119489119490119491119492119493119494119495119496119497119498119499119500119501119502119503119504119505119506119507119508119509119510119511119512119513119514119515119516119517119518119519119520119521119522119523119524119525119526119527119528119529119530119531119532119533119534119535119536119537119538119539119540119541119542119543119544119545119546119547119548119549119550119551119552119553119554119555119556119557119558119559119560119561119562119563119564119565119566119567119568119569119570119571119572119573119574119575119576119577119578119579119580119581119582119583119584119585119586119587119588119589119590119591119592119593119594119595119596119597119598119599119600119601119602119603119604119605119606119607119608119609119610119611119612119613119614119615119616119617119618119619119620119621119622119623119624119625119626119627119628119629119630119631119632119633119634119635119636119637119638119639119640119641119642119643119644119645119646119647119648119649119650119651119652119653119654119655119656119657119658119659119660119661119662119663119664119665119666119667119668119669119670119671119672119673119674119675119676119677119678119679119680119681119682119683119684119685119686119687119688119689119690119691119692119693119694119695119696119697119698119699119700119701119702119703119704119705119706119707119708119709119710119711119712119713119714119715119716119717119718119719119720119721119722119723119724119725119726119727119728119729119730119731119732119733119734119735119736119737119738119739119740119741119742119743119744119745119746119747119748119749119750119751119752119753119754119755119756119757119758119759119760119761119762119763119764119765119766119767119768119769119770119771119772119773119774119775119776119777119778119779119780119781119782119783119784119785119786119787119788119789119790119791119792119793119794119795119796119797119798119799119800119801119802119803119804119805119806119807119808119809119810119811119812119813119814119815119816119817119818119819119820119821119822119823119824119825119826119827119828119829119830119831119832119833119834119835119836119837119838119839119840119841119842119843119844119845119846119847119848119849119850119851119852119853119854119855119856119857119858119859119860119861119862119863119864119865119866119867119868119869119870119871119872119873119874119875119876119877119878119879119880119881119882119883119884119885119886119887119888119889119890119891119892119893119894119895119896119897119898119899119900119901119902119903119904119905119906119907119908119909119910119911119912119913119914119915119916119917119918119919119920119921119922119923119924119925119926119927119928119929119930119931119932119933119934119935119936119937119938119939119940119941119942119943119944119945119946119947119948119949119950119951119952119953119954119955119956119957119958119959119960119961119962119963119964119965119966119967119968119969119970119971119972119973119974119975119976119977119978119979119980119981119982119983119984119985119986119987119988119989119990119991119992119993119994119995119996119997119998119999120000120001120002120003120004120005120006120007120008120009120010120011120012120013120014120015120016120017120018120019120020120021120022120023120024120025120026120027120028120029120030120031120032120033120034120035120036120037120038120039120040120041120042120043120044120045120046120047120048120049120050120051120052120053120054120055120056120057120058120059120060120061120062120063120064120065120066120067120068120069120070120071120072120073120074120075120076120077120078120079120080120081120082120083120084120085120086120087120088120089120090120091120092120093120094120095120096120097120098120099120100120101120102120103120104120105120106120107120108120109120110120111120112120113120114120115120116120117120118120119120120120121120122120123120124120125120126120127120128120129120130120131120132120133120134120135120136120137120138120139120140120141120142120143120144120145120146120147120148120149120150120151120152120153120154120155120156120157120158120159120160120161120162120163120164120165120166120167120168120169120170120171120172120173120174120175120176120177120178120179120180120181120182120183120184120185120186120187120188120189120190120191120192120193120194120195120196120197120198120199120200120201120202120203120204120205120206120207120208120209120210120211120212120213120214120215120216120217120218120219120220120221120222120223120224120225120226120227120228120229120230120231120232120233120234120235120236120237120238120239120240120241120242120243120244120245120246120247120248120249120250120251120252120253120254120255120256120257120258120259120260120261120262120263120264120265120266120267120268120269120270120271120272120273120274120275120276120277120278120279120280120281120282120283120284120285120286120287120288120289120290120291120292120293120294120295120296120297120298120299120300120301120302120303120304120305120306120307120308120309120310120311120312120313120314120315120316120317120318120319120320120321120322120323120324120325120326120327120328120329120330120331120332120333120334120335120336120337120338120339120340120341120342120343120344120345120346120347120348120349120350120351120352120353120354120355120356120357120358120359120360120361120362120363120364120365120366120367120368120369120370120371120372120373120374120375120376120377120378120379120380120381120382120383120384120385120386120387120388120389120390120391120392120393120394120395120396120397120398120399120400120401120402120403120404120405120406120407120408120409120410120411120412120413120414120415120416120417120418120419120420120421120422120423120424120425120426120427120428120429120430120431120432120433120434120435120436120437120438120439120440120441120442120443120444120445120446120447120448120449120450120451120452120453120454120455120456120457120458120459120460120461120462120463120464120465120466120467120468120469120470120471120472120473120474120475120476120477120478120479120480120481120482120483120484120485120486120487120488120489120490120491120492120493120494120495120496120497120498120499120500120501120502120503120504120505120506120507120508120509120510120511120512120513120514120515120516120517120518120519120520120521120522120523120524120525120526120527120528120529120530120531120532120533120534120535120536120537120538120539120540120541120542120543120544120545120546120547120548120549120550120551120552120553120554120555120556120557120558120559120560120561120562120563120564120565120566120567120568120569120570120571120572120573120574120575120576120577120578120579120580120581120582120583120584120585120586120587120588120589120590120591120592120593120594120595120596120597120598120599120600120601120602120603120604120605120606120607120608120609120610120611120612120613120614120615120616120617120618120619120620120621120622120623120624120625120626120627120628120629120630120631120632120633120634120635120636120637120638120639120640120641120642120643120644120645120646120647120648120649120650120651120652120653120654120655120656120657120658120659120660120661120662120663120664120665120666120667120668120669120670120671120672120673120674120675120676120677120678120679120680120681120682120683120684120685120686120687120688120689120690120691120692120693120694120695120696120697120698120699120700120701120702120703120704120705120706120707120708120709120710120711120712120713120714120715120716120717120718120719120720120721120722120723120724120725120726120727120728120729120730120731120732120733120734120735120736120737120738120739120740120741120742120743120744120745120746120747120748120749120750120751120752120753120754120755120756120757120758120759120760120761120762120763120764120765120766120767120768120769120770120771120772120773120774120775120776120777120778120779120780120781120782120783120784120785120786120787120788120789120790120791120792120793120794120795120796120797120798120799120800120801120802120803120804120805120806120807120808120809120810120811120812120813120814120815120816120817120818120819120820120821120822120823120824120825120826120827120828120829120830120831120832120833120834120835120836120837120838120839120840120841120842120843120844120845120846120847120848120849120850120851120852120853120854120855120856120857120858120859120860120861120862120863120864120865120866120867120868120869120870120871120872120873120874120875
  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, -1.0, 0.0)
  3417. * @returns a new down Vector3
  3418. */
  3419. Vector3.Down = function () {
  3420. return new Vector3(0.0, -1.0, 0.0);
  3421. };
  3422. /**
  3423. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3424. * @returns a new forward Vector3
  3425. */
  3426. Vector3.Forward = function () {
  3427. return new Vector3(0.0, 0.0, 1.0);
  3428. };
  3429. /**
  3430. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3431. * @returns a new right Vector3
  3432. */
  3433. Vector3.Right = function () {
  3434. return new Vector3(1.0, 0.0, 0.0);
  3435. };
  3436. /**
  3437. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3438. * @returns a new left Vector3
  3439. */
  3440. Vector3.Left = function () {
  3441. return new Vector3(-1.0, 0.0, 0.0);
  3442. };
  3443. /**
  3444. * Returns a new Vector3 set with the result of the transformation by the given matrix of the given vector.
  3445. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3446. * @param vector defines the Vector3 to transform
  3447. * @param transformation defines the transformation matrix
  3448. * @returns the transformed Vector3
  3449. */
  3450. Vector3.TransformCoordinates = function (vector, transformation) {
  3451. var result = Vector3.Zero();
  3452. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3453. return result;
  3454. };
  3455. /**
  3456. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given vector
  3457. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3458. * @param vector defines the Vector3 to transform
  3459. * @param transformation defines the transformation matrix
  3460. * @param result defines the Vector3 where to store the result
  3461. */
  3462. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3463. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3464. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3465. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3466. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3467. result.x = x / w;
  3468. result.y = y / w;
  3469. result.z = z / w;
  3470. };
  3471. /**
  3472. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given floats (x, y, z)
  3473. * This method computes tranformed coordinates only, not transformed direction vectors
  3474. * @param x define the x coordinate of the source vector
  3475. * @param y define the y coordinate of the source vector
  3476. * @param z define the z coordinate of the source vector
  3477. * @param transformation defines the transformation matrix
  3478. * @param result defines the Vector3 where to store the result
  3479. */
  3480. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3481. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3482. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3483. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3484. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3485. result.x = rx / rw;
  3486. result.y = ry / rw;
  3487. result.z = rz / rw;
  3488. };
  3489. /**
  3490. * Returns a new Vector3 set with the result of the normal transformation by the given matrix of the given vector
  3491. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3492. * @param vector defines the Vector3 to transform
  3493. * @param transformation defines the transformation matrix
  3494. * @returns the new Vector3
  3495. */
  3496. Vector3.TransformNormal = function (vector, transformation) {
  3497. var result = Vector3.Zero();
  3498. Vector3.TransformNormalToRef(vector, transformation, result);
  3499. return result;
  3500. };
  3501. /**
  3502. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector
  3503. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3504. * @param vector defines the Vector3 to transform
  3505. * @param transformation defines the transformation matrix
  3506. * @param result defines the Vector3 where to store the result
  3507. */
  3508. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3509. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3510. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3511. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3512. result.x = x;
  3513. result.y = y;
  3514. result.z = z;
  3515. };
  3516. /**
  3517. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z)
  3518. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3519. * @param x define the x coordinate of the source vector
  3520. * @param y define the y coordinate of the source vector
  3521. * @param z define the z coordinate of the source vector
  3522. * @param transformation defines the transformation matrix
  3523. * @param result defines the Vector3 where to store the result
  3524. */
  3525. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3526. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3527. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3528. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3529. };
  3530. /**
  3531. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3532. * @param value1 defines the first control point
  3533. * @param value2 defines the second control point
  3534. * @param value3 defines the third control point
  3535. * @param value4 defines the fourth control point
  3536. * @param amount defines the amount on the spline to use
  3537. * @returns the new Vector3
  3538. */
  3539. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3540. var squared = amount * amount;
  3541. var cubed = amount * squared;
  3542. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3543. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3544. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3545. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3546. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3547. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3548. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3549. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3550. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3551. return new Vector3(x, y, z);
  3552. };
  3553. /**
  3554. * 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"
  3555. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3556. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3557. * @param value defines the current value
  3558. * @param min defines the lower range value
  3559. * @param max defines the upper range value
  3560. * @returns the new Vector3
  3561. */
  3562. Vector3.Clamp = function (value, min, max) {
  3563. var x = value.x;
  3564. x = (x > max.x) ? max.x : x;
  3565. x = (x < min.x) ? min.x : x;
  3566. var y = value.y;
  3567. y = (y > max.y) ? max.y : y;
  3568. y = (y < min.y) ? min.y : y;
  3569. var z = value.z;
  3570. z = (z > max.z) ? max.z : z;
  3571. z = (z < min.z) ? min.z : z;
  3572. return new Vector3(x, y, z);
  3573. };
  3574. /**
  3575. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3576. * @param value1 defines the first control point
  3577. * @param tangent1 defines the first tangent vector
  3578. * @param value2 defines the second control point
  3579. * @param tangent2 defines the second tangent vector
  3580. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3581. * @returns the new Vector3
  3582. */
  3583. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3584. var squared = amount * amount;
  3585. var cubed = amount * squared;
  3586. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3587. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3588. var part3 = (cubed - (2.0 * squared)) + amount;
  3589. var part4 = cubed - squared;
  3590. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3591. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3592. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3593. return new Vector3(x, y, z);
  3594. };
  3595. /**
  3596. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3597. * @param start defines the start value
  3598. * @param end defines the end value
  3599. * @param amount max defines amount between both (between 0 and 1)
  3600. * @returns the new Vector3
  3601. */
  3602. Vector3.Lerp = function (start, end, amount) {
  3603. var result = new Vector3(0, 0, 0);
  3604. Vector3.LerpToRef(start, end, amount, result);
  3605. return result;
  3606. };
  3607. /**
  3608. * Sets the given vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3609. * @param start defines the start value
  3610. * @param end defines the end value
  3611. * @param amount max defines amount between both (between 0 and 1)
  3612. * @param result defines the Vector3 where to store the result
  3613. */
  3614. Vector3.LerpToRef = function (start, end, amount, result) {
  3615. result.x = start.x + ((end.x - start.x) * amount);
  3616. result.y = start.y + ((end.y - start.y) * amount);
  3617. result.z = start.z + ((end.z - start.z) * amount);
  3618. };
  3619. /**
  3620. * Returns the dot product (float) between the vectors "left" and "right"
  3621. * @param left defines the left operand
  3622. * @param right defines the right operand
  3623. * @returns the dot product
  3624. */
  3625. Vector3.Dot = function (left, right) {
  3626. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3627. };
  3628. /**
  3629. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3630. * The cross product is then orthogonal to both "left" and "right"
  3631. * @param left defines the left operand
  3632. * @param right defines the right operand
  3633. * @returns the cross product
  3634. */
  3635. Vector3.Cross = function (left, right) {
  3636. var result = Vector3.Zero();
  3637. Vector3.CrossToRef(left, right, result);
  3638. return result;
  3639. };
  3640. /**
  3641. * Sets the given vector "result" with the cross product of "left" and "right"
  3642. * The cross product is then orthogonal to both "left" and "right"
  3643. * @param left defines the left operand
  3644. * @param right defines the right operand
  3645. * @param result defines the Vector3 where to store the result
  3646. */
  3647. Vector3.CrossToRef = function (left, right, result) {
  3648. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3649. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3650. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3651. result.copyFrom(MathTmp.Vector3[0]);
  3652. };
  3653. /**
  3654. * Returns a new Vector3 as the normalization of the given vector
  3655. * @param vector defines the Vector3 to normalize
  3656. * @returns the new Vector3
  3657. */
  3658. Vector3.Normalize = function (vector) {
  3659. var result = Vector3.Zero();
  3660. Vector3.NormalizeToRef(vector, result);
  3661. return result;
  3662. };
  3663. /**
  3664. * Sets the given vector "result" with the normalization of the given first vector
  3665. * @param vector defines the Vector3 to normalize
  3666. * @param result defines the Vector3 where to store the result
  3667. */
  3668. Vector3.NormalizeToRef = function (vector, result) {
  3669. result.copyFrom(vector);
  3670. result.normalize();
  3671. };
  3672. /**
  3673. * Project a Vector3 onto screen space
  3674. * @param vector defines the Vector3 to project
  3675. * @param world defines the world matrix to use
  3676. * @param transform defines the transform (view x projection) matrix to use
  3677. * @param viewport defines the screen viewport to use
  3678. * @returns the new Vector3
  3679. */
  3680. Vector3.Project = function (vector, world, transform, viewport) {
  3681. var cw = viewport.width;
  3682. var ch = viewport.height;
  3683. var cx = viewport.x;
  3684. var cy = viewport.y;
  3685. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3686. 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);
  3687. var matrix = MathTmp.Matrix[0];
  3688. world.multiplyToRef(transform, matrix);
  3689. matrix.multiplyToRef(viewportMatrix, matrix);
  3690. return Vector3.TransformCoordinates(vector, matrix);
  3691. };
  3692. /**
  3693. * Unproject from screen space to object space
  3694. * @param source defines the screen space Vector3 to use
  3695. * @param viewportWidth defines the current width of the viewport
  3696. * @param viewportHeight defines the current height of the viewport
  3697. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3698. * @param transform defines the transform (view x projection) matrix to use
  3699. * @returns the new Vector3
  3700. */
  3701. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3702. var matrix = MathTmp.Matrix[0];
  3703. world.multiplyToRef(transform, matrix);
  3704. matrix.invert();
  3705. source.x = source.x / viewportWidth * 2 - 1;
  3706. source.y = -(source.y / viewportHeight * 2 - 1);
  3707. var vector = Vector3.TransformCoordinates(source, matrix);
  3708. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3709. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3710. vector = vector.scale(1.0 / num);
  3711. }
  3712. return vector;
  3713. };
  3714. /**
  3715. * Unproject from screen space to object space
  3716. * @param source defines the screen space Vector3 to use
  3717. * @param viewportWidth defines the current width of the viewport
  3718. * @param viewportHeight defines the current height of the viewport
  3719. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3720. * @param view defines the view matrix to use
  3721. * @param projection defines the projection matrix to use
  3722. * @returns the new Vector3
  3723. */
  3724. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3725. var result = Vector3.Zero();
  3726. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3727. return result;
  3728. };
  3729. /**
  3730. * Unproject from screen space to object space
  3731. * @param source defines the screen space Vector3 to use
  3732. * @param viewportWidth defines the current width of the viewport
  3733. * @param viewportHeight defines the current height of the viewport
  3734. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3735. * @param view defines the view matrix to use
  3736. * @param projection defines the projection matrix to use
  3737. * @param result defines the Vector3 where to store the result
  3738. */
  3739. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3740. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3741. };
  3742. /**
  3743. * Unproject from screen space to object space
  3744. * @param sourceX defines the screen space x coordinate to use
  3745. * @param sourceY defines the screen space y coordinate to use
  3746. * @param sourceZ defines the screen space z coordinate to use
  3747. * @param viewportWidth defines the current width of the viewport
  3748. * @param viewportHeight defines the current height of the viewport
  3749. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3750. * @param view defines the view matrix to use
  3751. * @param projection defines the projection matrix to use
  3752. * @param result defines the Vector3 where to store the result
  3753. */
  3754. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3755. var matrix = MathTmp.Matrix[0];
  3756. world.multiplyToRef(view, matrix);
  3757. matrix.multiplyToRef(projection, matrix);
  3758. matrix.invert();
  3759. var screenSource = MathTmp.Vector3[0];
  3760. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3761. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3762. screenSource.z = 2 * sourceZ - 1.0;
  3763. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3764. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3765. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3766. result.scaleInPlace(1.0 / num);
  3767. }
  3768. };
  3769. /**
  3770. * Gets the minimal coordinate values between two Vector3
  3771. * @param left defines the first operand
  3772. * @param right defines the second operand
  3773. * @returns the new Vector3
  3774. */
  3775. Vector3.Minimize = function (left, right) {
  3776. var min = left.clone();
  3777. min.minimizeInPlace(right);
  3778. return min;
  3779. };
  3780. /**
  3781. * Gets the maximal coordinate values between two Vector3
  3782. * @param left defines the first operand
  3783. * @param right defines the second operand
  3784. * @returns the new Vector3
  3785. */
  3786. Vector3.Maximize = function (left, right) {
  3787. var max = left.clone();
  3788. max.maximizeInPlace(right);
  3789. return max;
  3790. };
  3791. /**
  3792. * Returns the distance between the vectors "value1" and "value2"
  3793. * @param value1 defines the first operand
  3794. * @param value2 defines the second operand
  3795. * @returns the distance
  3796. */
  3797. Vector3.Distance = function (value1, value2) {
  3798. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3799. };
  3800. /**
  3801. * Returns the squared distance between the vectors "value1" and "value2"
  3802. * @param value1 defines the first operand
  3803. * @param value2 defines the second operand
  3804. * @returns the squared distance
  3805. */
  3806. Vector3.DistanceSquared = function (value1, value2) {
  3807. var x = value1.x - value2.x;
  3808. var y = value1.y - value2.y;
  3809. var z = value1.z - value2.z;
  3810. return (x * x) + (y * y) + (z * z);
  3811. };
  3812. /**
  3813. * Returns a new Vector3 located at the center between "value1" and "value2"
  3814. * @param value1 defines the first operand
  3815. * @param value2 defines the second operand
  3816. * @returns the new Vector3
  3817. */
  3818. Vector3.Center = function (value1, value2) {
  3819. var center = value1.add(value2);
  3820. center.scaleInPlace(0.5);
  3821. return center;
  3822. };
  3823. /**
  3824. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3825. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3826. * to something in order to rotate it from its local system to the given target system
  3827. * Note: axis1, axis2 and axis3 are normalized during this operation
  3828. * @param axis1 defines the first axis
  3829. * @param axis2 defines the second axis
  3830. * @param axis3 defines the third axis
  3831. * @returns a new Vector3
  3832. */
  3833. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3834. var rotation = Vector3.Zero();
  3835. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3836. return rotation;
  3837. };
  3838. /**
  3839. * The same than RotationFromAxis but updates the given ref Vector3 parameter instead of returning a new Vector3
  3840. * @param axis1 defines the first axis
  3841. * @param axis2 defines the second axis
  3842. * @param axis3 defines the third axis
  3843. * @param ref defines the Vector3 where to store the result
  3844. */
  3845. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3846. var quat = MathTmp.Quaternion[0];
  3847. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3848. quat.toEulerAnglesToRef(ref);
  3849. };
  3850. return Vector3;
  3851. }());
  3852. BABYLON.Vector3 = Vector3;
  3853. //Vector4 class created for EulerAngle class conversion to Quaternion
  3854. var Vector4 = /** @class */ (function () {
  3855. /**
  3856. * Creates a Vector4 object from the given floats.
  3857. */
  3858. function Vector4(x, y, z, w) {
  3859. this.x = x;
  3860. this.y = y;
  3861. this.z = z;
  3862. this.w = w;
  3863. }
  3864. /**
  3865. * Returns the string with the Vector4 coordinates.
  3866. */
  3867. Vector4.prototype.toString = function () {
  3868. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3869. };
  3870. /**
  3871. * Returns the string "Vector4".
  3872. */
  3873. Vector4.prototype.getClassName = function () {
  3874. return "Vector4";
  3875. };
  3876. /**
  3877. * Returns the Vector4 hash code.
  3878. */
  3879. Vector4.prototype.getHashCode = function () {
  3880. var hash = this.x || 0;
  3881. hash = (hash * 397) ^ (this.y || 0);
  3882. hash = (hash * 397) ^ (this.z || 0);
  3883. hash = (hash * 397) ^ (this.w || 0);
  3884. return hash;
  3885. };
  3886. // Operators
  3887. /**
  3888. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3889. */
  3890. Vector4.prototype.asArray = function () {
  3891. var result = new Array();
  3892. this.toArray(result, 0);
  3893. return result;
  3894. };
  3895. /**
  3896. * Populates the given array from the given index with the Vector4 coordinates.
  3897. * Returns the Vector4.
  3898. */
  3899. Vector4.prototype.toArray = function (array, index) {
  3900. if (index === undefined) {
  3901. index = 0;
  3902. }
  3903. array[index] = this.x;
  3904. array[index + 1] = this.y;
  3905. array[index + 2] = this.z;
  3906. array[index + 3] = this.w;
  3907. return this;
  3908. };
  3909. /**
  3910. * Adds the given vector to the current Vector4.
  3911. * Returns the updated Vector4.
  3912. */
  3913. Vector4.prototype.addInPlace = function (otherVector) {
  3914. this.x += otherVector.x;
  3915. this.y += otherVector.y;
  3916. this.z += otherVector.z;
  3917. this.w += otherVector.w;
  3918. return this;
  3919. };
  3920. /**
  3921. * Returns a new Vector4 as the result of the addition of the current Vector4 and the given one.
  3922. */
  3923. Vector4.prototype.add = function (otherVector) {
  3924. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3925. };
  3926. /**
  3927. * Updates the given vector "result" with the result of the addition of the current Vector4 and the given one.
  3928. * Returns the current Vector4.
  3929. */
  3930. Vector4.prototype.addToRef = function (otherVector, result) {
  3931. result.x = this.x + otherVector.x;
  3932. result.y = this.y + otherVector.y;
  3933. result.z = this.z + otherVector.z;
  3934. result.w = this.w + otherVector.w;
  3935. return this;
  3936. };
  3937. /**
  3938. * Subtract in place the given vector from the current Vector4.
  3939. * Returns the updated Vector4.
  3940. */
  3941. Vector4.prototype.subtractInPlace = function (otherVector) {
  3942. this.x -= otherVector.x;
  3943. this.y -= otherVector.y;
  3944. this.z -= otherVector.z;
  3945. this.w -= otherVector.w;
  3946. return this;
  3947. };
  3948. /**
  3949. * Returns a new Vector4 with the result of the subtraction of the given vector from the current Vector4.
  3950. */
  3951. Vector4.prototype.subtract = function (otherVector) {
  3952. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3953. };
  3954. /**
  3955. * Sets the given vector "result" with the result of the subtraction of the given vector from the current Vector4.
  3956. * Returns the current Vector4.
  3957. */
  3958. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3959. result.x = this.x - otherVector.x;
  3960. result.y = this.y - otherVector.y;
  3961. result.z = this.z - otherVector.z;
  3962. result.w = this.w - otherVector.w;
  3963. return this;
  3964. };
  3965. /**
  3966. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3967. */
  3968. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3969. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3970. };
  3971. /**
  3972. * Sets the given vector "result" set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3973. * Returns the current Vector4.
  3974. */
  3975. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3976. result.x = this.x - x;
  3977. result.y = this.y - y;
  3978. result.z = this.z - z;
  3979. result.w = this.w - w;
  3980. return this;
  3981. };
  3982. /**
  3983. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3984. */
  3985. Vector4.prototype.negate = function () {
  3986. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3987. };
  3988. /**
  3989. * Multiplies the current Vector4 coordinates by scale (float).
  3990. * Returns the updated Vector4.
  3991. */
  3992. Vector4.prototype.scaleInPlace = function (scale) {
  3993. this.x *= scale;
  3994. this.y *= scale;
  3995. this.z *= scale;
  3996. this.w *= scale;
  3997. return this;
  3998. };
  3999. /**
  4000. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  4001. */
  4002. Vector4.prototype.scale = function (scale) {
  4003. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  4004. };
  4005. /**
  4006. * Sets the given vector "result" with the current Vector4 coordinates multiplied by scale (float).
  4007. * Returns the current Vector4.
  4008. */
  4009. Vector4.prototype.scaleToRef = function (scale, result) {
  4010. result.x = this.x * scale;
  4011. result.y = this.y * scale;
  4012. result.z = this.z * scale;
  4013. result.w = this.w * scale;
  4014. return this;
  4015. };
  4016. /**
  4017. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  4018. * @param scale defines the scale factor
  4019. * @param result defines the Vector4 object where to store the result
  4020. * @returns the unmodified current Vector4
  4021. */
  4022. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  4023. result.x += this.x * scale;
  4024. result.y += this.y * scale;
  4025. result.z += this.z * scale;
  4026. result.w += this.w * scale;
  4027. return this;
  4028. };
  4029. /**
  4030. * Boolean : True if the current Vector4 coordinates are stricly equal to the given ones.
  4031. */
  4032. Vector4.prototype.equals = function (otherVector) {
  4033. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  4034. };
  4035. /**
  4036. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the given vector ones.
  4037. */
  4038. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  4039. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  4040. return otherVector
  4041. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  4042. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  4043. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  4044. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  4045. };
  4046. /**
  4047. * Boolean : True if the given floats are strictly equal to the current Vector4 coordinates.
  4048. */
  4049. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  4050. return this.x === x && this.y === y && this.z === z && this.w === w;
  4051. };
  4052. /**
  4053. * Multiplies in place the current Vector4 by the given one.
  4054. * Returns the updated Vector4.
  4055. */
  4056. Vector4.prototype.multiplyInPlace = function (otherVector) {
  4057. this.x *= otherVector.x;
  4058. this.y *= otherVector.y;
  4059. this.z *= otherVector.z;
  4060. this.w *= otherVector.w;
  4061. return this;
  4062. };
  4063. /**
  4064. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the given one.
  4065. */
  4066. Vector4.prototype.multiply = function (otherVector) {
  4067. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  4068. };
  4069. /**
  4070. * Updates the given vector "result" with the multiplication result of the current Vector4 and the given one.
  4071. * Returns the current Vector4.
  4072. */
  4073. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  4074. result.x = this.x * otherVector.x;
  4075. result.y = this.y * otherVector.y;
  4076. result.z = this.z * otherVector.z;
  4077. result.w = this.w * otherVector.w;
  4078. return this;
  4079. };
  4080. /**
  4081. * Returns a new Vector4 set with the multiplication result of the given floats and the current Vector4 coordinates.
  4082. */
  4083. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  4084. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  4085. };
  4086. /**
  4087. * Returns a new Vector4 set with the division result of the current Vector4 by the given one.
  4088. */
  4089. Vector4.prototype.divide = function (otherVector) {
  4090. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  4091. };
  4092. /**
  4093. * Updates the given vector "result" with the division result of the current Vector4 by the given one.
  4094. * Returns the current Vector4.
  4095. */
  4096. Vector4.prototype.divideToRef = function (otherVector, result) {
  4097. result.x = this.x / otherVector.x;
  4098. result.y = this.y / otherVector.y;
  4099. result.z = this.z / otherVector.z;
  4100. result.w = this.w / otherVector.w;
  4101. return this;
  4102. };
  4103. /**
  4104. * Divides the current Vector3 coordinates by the given ones.
  4105. * @returns the updated Vector3.
  4106. */
  4107. Vector4.prototype.divideInPlace = function (otherVector) {
  4108. return this.divideToRef(otherVector, this);
  4109. };
  4110. /**
  4111. * Updates the Vector4 coordinates with the minimum values between its own and the given vector ones
  4112. * @param other defines the second operand
  4113. * @returns the current updated Vector4
  4114. */
  4115. Vector4.prototype.minimizeInPlace = function (other) {
  4116. if (other.x < this.x)
  4117. this.x = other.x;
  4118. if (other.y < this.y)
  4119. this.y = other.y;
  4120. if (other.z < this.z)
  4121. this.z = other.z;
  4122. if (other.w < this.w)
  4123. this.w = other.w;
  4124. return this;
  4125. };
  4126. /**
  4127. * Updates the Vector4 coordinates with the maximum values between its own and the given vector ones
  4128. * @param other defines the second operand
  4129. * @returns the current updated Vector4
  4130. */
  4131. Vector4.prototype.maximizeInPlace = function (other) {
  4132. if (other.x > this.x)
  4133. this.x = other.x;
  4134. if (other.y > this.y)
  4135. this.y = other.y;
  4136. if (other.z > this.z)
  4137. this.z = other.z;
  4138. if (other.w > this.w)
  4139. this.w = other.w;
  4140. return this;
  4141. };
  4142. // Properties
  4143. /**
  4144. * Returns the Vector4 length (float).
  4145. */
  4146. Vector4.prototype.length = function () {
  4147. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4148. };
  4149. /**
  4150. * Returns the Vector4 squared length (float).
  4151. */
  4152. Vector4.prototype.lengthSquared = function () {
  4153. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4154. };
  4155. // Methods
  4156. /**
  4157. * Normalizes in place the Vector4.
  4158. * Returns the updated Vector4.
  4159. */
  4160. Vector4.prototype.normalize = function () {
  4161. var len = this.length();
  4162. if (len === 0)
  4163. return this;
  4164. var num = 1.0 / len;
  4165. this.x *= num;
  4166. this.y *= num;
  4167. this.z *= num;
  4168. this.w *= num;
  4169. return this;
  4170. };
  4171. /**
  4172. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  4173. */
  4174. Vector4.prototype.toVector3 = function () {
  4175. return new Vector3(this.x, this.y, this.z);
  4176. };
  4177. /**
  4178. * Returns a new Vector4 copied from the current one.
  4179. */
  4180. Vector4.prototype.clone = function () {
  4181. return new Vector4(this.x, this.y, this.z, this.w);
  4182. };
  4183. /**
  4184. * Updates the current Vector4 with the given one coordinates.
  4185. * Returns the updated Vector4.
  4186. */
  4187. Vector4.prototype.copyFrom = function (source) {
  4188. this.x = source.x;
  4189. this.y = source.y;
  4190. this.z = source.z;
  4191. this.w = source.w;
  4192. return this;
  4193. };
  4194. /**
  4195. * Updates the current Vector4 coordinates with the given floats.
  4196. * Returns the updated Vector4.
  4197. */
  4198. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  4199. this.x = x;
  4200. this.y = y;
  4201. this.z = z;
  4202. this.w = w;
  4203. return this;
  4204. };
  4205. /**
  4206. * Updates the current Vector4 coordinates with the given floats.
  4207. * Returns the updated Vector4.
  4208. */
  4209. Vector4.prototype.set = function (x, y, z, w) {
  4210. return this.copyFromFloats(x, y, z, w);
  4211. };
  4212. // Statics
  4213. /**
  4214. * Returns a new Vector4 set from the starting index of the given array.
  4215. */
  4216. Vector4.FromArray = function (array, offset) {
  4217. if (!offset) {
  4218. offset = 0;
  4219. }
  4220. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4221. };
  4222. /**
  4223. * Updates the given vector "result" from the starting index of the given array.
  4224. */
  4225. Vector4.FromArrayToRef = function (array, offset, result) {
  4226. result.x = array[offset];
  4227. result.y = array[offset + 1];
  4228. result.z = array[offset + 2];
  4229. result.w = array[offset + 3];
  4230. };
  4231. /**
  4232. * Updates the given vector "result" from the starting index of the given Float32Array.
  4233. */
  4234. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4235. Vector4.FromArrayToRef(array, offset, result);
  4236. };
  4237. /**
  4238. * Updates the given vector "result" coordinates from the given floats.
  4239. */
  4240. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4241. result.x = x;
  4242. result.y = y;
  4243. result.z = z;
  4244. result.w = w;
  4245. };
  4246. /**
  4247. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4248. */
  4249. Vector4.Zero = function () {
  4250. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4251. };
  4252. /**
  4253. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4254. */
  4255. Vector4.One = function () {
  4256. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4257. };
  4258. /**
  4259. * Returns a new normalized Vector4 from the given one.
  4260. */
  4261. Vector4.Normalize = function (vector) {
  4262. var result = Vector4.Zero();
  4263. Vector4.NormalizeToRef(vector, result);
  4264. return result;
  4265. };
  4266. /**
  4267. * Updates the given vector "result" from the normalization of the given one.
  4268. */
  4269. Vector4.NormalizeToRef = function (vector, result) {
  4270. result.copyFrom(vector);
  4271. result.normalize();
  4272. };
  4273. Vector4.Minimize = function (left, right) {
  4274. var min = left.clone();
  4275. min.minimizeInPlace(right);
  4276. return min;
  4277. };
  4278. Vector4.Maximize = function (left, right) {
  4279. var max = left.clone();
  4280. max.maximizeInPlace(right);
  4281. return max;
  4282. };
  4283. /**
  4284. * Returns the distance (float) between the vectors "value1" and "value2".
  4285. */
  4286. Vector4.Distance = function (value1, value2) {
  4287. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4288. };
  4289. /**
  4290. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4291. */
  4292. Vector4.DistanceSquared = function (value1, value2) {
  4293. var x = value1.x - value2.x;
  4294. var y = value1.y - value2.y;
  4295. var z = value1.z - value2.z;
  4296. var w = value1.w - value2.w;
  4297. return (x * x) + (y * y) + (z * z) + (w * w);
  4298. };
  4299. /**
  4300. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4301. */
  4302. Vector4.Center = function (value1, value2) {
  4303. var center = value1.add(value2);
  4304. center.scaleInPlace(0.5);
  4305. return center;
  4306. };
  4307. /**
  4308. * Returns a new Vector4 set with the result of the normal transformation by the given matrix of the given vector.
  4309. * This methods computes transformed normalized direction vectors only.
  4310. */
  4311. Vector4.TransformNormal = function (vector, transformation) {
  4312. var result = Vector4.Zero();
  4313. Vector4.TransformNormalToRef(vector, transformation, result);
  4314. return result;
  4315. };
  4316. /**
  4317. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector.
  4318. * This methods computes transformed normalized direction vectors only.
  4319. */
  4320. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4321. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4322. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4323. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4324. result.x = x;
  4325. result.y = y;
  4326. result.z = z;
  4327. result.w = vector.w;
  4328. };
  4329. /**
  4330. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z, w).
  4331. * This methods computes transformed normalized direction vectors only.
  4332. */
  4333. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4334. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4335. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4336. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4337. result.w = w;
  4338. };
  4339. return Vector4;
  4340. }());
  4341. BABYLON.Vector4 = Vector4;
  4342. var Size = /** @class */ (function () {
  4343. /**
  4344. * Creates a Size object from the given width and height (floats).
  4345. */
  4346. function Size(width, height) {
  4347. this.width = width;
  4348. this.height = height;
  4349. }
  4350. // Returns a string with the Size width and height.
  4351. Size.prototype.toString = function () {
  4352. return "{W: " + this.width + ", H: " + this.height + "}";
  4353. };
  4354. /**
  4355. * Returns the string "Size"
  4356. */
  4357. Size.prototype.getClassName = function () {
  4358. return "Size";
  4359. };
  4360. /**
  4361. * Returns the Size hash code.
  4362. */
  4363. Size.prototype.getHashCode = function () {
  4364. var hash = this.width || 0;
  4365. hash = (hash * 397) ^ (this.height || 0);
  4366. return hash;
  4367. };
  4368. /**
  4369. * Updates the current size from the given one.
  4370. * Returns the updated Size.
  4371. */
  4372. Size.prototype.copyFrom = function (src) {
  4373. this.width = src.width;
  4374. this.height = src.height;
  4375. };
  4376. /**
  4377. * Updates in place the current Size from the given floats.
  4378. * Returns the updated Size.
  4379. */
  4380. Size.prototype.copyFromFloats = function (width, height) {
  4381. this.width = width;
  4382. this.height = height;
  4383. return this;
  4384. };
  4385. /**
  4386. * Updates in place the current Size from the given floats.
  4387. * Returns the updated Size.
  4388. */
  4389. Size.prototype.set = function (width, height) {
  4390. return this.copyFromFloats(width, height);
  4391. };
  4392. /**
  4393. * Returns a new Size set with the multiplication result of the current Size and the given floats.
  4394. */
  4395. Size.prototype.multiplyByFloats = function (w, h) {
  4396. return new Size(this.width * w, this.height * h);
  4397. };
  4398. /**
  4399. * Returns a new Size copied from the given one.
  4400. */
  4401. Size.prototype.clone = function () {
  4402. return new Size(this.width, this.height);
  4403. };
  4404. /**
  4405. * Boolean : True if the current Size and the given one width and height are strictly equal.
  4406. */
  4407. Size.prototype.equals = function (other) {
  4408. if (!other) {
  4409. return false;
  4410. }
  4411. return (this.width === other.width) && (this.height === other.height);
  4412. };
  4413. Object.defineProperty(Size.prototype, "surface", {
  4414. /**
  4415. * Returns the surface of the Size : width * height (float).
  4416. */
  4417. get: function () {
  4418. return this.width * this.height;
  4419. },
  4420. enumerable: true,
  4421. configurable: true
  4422. });
  4423. /**
  4424. * Returns a new Size set to (0.0, 0.0)
  4425. */
  4426. Size.Zero = function () {
  4427. return new Size(0.0, 0.0);
  4428. };
  4429. /**
  4430. * Returns a new Size set as the addition result of the current Size and the given one.
  4431. */
  4432. Size.prototype.add = 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 as the subtraction result of the given one from the current Size.
  4438. */
  4439. Size.prototype.subtract = function (otherSize) {
  4440. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4441. return r;
  4442. };
  4443. /**
  4444. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4445. */
  4446. Size.Lerp = function (start, end, amount) {
  4447. var w = start.width + ((end.width - start.width) * amount);
  4448. var h = start.height + ((end.height - start.height) * amount);
  4449. return new Size(w, h);
  4450. };
  4451. return Size;
  4452. }());
  4453. BABYLON.Size = Size;
  4454. /**
  4455. * Class used to store quaternion data
  4456. * @see https://en.wikipedia.org/wiki/Quaternion
  4457. * @see http://doc.babylonjs.com/features/position,_rotation,_scaling
  4458. */
  4459. var Quaternion = /** @class */ (function () {
  4460. /**
  4461. * Creates a new Quaternion from the given floats
  4462. * @param x defines the first component (0 by default)
  4463. * @param y defines the second component (0 by default)
  4464. * @param z defines the third component (0 by default)
  4465. * @param w defines the fourth component (1.0 by default)
  4466. */
  4467. function Quaternion(
  4468. /** defines the first component (0 by default) */
  4469. x,
  4470. /** defines the second component (0 by default) */
  4471. y,
  4472. /** defines the third component (0 by default) */
  4473. z,
  4474. /** defines the fourth component (1.0 by default) */
  4475. w) {
  4476. if (x === void 0) { x = 0.0; }
  4477. if (y === void 0) { y = 0.0; }
  4478. if (z === void 0) { z = 0.0; }
  4479. if (w === void 0) { w = 1.0; }
  4480. this.x = x;
  4481. this.y = y;
  4482. this.z = z;
  4483. this.w = w;
  4484. }
  4485. /**
  4486. * Gets a string representation for the current quaternion
  4487. * @returns a string with the Quaternion coordinates
  4488. */
  4489. Quaternion.prototype.toString = function () {
  4490. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4491. };
  4492. /**
  4493. * Gets the class name of the quaternion
  4494. * @returns the string "Quaternion"
  4495. */
  4496. Quaternion.prototype.getClassName = function () {
  4497. return "Quaternion";
  4498. };
  4499. /**
  4500. * Gets a hash code for this quaternion
  4501. * @returns the quaternion hash code
  4502. */
  4503. Quaternion.prototype.getHashCode = function () {
  4504. var hash = this.x || 0;
  4505. hash = (hash * 397) ^ (this.y || 0);
  4506. hash = (hash * 397) ^ (this.z || 0);
  4507. hash = (hash * 397) ^ (this.w || 0);
  4508. return hash;
  4509. };
  4510. /**
  4511. * Copy the quaternion to an array
  4512. * @returns a new array populated with 4 elements from the quaternion coordinates
  4513. */
  4514. Quaternion.prototype.asArray = function () {
  4515. return [this.x, this.y, this.z, this.w];
  4516. };
  4517. /**
  4518. * Check if two quaternions are equals
  4519. * @param otherQuaternion defines the second operand
  4520. * @return true if the current quaternion and the given one coordinates are strictly equals
  4521. */
  4522. Quaternion.prototype.equals = function (otherQuaternion) {
  4523. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4524. };
  4525. /**
  4526. * Clone the current quaternion
  4527. * @returns a new quaternion copied from the current one
  4528. */
  4529. Quaternion.prototype.clone = function () {
  4530. return new Quaternion(this.x, this.y, this.z, this.w);
  4531. };
  4532. /**
  4533. * Copy a quaternion to the current one
  4534. * @param other defines the other quaternion
  4535. * @returns the updated current quaternion
  4536. */
  4537. Quaternion.prototype.copyFrom = function (other) {
  4538. this.x = other.x;
  4539. this.y = other.y;
  4540. this.z = other.z;
  4541. this.w = other.w;
  4542. return this;
  4543. };
  4544. /**
  4545. * Updates the current quaternion with the given float coordinates
  4546. * @param x defines the x coordinate
  4547. * @param y defines the y coordinate
  4548. * @param z defines the z coordinate
  4549. * @param w defines the w coordinate
  4550. * @returns the updated current quaternion
  4551. */
  4552. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4553. this.x = x;
  4554. this.y = y;
  4555. this.z = z;
  4556. this.w = w;
  4557. return this;
  4558. };
  4559. /**
  4560. * Updates the current quaternion from the given float coordinates
  4561. * @param x defines the x coordinate
  4562. * @param y defines the y coordinate
  4563. * @param z defines the z coordinate
  4564. * @param w defines the w coordinate
  4565. * @returns the updated current quaternion
  4566. */
  4567. Quaternion.prototype.set = function (x, y, z, w) {
  4568. return this.copyFromFloats(x, y, z, w);
  4569. };
  4570. /**
  4571. * Adds two quaternions
  4572. * @param other defines the second operand
  4573. * @returns a new quaternion as the addition result of the given one and the current quaternion
  4574. */
  4575. Quaternion.prototype.add = function (other) {
  4576. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4577. };
  4578. /**
  4579. * Add a quaternion to the current one
  4580. * @param other defines the quaternion to add
  4581. * @returns the current quaternion
  4582. */
  4583. Quaternion.prototype.addInPlace = function (other) {
  4584. this.x += other.x;
  4585. this.y += other.y;
  4586. this.z += other.z;
  4587. this.w += other.w;
  4588. return this;
  4589. };
  4590. /**
  4591. * Subtract two quaternions
  4592. * @param other defines the second operand
  4593. * @returns a new quaternion as the subtraction result of the given one from the current one
  4594. */
  4595. Quaternion.prototype.subtract = function (other) {
  4596. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4597. };
  4598. /**
  4599. * Multiplies the current quaternion by a scale factor
  4600. * @param value defines the scale factor
  4601. * @returns a new quaternion set by multiplying the current quaternion coordinates by the float "scale"
  4602. */
  4603. Quaternion.prototype.scale = function (value) {
  4604. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4605. };
  4606. /**
  4607. * Scale the current quaternion values by a factor and stores the result to a given quaternion
  4608. * @param scale defines the scale factor
  4609. * @param result defines the Quaternion object where to store the result
  4610. * @returns the unmodified current quaternion
  4611. */
  4612. Quaternion.prototype.scaleToRef = function (scale, result) {
  4613. result.x = this.x * scale;
  4614. result.y = this.y * scale;
  4615. result.z = this.z * scale;
  4616. result.w = this.w * scale;
  4617. return this;
  4618. };
  4619. /**
  4620. * Multiplies in place the current quaternion by a scale factor
  4621. * @param value defines the scale factor
  4622. * @returns the current modified quaternion
  4623. */
  4624. Quaternion.prototype.scaleInPlace = function (value) {
  4625. this.x *= value;
  4626. this.y *= value;
  4627. this.z *= value;
  4628. this.w *= value;
  4629. return this;
  4630. };
  4631. /**
  4632. * Scale the current quaternion values by a factor and add the result to a given quaternion
  4633. * @param scale defines the scale factor
  4634. * @param result defines the Quaternion object where to store the result
  4635. * @returns the unmodified current quaternion
  4636. */
  4637. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4638. result.x += this.x * scale;
  4639. result.y += this.y * scale;
  4640. result.z += this.z * scale;
  4641. result.w += this.w * scale;
  4642. return this;
  4643. };
  4644. /**
  4645. * Multiplies two quaternions
  4646. * @param q1 defines the second operand
  4647. * @returns a new quaternion set as the multiplication result of the current one with the given one "q1"
  4648. */
  4649. Quaternion.prototype.multiply = function (q1) {
  4650. var result = new Quaternion(0, 0, 0, 1.0);
  4651. this.multiplyToRef(q1, result);
  4652. return result;
  4653. };
  4654. /**
  4655. * Sets the given "result" as the the multiplication result of the current one with the given one "q1"
  4656. * @param q1 defines the second operand
  4657. * @param result defines the target quaternion
  4658. * @returns the current quaternion
  4659. */
  4660. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4661. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4662. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4663. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4664. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4665. result.copyFromFloats(x, y, z, w);
  4666. return this;
  4667. };
  4668. /**
  4669. * Updates the current quaternion with the multiplication of itself with the given one "q1"
  4670. * @param q1 defines the second operand
  4671. * @returns the currentupdated quaternion
  4672. */
  4673. Quaternion.prototype.multiplyInPlace = function (q1) {
  4674. this.multiplyToRef(q1, this);
  4675. return this;
  4676. };
  4677. /**
  4678. * Conjugates (1-q) the current quaternion and stores the result in the given quaternion
  4679. * @param ref defines the target quaternion
  4680. * @returns the current quaternion
  4681. */
  4682. Quaternion.prototype.conjugateToRef = function (ref) {
  4683. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4684. return this;
  4685. };
  4686. /**
  4687. * Conjugates in place (1-q) the current quaternion
  4688. * @returns the current updated quaternion
  4689. */
  4690. Quaternion.prototype.conjugateInPlace = function () {
  4691. this.x *= -1;
  4692. this.y *= -1;
  4693. this.z *= -1;
  4694. return this;
  4695. };
  4696. /**
  4697. * Conjugates in place (1-q) the current quaternion
  4698. * @returns a new quaternion
  4699. */
  4700. Quaternion.prototype.conjugate = function () {
  4701. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4702. return result;
  4703. };
  4704. /**
  4705. * Gets length of current quaternion
  4706. * @returns the quaternion length (float)
  4707. */
  4708. Quaternion.prototype.length = function () {
  4709. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4710. };
  4711. /**
  4712. * Normalize in place the current quaternion
  4713. * @returns the current updated quaternion
  4714. */
  4715. Quaternion.prototype.normalize = function () {
  4716. var length = 1.0 / this.length();
  4717. this.x *= length;
  4718. this.y *= length;
  4719. this.z *= length;
  4720. this.w *= length;
  4721. return this;
  4722. };
  4723. /**
  4724. * Returns a new Vector3 set with the Euler angles translated from the current quaternion
  4725. * @param order is a reserved parameter and is ignore for now
  4726. * @returns a new Vector3 containing the Euler angles
  4727. */
  4728. Quaternion.prototype.toEulerAngles = function (order) {
  4729. if (order === void 0) { order = "YZX"; }
  4730. var result = Vector3.Zero();
  4731. this.toEulerAnglesToRef(result, order);
  4732. return result;
  4733. };
  4734. /**
  4735. * Sets the given vector3 "result" with the Euler angles translated from the current quaternion
  4736. * @param result defines the vector which will be filled with the Euler angles
  4737. * @param order is a reserved parameter and is ignore for now
  4738. * @returns the current unchanged quaternion
  4739. */
  4740. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4741. if (order === void 0) { order = "YZX"; }
  4742. var qz = this.z;
  4743. var qx = this.x;
  4744. var qy = this.y;
  4745. var qw = this.w;
  4746. var sqw = qw * qw;
  4747. var sqz = qz * qz;
  4748. var sqx = qx * qx;
  4749. var sqy = qy * qy;
  4750. var zAxisY = qy * qz - qx * qw;
  4751. var limit = .4999999;
  4752. if (zAxisY < -limit) {
  4753. result.y = 2 * Math.atan2(qy, qw);
  4754. result.x = Math.PI / 2;
  4755. result.z = 0;
  4756. }
  4757. else if (zAxisY > limit) {
  4758. result.y = 2 * Math.atan2(qy, qw);
  4759. result.x = -Math.PI / 2;
  4760. result.z = 0;
  4761. }
  4762. else {
  4763. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4764. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4765. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4766. }
  4767. return this;
  4768. };
  4769. /**
  4770. * Updates the given rotation matrix with the current quaternion values
  4771. * @param result defines the target matrix
  4772. * @returns the current unchanged quaternion
  4773. */
  4774. Quaternion.prototype.toRotationMatrix = function (result) {
  4775. var xx = this.x * this.x;
  4776. var yy = this.y * this.y;
  4777. var zz = this.z * this.z;
  4778. var xy = this.x * this.y;
  4779. var zw = this.z * this.w;
  4780. var zx = this.z * this.x;
  4781. var yw = this.y * this.w;
  4782. var yz = this.y * this.z;
  4783. var xw = this.x * this.w;
  4784. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4785. result.m[1] = 2.0 * (xy + zw);
  4786. result.m[2] = 2.0 * (zx - yw);
  4787. result.m[3] = 0;
  4788. result.m[4] = 2.0 * (xy - zw);
  4789. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4790. result.m[6] = 2.0 * (yz + xw);
  4791. result.m[7] = 0;
  4792. result.m[8] = 2.0 * (zx + yw);
  4793. result.m[9] = 2.0 * (yz - xw);
  4794. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4795. result.m[11] = 0;
  4796. result.m[12] = 0;
  4797. result.m[13] = 0;
  4798. result.m[14] = 0;
  4799. result.m[15] = 1.0;
  4800. result._markAsUpdated();
  4801. return this;
  4802. };
  4803. /**
  4804. * Updates the current quaternion from the given rotation matrix values
  4805. * @param matrix defines the source matrix
  4806. * @returns the current updated quaternion
  4807. */
  4808. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4809. Quaternion.FromRotationMatrixToRef(matrix, this);
  4810. return this;
  4811. };
  4812. // Statics
  4813. /**
  4814. * Creates a new quaternion from a rotation matrix
  4815. * @param matrix defines the source matrix
  4816. * @returns a new quaternion created from the given rotation matrix values
  4817. */
  4818. Quaternion.FromRotationMatrix = function (matrix) {
  4819. var result = new Quaternion();
  4820. Quaternion.FromRotationMatrixToRef(matrix, result);
  4821. return result;
  4822. };
  4823. /**
  4824. * Updates the given quaternion with the given rotation matrix values
  4825. * @param matrix defines the source matrix
  4826. * @param result defines the target quaternion
  4827. */
  4828. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4829. var data = matrix.m;
  4830. var m11 = data[0], m12 = data[4], m13 = data[8];
  4831. var m21 = data[1], m22 = data[5], m23 = data[9];
  4832. var m31 = data[2], m32 = data[6], m33 = data[10];
  4833. var trace = m11 + m22 + m33;
  4834. var s;
  4835. if (trace > 0) {
  4836. s = 0.5 / Math.sqrt(trace + 1.0);
  4837. result.w = 0.25 / s;
  4838. result.x = (m32 - m23) * s;
  4839. result.y = (m13 - m31) * s;
  4840. result.z = (m21 - m12) * s;
  4841. }
  4842. else if (m11 > m22 && m11 > m33) {
  4843. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4844. result.w = (m32 - m23) / s;
  4845. result.x = 0.25 * s;
  4846. result.y = (m12 + m21) / s;
  4847. result.z = (m13 + m31) / s;
  4848. }
  4849. else if (m22 > m33) {
  4850. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4851. result.w = (m13 - m31) / s;
  4852. result.x = (m12 + m21) / s;
  4853. result.y = 0.25 * s;
  4854. result.z = (m23 + m32) / s;
  4855. }
  4856. else {
  4857. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4858. result.w = (m21 - m12) / s;
  4859. result.x = (m13 + m31) / s;
  4860. result.y = (m23 + m32) / s;
  4861. result.z = 0.25 * s;
  4862. }
  4863. };
  4864. /**
  4865. * Returns the dot product (float) between the quaternions "left" and "right"
  4866. * @param left defines the left operand
  4867. * @param right defines the right operand
  4868. * @returns the dot product
  4869. */
  4870. Quaternion.Dot = function (left, right) {
  4871. return (left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w);
  4872. };
  4873. /**
  4874. * Checks if the two quaternions are close to each other
  4875. * @param quat0 defines the first quaternion to check
  4876. * @param quat1 defines the second quaternion to check
  4877. * @returns true if the two quaternions are close to each other
  4878. */
  4879. Quaternion.AreClose = function (quat0, quat1) {
  4880. var dot = Quaternion.Dot(quat0, quat1);
  4881. return dot >= 0;
  4882. };
  4883. /**
  4884. * Creates an empty quaternion
  4885. * @returns a new quaternion set to (0.0, 0.0, 0.0)
  4886. */
  4887. Quaternion.Zero = function () {
  4888. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4889. };
  4890. /**
  4891. * Inverse a given quaternion
  4892. * @param q defines the source quaternion
  4893. * @returns a new quaternion as the inverted current quaternion
  4894. */
  4895. Quaternion.Inverse = function (q) {
  4896. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4897. };
  4898. /**
  4899. * Creates an identity quaternion
  4900. * @returns the identity quaternion
  4901. */
  4902. Quaternion.Identity = function () {
  4903. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4904. };
  4905. /**
  4906. * Gets a boolean indicating if the given quaternion is identity
  4907. * @param quaternion defines the quaternion to check
  4908. * @returns true if the quaternion is identity
  4909. */
  4910. Quaternion.IsIdentity = function (quaternion) {
  4911. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4912. };
  4913. /**
  4914. * Creates a quaternion from a rotation around an axis
  4915. * @param axis defines the axis to use
  4916. * @param angle defines the angle to use
  4917. * @returns a new quaternion created from the given axis (Vector3) and angle in radians (float)
  4918. */
  4919. Quaternion.RotationAxis = function (axis, angle) {
  4920. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4921. };
  4922. /**
  4923. * Creates a rotation around an axis and stores it into the given quaternion
  4924. * @param axis defines the axis to use
  4925. * @param angle defines the angle to use
  4926. * @param result defines the target quaternion
  4927. * @returns the target quaternion
  4928. */
  4929. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4930. var sin = Math.sin(angle / 2);
  4931. axis.normalize();
  4932. result.w = Math.cos(angle / 2);
  4933. result.x = axis.x * sin;
  4934. result.y = axis.y * sin;
  4935. result.z = axis.z * sin;
  4936. return result;
  4937. };
  4938. /**
  4939. * Creates a new quaternion from data stored into an array
  4940. * @param array defines the data source
  4941. * @param offset defines the offset in the source array where the data starts
  4942. * @returns a new quaternion
  4943. */
  4944. Quaternion.FromArray = function (array, offset) {
  4945. if (!offset) {
  4946. offset = 0;
  4947. }
  4948. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4949. };
  4950. /**
  4951. * Creates a new quaternion from the given Euler float angles (y, x, z)
  4952. * @param yaw defines the rotation around Y axis
  4953. * @param pitch defines the rotation around X axis
  4954. * @param roll defines the rotation around Z axis
  4955. * @returns the new quaternion
  4956. */
  4957. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4958. var q = new Quaternion();
  4959. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4960. return q;
  4961. };
  4962. /**
  4963. * Creates a new rotation from the given Euler float angles (y, x, z) and stores it in the target quaternion
  4964. * @param yaw defines the rotation around Y axis
  4965. * @param pitch defines the rotation around X axis
  4966. * @param roll defines the rotation around Z axis
  4967. * @param result defines the target quaternion
  4968. */
  4969. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4970. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4971. var halfRoll = roll * 0.5;
  4972. var halfPitch = pitch * 0.5;
  4973. var halfYaw = yaw * 0.5;
  4974. var sinRoll = Math.sin(halfRoll);
  4975. var cosRoll = Math.cos(halfRoll);
  4976. var sinPitch = Math.sin(halfPitch);
  4977. var cosPitch = Math.cos(halfPitch);
  4978. var sinYaw = Math.sin(halfYaw);
  4979. var cosYaw = Math.cos(halfYaw);
  4980. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4981. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4982. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4983. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4984. };
  4985. /**
  4986. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation
  4987. * @param alpha defines the rotation around first axis
  4988. * @param beta defines the rotation around second axis
  4989. * @param gamma defines the rotation around third axis
  4990. * @returns the new quaternion
  4991. */
  4992. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4993. var result = new Quaternion();
  4994. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4995. return result;
  4996. };
  4997. /**
  4998. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation and stores it in the target quaternion
  4999. * @param alpha defines the rotation around first axis
  5000. * @param beta defines the rotation around second axis
  5001. * @param gamma defines the rotation around third axis
  5002. * @param result defines the target quaternion
  5003. */
  5004. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  5005. // Produces a quaternion from Euler angles in the z-x-z orientation
  5006. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  5007. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  5008. var halfBeta = beta * 0.5;
  5009. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  5010. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  5011. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  5012. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  5013. };
  5014. /**
  5015. * 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)
  5016. * @param axis1 defines the first axis
  5017. * @param axis2 defines the second axis
  5018. * @param axis3 defines the third axis
  5019. * @returns the new quaternion
  5020. */
  5021. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3) {
  5022. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  5023. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  5024. return quat;
  5025. };
  5026. /**
  5027. * 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
  5028. * @param axis1 defines the first axis
  5029. * @param axis2 defines the second axis
  5030. * @param axis3 defines the third axis
  5031. * @param ref defines the target quaternion
  5032. */
  5033. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  5034. var rotMat = MathTmp.Matrix[0];
  5035. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  5036. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  5037. };
  5038. /**
  5039. * Interpolates between two quaternions
  5040. * @param left defines first quaternion
  5041. * @param right defines second quaternion
  5042. * @param amount defines the gradient to use
  5043. * @returns the new interpolated quaternion
  5044. */
  5045. Quaternion.Slerp = function (left, right, amount) {
  5046. var result = Quaternion.Identity();
  5047. Quaternion.SlerpToRef(left, right, amount, result);
  5048. return result;
  5049. };
  5050. /**
  5051. * Interpolates between two quaternions and stores it into a target quaternion
  5052. * @param left defines first quaternion
  5053. * @param right defines second quaternion
  5054. * @param amount defines the gradient to use
  5055. * @param result defines the target quaternion
  5056. */
  5057. Quaternion.SlerpToRef = function (left, right, amount, result) {
  5058. var num2;
  5059. var num3;
  5060. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  5061. var flag = false;
  5062. if (num4 < 0) {
  5063. flag = true;
  5064. num4 = -num4;
  5065. }
  5066. if (num4 > 0.999999) {
  5067. num3 = 1 - amount;
  5068. num2 = flag ? -amount : amount;
  5069. }
  5070. else {
  5071. var num5 = Math.acos(num4);
  5072. var num6 = (1.0 / Math.sin(num5));
  5073. num3 = (Math.sin((1.0 - amount) * num5)) * num6;
  5074. num2 = flag ? ((-Math.sin(amount * num5)) * num6) : ((Math.sin(amount * num5)) * num6);
  5075. }
  5076. result.x = (num3 * left.x) + (num2 * right.x);
  5077. result.y = (num3 * left.y) + (num2 * right.y);
  5078. result.z = (num3 * left.z) + (num2 * right.z);
  5079. result.w = (num3 * left.w) + (num2 * right.w);
  5080. };
  5081. /**
  5082. * Interpolate between two quaternions using Hermite interpolation
  5083. * @param value1 defines first quaternion
  5084. * @param tangent1 defines the incoming tangent
  5085. * @param value2 defines second quaternion
  5086. * @param tangent2 defines the outgoing tangent
  5087. * @param amount defines the target quaternion
  5088. * @returns the new interpolated quaternion
  5089. */
  5090. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  5091. var squared = amount * amount;
  5092. var cubed = amount * squared;
  5093. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  5094. var part2 = (-2.0 * cubed) + (3.0 * squared);
  5095. var part3 = (cubed - (2.0 * squared)) + amount;
  5096. var part4 = cubed - squared;
  5097. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  5098. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  5099. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  5100. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  5101. return new Quaternion(x, y, z, w);
  5102. };
  5103. return Quaternion;
  5104. }());
  5105. BABYLON.Quaternion = Quaternion;
  5106. /**
  5107. * Class used to store matrix data (4x4)
  5108. */
  5109. var Matrix = /** @class */ (function () {
  5110. /**
  5111. * Creates an empty matrix (filled with zeros)
  5112. */
  5113. function Matrix() {
  5114. this._isIdentity = false;
  5115. this._isIdentityDirty = true;
  5116. /**
  5117. * Gets or sets the internal data of the matrix
  5118. */
  5119. this.m = new Float32Array(16);
  5120. this._markAsUpdated();
  5121. }
  5122. /** @hidden */
  5123. Matrix.prototype._markAsUpdated = function () {
  5124. this.updateFlag = Matrix._updateFlagSeed++;
  5125. this._isIdentityDirty = true;
  5126. };
  5127. // Properties
  5128. /**
  5129. * Check if the current matrix is indentity
  5130. * @param considerAsTextureMatrix defines if the current matrix must be considered as a texture matrix (3x2)
  5131. * @returns true is the matrix is the identity matrix
  5132. */
  5133. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  5134. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  5135. if (this._isIdentityDirty) {
  5136. this._isIdentityDirty = false;
  5137. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  5138. this._isIdentity = false;
  5139. }
  5140. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  5141. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  5142. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  5143. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  5144. this._isIdentity = false;
  5145. }
  5146. else {
  5147. this._isIdentity = true;
  5148. }
  5149. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  5150. this._isIdentity = false;
  5151. }
  5152. }
  5153. return this._isIdentity;
  5154. };
  5155. /**
  5156. * Gets the determinant of the matrix
  5157. * @returns the matrix determinant
  5158. */
  5159. Matrix.prototype.determinant = function () {
  5160. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  5161. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  5162. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  5163. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  5164. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  5165. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  5166. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  5167. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  5168. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  5169. };
  5170. // Methods
  5171. /**
  5172. * Returns the matrix as a Float32Array
  5173. * @returns the matrix underlying array
  5174. */
  5175. Matrix.prototype.toArray = function () {
  5176. return this.m;
  5177. };
  5178. /**
  5179. * Returns the matrix as a Float32Array
  5180. * @returns the matrix underlying array.
  5181. */
  5182. Matrix.prototype.asArray = function () {
  5183. return this.toArray();
  5184. };
  5185. /**
  5186. * Inverts the current matrix in place
  5187. * @returns the current inverted matrix
  5188. */
  5189. Matrix.prototype.invert = function () {
  5190. this.invertToRef(this);
  5191. return this;
  5192. };
  5193. /**
  5194. * Sets all the matrix elements to zero
  5195. * @returns the current matrix
  5196. */
  5197. Matrix.prototype.reset = function () {
  5198. for (var index = 0; index < 16; index++) {
  5199. this.m[index] = 0.0;
  5200. }
  5201. this._markAsUpdated();
  5202. return this;
  5203. };
  5204. /**
  5205. * Adds the current matrix with a second one
  5206. * @param other defines the matrix to add
  5207. * @returns a new matrix as the addition of the current matrix and the given one
  5208. */
  5209. Matrix.prototype.add = function (other) {
  5210. var result = new Matrix();
  5211. this.addToRef(other, result);
  5212. return result;
  5213. };
  5214. /**
  5215. * Sets the given matrix "result" to the addition of the current matrix and the given one
  5216. * @param other defines the matrix to add
  5217. * @param result defines the target matrix
  5218. * @returns the current matrix
  5219. */
  5220. Matrix.prototype.addToRef = function (other, result) {
  5221. for (var index = 0; index < 16; index++) {
  5222. result.m[index] = this.m[index] + other.m[index];
  5223. }
  5224. result._markAsUpdated();
  5225. return this;
  5226. };
  5227. /**
  5228. * Adds in place the given matrix to the current matrix
  5229. * @param other defines the second operand
  5230. * @returns the current updated matrix
  5231. */
  5232. Matrix.prototype.addToSelf = function (other) {
  5233. for (var index = 0; index < 16; index++) {
  5234. this.m[index] += other.m[index];
  5235. }
  5236. this._markAsUpdated();
  5237. return this;
  5238. };
  5239. /**
  5240. * Sets the given matrix to the current inverted Matrix
  5241. * @param other defines the target matrix
  5242. * @returns the unmodified current matrix
  5243. */
  5244. Matrix.prototype.invertToRef = function (other) {
  5245. var l1 = this.m[0];
  5246. var l2 = this.m[1];
  5247. var l3 = this.m[2];
  5248. var l4 = this.m[3];
  5249. var l5 = this.m[4];
  5250. var l6 = this.m[5];
  5251. var l7 = this.m[6];
  5252. var l8 = this.m[7];
  5253. var l9 = this.m[8];
  5254. var l10 = this.m[9];
  5255. var l11 = this.m[10];
  5256. var l12 = this.m[11];
  5257. var l13 = this.m[12];
  5258. var l14 = this.m[13];
  5259. var l15 = this.m[14];
  5260. var l16 = this.m[15];
  5261. var l17 = (l11 * l16) - (l12 * l15);
  5262. var l18 = (l10 * l16) - (l12 * l14);
  5263. var l19 = (l10 * l15) - (l11 * l14);
  5264. var l20 = (l9 * l16) - (l12 * l13);
  5265. var l21 = (l9 * l15) - (l11 * l13);
  5266. var l22 = (l9 * l14) - (l10 * l13);
  5267. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  5268. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  5269. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  5270. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  5271. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  5272. var l28 = (l7 * l16) - (l8 * l15);
  5273. var l29 = (l6 * l16) - (l8 * l14);
  5274. var l30 = (l6 * l15) - (l7 * l14);
  5275. var l31 = (l5 * l16) - (l8 * l13);
  5276. var l32 = (l5 * l15) - (l7 * l13);
  5277. var l33 = (l5 * l14) - (l6 * l13);
  5278. var l34 = (l7 * l12) - (l8 * l11);
  5279. var l35 = (l6 * l12) - (l8 * l10);
  5280. var l36 = (l6 * l11) - (l7 * l10);
  5281. var l37 = (l5 * l12) - (l8 * l9);
  5282. var l38 = (l5 * l11) - (l7 * l9);
  5283. var l39 = (l5 * l10) - (l6 * l9);
  5284. other.m[0] = l23 * l27;
  5285. other.m[4] = l24 * l27;
  5286. other.m[8] = l25 * l27;
  5287. other.m[12] = l26 * l27;
  5288. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  5289. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  5290. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  5291. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  5292. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  5293. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  5294. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  5295. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  5296. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  5297. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  5298. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  5299. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  5300. other._markAsUpdated();
  5301. return this;
  5302. };
  5303. /**
  5304. * Inserts the translation vector (using 3 floats) in the current matrix
  5305. * @param x defines the 1st component of the translation
  5306. * @param y defines the 2nd component of the translation
  5307. * @param z defines the 3rd component of the translation
  5308. * @returns the current updated matrix
  5309. */
  5310. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  5311. this.m[12] = x;
  5312. this.m[13] = y;
  5313. this.m[14] = z;
  5314. this._markAsUpdated();
  5315. return this;
  5316. };
  5317. /**
  5318. * Inserts the translation vector in the current matrix
  5319. * @param vector3 defines the translation to insert
  5320. * @returns the current updated matrix
  5321. */
  5322. Matrix.prototype.setTranslation = function (vector3) {
  5323. this.m[12] = vector3.x;
  5324. this.m[13] = vector3.y;
  5325. this.m[14] = vector3.z;
  5326. this._markAsUpdated();
  5327. return this;
  5328. };
  5329. /**
  5330. * Gets the translation value of the current matrix
  5331. * @returns a new Vector3 as the extracted translation from the matrix
  5332. */
  5333. Matrix.prototype.getTranslation = function () {
  5334. return new Vector3(this.m[12], this.m[13], this.m[14]);
  5335. };
  5336. /**
  5337. * Fill a Vector3 with the extracted translation from the matrix
  5338. * @param result defines the Vector3 where to store the translation
  5339. * @returns the current matrix
  5340. */
  5341. Matrix.prototype.getTranslationToRef = function (result) {
  5342. result.x = this.m[12];
  5343. result.y = this.m[13];
  5344. result.z = this.m[14];
  5345. return this;
  5346. };
  5347. /**
  5348. * Remove rotation and scaling part from the matrix
  5349. * @returns the updated matrix
  5350. */
  5351. Matrix.prototype.removeRotationAndScaling = function () {
  5352. this.setRowFromFloats(0, 1, 0, 0, 0);
  5353. this.setRowFromFloats(1, 0, 1, 0, 0);
  5354. this.setRowFromFloats(2, 0, 0, 1, 0);
  5355. return this;
  5356. };
  5357. /**
  5358. * Multiply two matrices
  5359. * @param other defines the second operand
  5360. * @returns a new matrix set with the multiplication result of the current Matrix and the given one
  5361. */
  5362. Matrix.prototype.multiply = function (other) {
  5363. var result = new Matrix();
  5364. this.multiplyToRef(other, result);
  5365. return result;
  5366. };
  5367. /**
  5368. * Copy the current matrix from the given one
  5369. * @param other defines the source matrix
  5370. * @returns the current updated matrix
  5371. */
  5372. Matrix.prototype.copyFrom = function (other) {
  5373. for (var index = 0; index < 16; index++) {
  5374. this.m[index] = other.m[index];
  5375. }
  5376. this._markAsUpdated();
  5377. return this;
  5378. };
  5379. /**
  5380. * Populates the given array from the starting index with the current matrix values
  5381. * @param array defines the target array
  5382. * @param offset defines the offset in the target array where to start storing values
  5383. * @returns the current matrix
  5384. */
  5385. Matrix.prototype.copyToArray = function (array, offset) {
  5386. if (offset === void 0) { offset = 0; }
  5387. for (var index = 0; index < 16; index++) {
  5388. array[offset + index] = this.m[index];
  5389. }
  5390. return this;
  5391. };
  5392. /**
  5393. * Sets the given matrix "result" with the multiplication result of the current Matrix and the given one
  5394. * @param other defines the second operand
  5395. * @param result defines the matrix where to store the multiplication
  5396. * @returns the current matrix
  5397. */
  5398. Matrix.prototype.multiplyToRef = function (other, result) {
  5399. this.multiplyToArray(other, result.m, 0);
  5400. result._markAsUpdated();
  5401. return this;
  5402. };
  5403. /**
  5404. * Sets the Float32Array "result" from the given index "offset" with the multiplication of the current matrix and the given one
  5405. * @param other defines the second operand
  5406. * @param result defines the array where to store the multiplication
  5407. * @param offset defines the offset in the target array where to start storing values
  5408. * @returns the current matrix
  5409. */
  5410. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5411. var tm0 = this.m[0];
  5412. var tm1 = this.m[1];
  5413. var tm2 = this.m[2];
  5414. var tm3 = this.m[3];
  5415. var tm4 = this.m[4];
  5416. var tm5 = this.m[5];
  5417. var tm6 = this.m[6];
  5418. var tm7 = this.m[7];
  5419. var tm8 = this.m[8];
  5420. var tm9 = this.m[9];
  5421. var tm10 = this.m[10];
  5422. var tm11 = this.m[11];
  5423. var tm12 = this.m[12];
  5424. var tm13 = this.m[13];
  5425. var tm14 = this.m[14];
  5426. var tm15 = this.m[15];
  5427. var om0 = other.m[0];
  5428. var om1 = other.m[1];
  5429. var om2 = other.m[2];
  5430. var om3 = other.m[3];
  5431. var om4 = other.m[4];
  5432. var om5 = other.m[5];
  5433. var om6 = other.m[6];
  5434. var om7 = other.m[7];
  5435. var om8 = other.m[8];
  5436. var om9 = other.m[9];
  5437. var om10 = other.m[10];
  5438. var om11 = other.m[11];
  5439. var om12 = other.m[12];
  5440. var om13 = other.m[13];
  5441. var om14 = other.m[14];
  5442. var om15 = other.m[15];
  5443. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5444. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5445. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5446. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5447. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5448. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5449. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5450. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5451. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5452. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5453. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5454. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5455. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5456. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5457. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5458. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5459. return this;
  5460. };
  5461. /**
  5462. * Check equality between this matrix and a second one
  5463. * @param value defines the second matrix to compare
  5464. * @returns true is the current matrix and the given one values are strictly equal
  5465. */
  5466. Matrix.prototype.equals = function (value) {
  5467. return value &&
  5468. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5469. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5470. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5471. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5472. };
  5473. /**
  5474. * Clone the current matrix
  5475. * @returns a new matrix from the current matrix
  5476. */
  5477. Matrix.prototype.clone = function () {
  5478. 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]);
  5479. };
  5480. /**
  5481. * Returns the name of the current matrix class
  5482. * @returns the string "Matrix"
  5483. */
  5484. Matrix.prototype.getClassName = function () {
  5485. return "Matrix";
  5486. };
  5487. /**
  5488. * Gets the hash code of the current matrix
  5489. * @returns the hash code
  5490. */
  5491. Matrix.prototype.getHashCode = function () {
  5492. var hash = this.m[0] || 0;
  5493. for (var i = 1; i < 16; i++) {
  5494. hash = (hash * 397) ^ (this.m[i] || 0);
  5495. }
  5496. return hash;
  5497. };
  5498. /**
  5499. * Decomposes the current Matrix into a translation, rotation and scaling components
  5500. * @param scale defines the scale vector3 given as a reference to update
  5501. * @param rotation defines the rotation quaternion given as a reference to update
  5502. * @param translation defines the translation vector3 given as a reference to update
  5503. * @returns true if operation was successful
  5504. */
  5505. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5506. if (translation) {
  5507. translation.x = this.m[12];
  5508. translation.y = this.m[13];
  5509. translation.z = this.m[14];
  5510. }
  5511. scale = scale || MathTmp.Vector3[0];
  5512. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5513. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5514. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5515. if (this.determinant() <= 0) {
  5516. scale.y *= -1;
  5517. }
  5518. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5519. if (rotation) {
  5520. rotation.x = 0;
  5521. rotation.y = 0;
  5522. rotation.z = 0;
  5523. rotation.w = 1;
  5524. }
  5525. return false;
  5526. }
  5527. if (rotation) {
  5528. 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]);
  5529. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5530. }
  5531. return true;
  5532. };
  5533. /**
  5534. * Gets specific row of the matrix
  5535. * @param index defines the number of the row to get
  5536. * @returns the index-th row of the current matrix as a new Vector4
  5537. */
  5538. Matrix.prototype.getRow = function (index) {
  5539. if (index < 0 || index > 3) {
  5540. return null;
  5541. }
  5542. var i = index * 4;
  5543. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5544. };
  5545. /**
  5546. * Sets the index-th row of the current matrix to the vector4 values
  5547. * @param index defines the number of the row to set
  5548. * @param row defines the target vector4
  5549. * @returns the updated current matrix
  5550. */
  5551. Matrix.prototype.setRow = function (index, row) {
  5552. if (index < 0 || index > 3) {
  5553. return this;
  5554. }
  5555. var i = index * 4;
  5556. this.m[i + 0] = row.x;
  5557. this.m[i + 1] = row.y;
  5558. this.m[i + 2] = row.z;
  5559. this.m[i + 3] = row.w;
  5560. this._markAsUpdated();
  5561. return this;
  5562. };
  5563. /**
  5564. * Compute the transpose of the matrix
  5565. * @returns the new transposed matrix
  5566. */
  5567. Matrix.prototype.transpose = function () {
  5568. return Matrix.Transpose(this);
  5569. };
  5570. /**
  5571. * Compute the transpose of the matrix and store it in a given matrix
  5572. * @param result defines the target matrix
  5573. * @returns the current matrix
  5574. */
  5575. Matrix.prototype.transposeToRef = function (result) {
  5576. Matrix.TransposeToRef(this, result);
  5577. return this;
  5578. };
  5579. /**
  5580. * Sets the index-th row of the current matrix with the given 4 x float values
  5581. * @param index defines the row index
  5582. * @param x defines the x component to set
  5583. * @param y defines the y component to set
  5584. * @param z defines the z component to set
  5585. * @param w defines the w component to set
  5586. * @returns the updated current matrix
  5587. */
  5588. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5589. if (index < 0 || index > 3) {
  5590. return this;
  5591. }
  5592. var i = index * 4;
  5593. this.m[i + 0] = x;
  5594. this.m[i + 1] = y;
  5595. this.m[i + 2] = z;
  5596. this.m[i + 3] = w;
  5597. this._markAsUpdated();
  5598. return this;
  5599. };
  5600. /**
  5601. * Compute a new matrix set with the current matrix values multiplied by scale (float)
  5602. * @param scale defines the scale factor
  5603. * @returns a new matrix
  5604. */
  5605. Matrix.prototype.scale = function (scale) {
  5606. var result = new Matrix();
  5607. this.scaleToRef(scale, result);
  5608. return result;
  5609. };
  5610. /**
  5611. * Scale the current matrix values by a factor to a given result matrix
  5612. * @param scale defines the scale factor
  5613. * @param result defines the matrix to store the result
  5614. * @returns the current matrix
  5615. */
  5616. Matrix.prototype.scaleToRef = function (scale, result) {
  5617. for (var index = 0; index < 16; index++) {
  5618. result.m[index] = this.m[index] * scale;
  5619. }
  5620. result._markAsUpdated();
  5621. return this;
  5622. };
  5623. /**
  5624. * Scale the current matrix values by a factor and add the result to a given matrix
  5625. * @param scale defines the scale factor
  5626. * @param result defines the Matrix to store the result
  5627. * @returns the current matrix
  5628. */
  5629. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5630. for (var index = 0; index < 16; index++) {
  5631. result.m[index] += this.m[index] * scale;
  5632. }
  5633. result._markAsUpdated();
  5634. return this;
  5635. };
  5636. /**
  5637. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5638. * @param ref matrix to store the result
  5639. */
  5640. Matrix.prototype.toNormalMatrix = function (ref) {
  5641. this.invertToRef(ref);
  5642. ref.transpose();
  5643. var m = ref.m;
  5644. 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);
  5645. };
  5646. /**
  5647. * Gets only rotation part of the current matrix
  5648. * @returns a new matrix sets to the extracted rotation matrix from the current one
  5649. */
  5650. Matrix.prototype.getRotationMatrix = function () {
  5651. var result = Matrix.Identity();
  5652. this.getRotationMatrixToRef(result);
  5653. return result;
  5654. };
  5655. /**
  5656. * Extracts the rotation matrix from the current one and sets it as the given "result"
  5657. * @param result defines the target matrix to store data to
  5658. * @returns the current matrix
  5659. */
  5660. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5661. var m = this.m;
  5662. var sx = Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5663. var sy = Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5664. var sz = Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5665. if (this.determinant() <= 0) {
  5666. sy *= -1;
  5667. }
  5668. if (sx === 0 || sy === 0 || sz === 0) {
  5669. Matrix.IdentityToRef(result);
  5670. }
  5671. else {
  5672. 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);
  5673. }
  5674. return this;
  5675. };
  5676. // Statics
  5677. /**
  5678. * Creates a matrix from an array
  5679. * @param array defines the source array
  5680. * @param offset defines an offset in the source array
  5681. * @returns a new Matrix set from the starting index of the given array
  5682. */
  5683. Matrix.FromArray = function (array, offset) {
  5684. var result = new Matrix();
  5685. if (!offset) {
  5686. offset = 0;
  5687. }
  5688. Matrix.FromArrayToRef(array, offset, result);
  5689. return result;
  5690. };
  5691. /**
  5692. * Copy the content of an array into a given matrix
  5693. * @param array defines the source array
  5694. * @param offset defines an offset in the source array
  5695. * @param result defines the target matrix
  5696. */
  5697. Matrix.FromArrayToRef = function (array, offset, result) {
  5698. for (var index = 0; index < 16; index++) {
  5699. result.m[index] = array[index + offset];
  5700. }
  5701. result._markAsUpdated();
  5702. };
  5703. /**
  5704. * Stores an array into a matrix after having multiplied each component by a given factor
  5705. * @param array defines the source array
  5706. * @param offset defines the offset in the source array
  5707. * @param scale defines the scaling factor
  5708. * @param result defines the target matrix
  5709. */
  5710. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5711. for (var index = 0; index < 16; index++) {
  5712. result.m[index] = array[index + offset] * scale;
  5713. }
  5714. result._markAsUpdated();
  5715. };
  5716. /**
  5717. * Stores a list of values (16) inside a given matrix
  5718. * @param initialM11 defines 1st value of 1st row
  5719. * @param initialM12 defines 2nd value of 1st row
  5720. * @param initialM13 defines 3rd value of 1st row
  5721. * @param initialM14 defines 4th value of 1st row
  5722. * @param initialM21 defines 1st value of 2nd row
  5723. * @param initialM22 defines 2nd value of 2nd row
  5724. * @param initialM23 defines 3rd value of 2nd row
  5725. * @param initialM24 defines 4th value of 2nd row
  5726. * @param initialM31 defines 1st value of 3rd row
  5727. * @param initialM32 defines 2nd value of 3rd row
  5728. * @param initialM33 defines 3rd value of 3rd row
  5729. * @param initialM34 defines 4th value of 3rd row
  5730. * @param initialM41 defines 1st value of 4th row
  5731. * @param initialM42 defines 2nd value of 4th row
  5732. * @param initialM43 defines 3rd value of 4th row
  5733. * @param initialM44 defines 4th value of 4th row
  5734. * @param result defines the target matrix
  5735. */
  5736. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5737. result.m[0] = initialM11;
  5738. result.m[1] = initialM12;
  5739. result.m[2] = initialM13;
  5740. result.m[3] = initialM14;
  5741. result.m[4] = initialM21;
  5742. result.m[5] = initialM22;
  5743. result.m[6] = initialM23;
  5744. result.m[7] = initialM24;
  5745. result.m[8] = initialM31;
  5746. result.m[9] = initialM32;
  5747. result.m[10] = initialM33;
  5748. result.m[11] = initialM34;
  5749. result.m[12] = initialM41;
  5750. result.m[13] = initialM42;
  5751. result.m[14] = initialM43;
  5752. result.m[15] = initialM44;
  5753. result._markAsUpdated();
  5754. };
  5755. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5756. /**
  5757. * Gets an identity matrix that must not be updated
  5758. */
  5759. get: function () {
  5760. return Matrix._identityReadOnly;
  5761. },
  5762. enumerable: true,
  5763. configurable: true
  5764. });
  5765. /**
  5766. * Creates new matrix from a list of values (16)
  5767. * @param initialM11 defines 1st value of 1st row
  5768. * @param initialM12 defines 2nd value of 1st row
  5769. * @param initialM13 defines 3rd value of 1st row
  5770. * @param initialM14 defines 4th value of 1st row
  5771. * @param initialM21 defines 1st value of 2nd row
  5772. * @param initialM22 defines 2nd value of 2nd row
  5773. * @param initialM23 defines 3rd value of 2nd row
  5774. * @param initialM24 defines 4th value of 2nd row
  5775. * @param initialM31 defines 1st value of 3rd row
  5776. * @param initialM32 defines 2nd value of 3rd row
  5777. * @param initialM33 defines 3rd value of 3rd row
  5778. * @param initialM34 defines 4th value of 3rd row
  5779. * @param initialM41 defines 1st value of 4th row
  5780. * @param initialM42 defines 2nd value of 4th row
  5781. * @param initialM43 defines 3rd value of 4th row
  5782. * @param initialM44 defines 4th value of 4th row
  5783. * @returns the new matrix
  5784. */
  5785. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5786. var result = new Matrix();
  5787. result.m[0] = initialM11;
  5788. result.m[1] = initialM12;
  5789. result.m[2] = initialM13;
  5790. result.m[3] = initialM14;
  5791. result.m[4] = initialM21;
  5792. result.m[5] = initialM22;
  5793. result.m[6] = initialM23;
  5794. result.m[7] = initialM24;
  5795. result.m[8] = initialM31;
  5796. result.m[9] = initialM32;
  5797. result.m[10] = initialM33;
  5798. result.m[11] = initialM34;
  5799. result.m[12] = initialM41;
  5800. result.m[13] = initialM42;
  5801. result.m[14] = initialM43;
  5802. result.m[15] = initialM44;
  5803. return result;
  5804. };
  5805. /**
  5806. * Creates a new matrix composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5807. * @param scale defines the scale vector3
  5808. * @param rotation defines the rotation quaternion
  5809. * @param translation defines the translation vector3
  5810. * @returns a new matrix
  5811. */
  5812. Matrix.Compose = function (scale, rotation, translation) {
  5813. var result = Matrix.Identity();
  5814. Matrix.ComposeToRef(scale, rotation, translation, result);
  5815. return result;
  5816. };
  5817. /**
  5818. * Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5819. * @param scale defines the scale vector3
  5820. * @param rotation defines the rotation quaternion
  5821. * @param translation defines the translation vector3
  5822. * @param result defines the target matrix
  5823. */
  5824. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5825. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5826. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5827. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5828. result.setTranslation(translation);
  5829. };
  5830. /**
  5831. * Creates a new identity matrix
  5832. * @returns a new identity matrix
  5833. */
  5834. Matrix.Identity = function () {
  5835. 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);
  5836. };
  5837. /**
  5838. * Creates a new identity matrix and stores the result in a given matrix
  5839. * @param result defines the target matrix
  5840. */
  5841. Matrix.IdentityToRef = function (result) {
  5842. 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);
  5843. };
  5844. /**
  5845. * Creates a new zero matrix
  5846. * @returns a new zero matrix
  5847. */
  5848. Matrix.Zero = function () {
  5849. 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);
  5850. };
  5851. /**
  5852. * Creates a new rotation matrix for "angle" radians around the X axis
  5853. * @param angle defines the angle (in radians) to use
  5854. * @return the new matrix
  5855. */
  5856. Matrix.RotationX = function (angle) {
  5857. var result = new Matrix();
  5858. Matrix.RotationXToRef(angle, result);
  5859. return result;
  5860. };
  5861. /**
  5862. * Creates a new matrix as the invert of a given matrix
  5863. * @param source defines the source matrix
  5864. * @returns the new matrix
  5865. */
  5866. Matrix.Invert = function (source) {
  5867. var result = new Matrix();
  5868. source.invertToRef(result);
  5869. return result;
  5870. };
  5871. /**
  5872. * Creates a new rotation matrix for "angle" radians around the X axis and stores it in a given matrix
  5873. * @param angle defines the angle (in radians) to use
  5874. * @param result defines the target matrix
  5875. */
  5876. Matrix.RotationXToRef = function (angle, result) {
  5877. var s = Math.sin(angle);
  5878. var c = Math.cos(angle);
  5879. result.m[0] = 1.0;
  5880. result.m[15] = 1.0;
  5881. result.m[5] = c;
  5882. result.m[10] = c;
  5883. result.m[9] = -s;
  5884. result.m[6] = s;
  5885. result.m[1] = 0.0;
  5886. result.m[2] = 0.0;
  5887. result.m[3] = 0.0;
  5888. result.m[4] = 0.0;
  5889. result.m[7] = 0.0;
  5890. result.m[8] = 0.0;
  5891. result.m[11] = 0.0;
  5892. result.m[12] = 0.0;
  5893. result.m[13] = 0.0;
  5894. result.m[14] = 0.0;
  5895. result._markAsUpdated();
  5896. };
  5897. /**
  5898. * Creates a new rotation matrix for "angle" radians around the Y axis
  5899. * @param angle defines the angle (in radians) to use
  5900. * @return the new matrix
  5901. */
  5902. Matrix.RotationY = function (angle) {
  5903. var result = new Matrix();
  5904. Matrix.RotationYToRef(angle, result);
  5905. return result;
  5906. };
  5907. /**
  5908. * Creates a new rotation matrix for "angle" radians around the Y axis and stores it in a given matrix
  5909. * @param angle defines the angle (in radians) to use
  5910. * @param result defines the target matrix
  5911. */
  5912. Matrix.RotationYToRef = function (angle, result) {
  5913. var s = Math.sin(angle);
  5914. var c = Math.cos(angle);
  5915. result.m[5] = 1.0;
  5916. result.m[15] = 1.0;
  5917. result.m[0] = c;
  5918. result.m[2] = -s;
  5919. result.m[8] = s;
  5920. result.m[10] = c;
  5921. result.m[1] = 0.0;
  5922. result.m[3] = 0.0;
  5923. result.m[4] = 0.0;
  5924. result.m[6] = 0.0;
  5925. result.m[7] = 0.0;
  5926. result.m[9] = 0.0;
  5927. result.m[11] = 0.0;
  5928. result.m[12] = 0.0;
  5929. result.m[13] = 0.0;
  5930. result.m[14] = 0.0;
  5931. result._markAsUpdated();
  5932. };
  5933. /**
  5934. * Creates a new rotation matrix for "angle" radians around the Z axis
  5935. * @param angle defines the angle (in radians) to use
  5936. * @return the new matrix
  5937. */
  5938. Matrix.RotationZ = function (angle) {
  5939. var result = new Matrix();
  5940. Matrix.RotationZToRef(angle, result);
  5941. return result;
  5942. };
  5943. /**
  5944. * Creates a new rotation matrix for "angle" radians around the Z axis and stores it in a given matrix
  5945. * @param angle defines the angle (in radians) to use
  5946. * @param result defines the target matrix
  5947. */
  5948. Matrix.RotationZToRef = function (angle, result) {
  5949. var s = Math.sin(angle);
  5950. var c = Math.cos(angle);
  5951. result.m[10] = 1.0;
  5952. result.m[15] = 1.0;
  5953. result.m[0] = c;
  5954. result.m[1] = s;
  5955. result.m[4] = -s;
  5956. result.m[5] = c;
  5957. result.m[2] = 0.0;
  5958. result.m[3] = 0.0;
  5959. result.m[6] = 0.0;
  5960. result.m[7] = 0.0;
  5961. result.m[8] = 0.0;
  5962. result.m[9] = 0.0;
  5963. result.m[11] = 0.0;
  5964. result.m[12] = 0.0;
  5965. result.m[13] = 0.0;
  5966. result.m[14] = 0.0;
  5967. result._markAsUpdated();
  5968. };
  5969. /**
  5970. * Creates a new rotation matrix for "angle" radians around the given axis
  5971. * @param axis defines the axis to use
  5972. * @param angle defines the angle (in radians) to use
  5973. * @return the new matrix
  5974. */
  5975. Matrix.RotationAxis = function (axis, angle) {
  5976. var result = Matrix.Zero();
  5977. Matrix.RotationAxisToRef(axis, angle, result);
  5978. return result;
  5979. };
  5980. /**
  5981. * Creates a new rotation matrix for "angle" radians around the given axis and stores it in a given matrix
  5982. * @param axis defines the axis to use
  5983. * @param angle defines the angle (in radians) to use
  5984. * @param result defines the target matrix
  5985. */
  5986. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5987. var s = Math.sin(-angle);
  5988. var c = Math.cos(-angle);
  5989. var c1 = 1 - c;
  5990. axis.normalize();
  5991. result.m[0] = (axis.x * axis.x) * c1 + c;
  5992. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5993. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5994. result.m[3] = 0.0;
  5995. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5996. result.m[5] = (axis.y * axis.y) * c1 + c;
  5997. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5998. result.m[7] = 0.0;
  5999. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  6000. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  6001. result.m[10] = (axis.z * axis.z) * c1 + c;
  6002. result.m[11] = 0.0;
  6003. result.m[15] = 1.0;
  6004. result._markAsUpdated();
  6005. };
  6006. /**
  6007. * Creates a rotation matrix
  6008. * @param yaw defines the yaw angle in radians (Y axis)
  6009. * @param pitch defines the pitch angle in radians (X axis)
  6010. * @param roll defines the roll angle in radians (X axis)
  6011. * @returns the new rotation matrix
  6012. */
  6013. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  6014. var result = new Matrix();
  6015. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  6016. return result;
  6017. };
  6018. /**
  6019. * Creates a rotation matrix and stores it in a given matrix
  6020. * @param yaw defines the yaw angle in radians (Y axis)
  6021. * @param pitch defines the pitch angle in radians (X axis)
  6022. * @param roll defines the roll angle in radians (X axis)
  6023. * @param result defines the target matrix
  6024. */
  6025. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  6026. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  6027. this._tempQuaternion.toRotationMatrix(result);
  6028. };
  6029. /**
  6030. * Creates a scaling matrix
  6031. * @param x defines the scale factor on X axis
  6032. * @param y defines the scale factor on Y axis
  6033. * @param z defines the scale factor on Z axis
  6034. * @returns the new matrix
  6035. */
  6036. Matrix.Scaling = function (x, y, z) {
  6037. var result = Matrix.Zero();
  6038. Matrix.ScalingToRef(x, y, z, result);
  6039. return result;
  6040. };
  6041. /**
  6042. * Creates a scaling matrix and stores it in a given matrix
  6043. * @param x defines the scale factor on X axis
  6044. * @param y defines the scale factor on Y axis
  6045. * @param z defines the scale factor on Z axis
  6046. * @param result defines the target matrix
  6047. */
  6048. Matrix.ScalingToRef = function (x, y, z, result) {
  6049. result.m[0] = x;
  6050. result.m[1] = 0.0;
  6051. result.m[2] = 0.0;
  6052. result.m[3] = 0.0;
  6053. result.m[4] = 0.0;
  6054. result.m[5] = y;
  6055. result.m[6] = 0.0;
  6056. result.m[7] = 0.0;
  6057. result.m[8] = 0.0;
  6058. result.m[9] = 0.0;
  6059. result.m[10] = z;
  6060. result.m[11] = 0.0;
  6061. result.m[12] = 0.0;
  6062. result.m[13] = 0.0;
  6063. result.m[14] = 0.0;
  6064. result.m[15] = 1.0;
  6065. result._markAsUpdated();
  6066. };
  6067. /**
  6068. * Creates a translation matrix
  6069. * @param x defines the translation on X axis
  6070. * @param y defines the translation on Y axis
  6071. * @param z defines the translationon Z axis
  6072. * @returns the new matrix
  6073. */
  6074. Matrix.Translation = function (x, y, z) {
  6075. var result = Matrix.Identity();
  6076. Matrix.TranslationToRef(x, y, z, result);
  6077. return result;
  6078. };
  6079. /**
  6080. * Creates a translation matrix and stores it in a given matrix
  6081. * @param x defines the translation on X axis
  6082. * @param y defines the translation on Y axis
  6083. * @param z defines the translationon Z axis
  6084. * @param result defines the target matrix
  6085. */
  6086. Matrix.TranslationToRef = function (x, y, z, result) {
  6087. 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);
  6088. };
  6089. /**
  6090. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6091. * @param startValue defines the start value
  6092. * @param endValue defines the end value
  6093. * @param gradient defines the gradient factor
  6094. * @returns the new matrix
  6095. */
  6096. Matrix.Lerp = function (startValue, endValue, gradient) {
  6097. var result = Matrix.Zero();
  6098. Matrix.LerpToRef(startValue, endValue, gradient, result);
  6099. return result;
  6100. };
  6101. /**
  6102. * Set the given matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6103. * @param startValue defines the start value
  6104. * @param endValue defines the end value
  6105. * @param gradient defines the gradient factor
  6106. * @param result defines the Matrix object where to store data
  6107. */
  6108. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  6109. for (var index = 0; index < 16; index++) {
  6110. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  6111. }
  6112. result._markAsUpdated();
  6113. };
  6114. /**
  6115. * Builds a new matrix whose values are computed by:
  6116. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6117. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6118. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6119. * @param startValue defines the first matrix
  6120. * @param endValue defines the second matrix
  6121. * @param gradient defines the gradient between the two matrices
  6122. * @returns the new matrix
  6123. */
  6124. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  6125. var result = Matrix.Zero();
  6126. Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  6127. return result;
  6128. };
  6129. /**
  6130. * Update a matrix to values which are computed by:
  6131. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6132. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6133. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6134. * @param startValue defines the first matrix
  6135. * @param endValue defines the second matrix
  6136. * @param gradient defines the gradient between the two matrices
  6137. * @param result defines the target matrix
  6138. */
  6139. Matrix.DecomposeLerpToRef = function (startValue, endValue, gradient, result) {
  6140. var startScale = MathTmp.Vector3[0];
  6141. var startRotation = MathTmp.Quaternion[0];
  6142. var startTranslation = MathTmp.Vector3[1];
  6143. startValue.decompose(startScale, startRotation, startTranslation);
  6144. var endScale = MathTmp.Vector3[2];
  6145. var endRotation = MathTmp.Quaternion[1];
  6146. var endTranslation = MathTmp.Vector3[3];
  6147. endValue.decompose(endScale, endRotation, endTranslation);
  6148. var resultScale = MathTmp.Vector3[4];
  6149. Vector3.LerpToRef(startScale, endScale, gradient, resultScale);
  6150. var resultRotation = MathTmp.Quaternion[2];
  6151. Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation);
  6152. var resultTranslation = MathTmp.Vector3[5];
  6153. Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation);
  6154. Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result);
  6155. };
  6156. /**
  6157. * 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"
  6158. * This function works in left handed mode
  6159. * @param eye defines the final position of the entity
  6160. * @param target defines where the entity should look at
  6161. * @param up defines the up vector for the entity
  6162. * @returns the new matrix
  6163. */
  6164. Matrix.LookAtLH = function (eye, target, up) {
  6165. var result = Matrix.Zero();
  6166. Matrix.LookAtLHToRef(eye, target, up, result);
  6167. return result;
  6168. };
  6169. /**
  6170. * 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".
  6171. * This function works in left handed mode
  6172. * @param eye defines the final position of the entity
  6173. * @param target defines where the entity should look at
  6174. * @param up defines the up vector for the entity
  6175. * @param result defines the target matrix
  6176. */
  6177. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  6178. // Z axis
  6179. target.subtractToRef(eye, this._zAxis);
  6180. this._zAxis.normalize();
  6181. // X axis
  6182. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6183. if (this._xAxis.lengthSquared() === 0) {
  6184. this._xAxis.x = 1.0;
  6185. }
  6186. else {
  6187. this._xAxis.normalize();
  6188. }
  6189. // Y axis
  6190. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6191. this._yAxis.normalize();
  6192. // Eye angles
  6193. var ex = -Vector3.Dot(this._xAxis, eye);
  6194. var ey = -Vector3.Dot(this._yAxis, eye);
  6195. var ez = -Vector3.Dot(this._zAxis, eye);
  6196. 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);
  6197. };
  6198. /**
  6199. * 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"
  6200. * This function works in right handed mode
  6201. * @param eye defines the final position of the entity
  6202. * @param target defines where the entity should look at
  6203. * @param up defines the up vector for the entity
  6204. * @returns the new matrix
  6205. */
  6206. Matrix.LookAtRH = function (eye, target, up) {
  6207. var result = Matrix.Zero();
  6208. Matrix.LookAtRHToRef(eye, target, up, result);
  6209. return result;
  6210. };
  6211. /**
  6212. * 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".
  6213. * This function works in right handed mode
  6214. * @param eye defines the final position of the entity
  6215. * @param target defines where the entity should look at
  6216. * @param up defines the up vector for the entity
  6217. * @param result defines the target matrix
  6218. */
  6219. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  6220. // Z axis
  6221. eye.subtractToRef(target, this._zAxis);
  6222. this._zAxis.normalize();
  6223. // X axis
  6224. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6225. if (this._xAxis.lengthSquared() === 0) {
  6226. this._xAxis.x = 1.0;
  6227. }
  6228. else {
  6229. this._xAxis.normalize();
  6230. }
  6231. // Y axis
  6232. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6233. this._yAxis.normalize();
  6234. // Eye angles
  6235. var ex = -Vector3.Dot(this._xAxis, eye);
  6236. var ey = -Vector3.Dot(this._yAxis, eye);
  6237. var ez = -Vector3.Dot(this._zAxis, eye);
  6238. 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);
  6239. };
  6240. /**
  6241. * Create a left-handed orthographic projection matrix
  6242. * @param width defines the viewport width
  6243. * @param height defines the viewport height
  6244. * @param znear defines the near clip plane
  6245. * @param zfar defines the far clip plane
  6246. * @returns a new matrix as a left-handed orthographic projection matrix
  6247. */
  6248. Matrix.OrthoLH = function (width, height, znear, zfar) {
  6249. var matrix = Matrix.Zero();
  6250. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  6251. return matrix;
  6252. };
  6253. /**
  6254. * Store a left-handed orthographic projection to a given matrix
  6255. * @param width defines the viewport width
  6256. * @param height defines the viewport height
  6257. * @param znear defines the near clip plane
  6258. * @param zfar defines the far clip plane
  6259. * @param result defines the target matrix
  6260. */
  6261. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  6262. var n = znear;
  6263. var f = zfar;
  6264. var a = 2.0 / width;
  6265. var b = 2.0 / height;
  6266. var c = 2.0 / (f - n);
  6267. var d = -(f + n) / (f - n);
  6268. 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);
  6269. };
  6270. /**
  6271. * Create a left-handed orthographic projection matrix
  6272. * @param left defines the viewport left coordinate
  6273. * @param right defines the viewport right coordinate
  6274. * @param bottom defines the viewport bottom coordinate
  6275. * @param top defines the viewport top coordinate
  6276. * @param znear defines the near clip plane
  6277. * @param zfar defines the far clip plane
  6278. * @returns a new matrix as a left-handed orthographic projection matrix
  6279. */
  6280. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  6281. var matrix = Matrix.Zero();
  6282. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  6283. return matrix;
  6284. };
  6285. /**
  6286. * Stores a left-handed orthographic projection into a given matrix
  6287. * @param left defines the viewport left coordinate
  6288. * @param right defines the viewport right coordinate
  6289. * @param bottom defines the viewport bottom coordinate
  6290. * @param top defines the viewport top coordinate
  6291. * @param znear defines the near clip plane
  6292. * @param zfar defines the far clip plane
  6293. * @param result defines the target matrix
  6294. */
  6295. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6296. var n = znear;
  6297. var f = zfar;
  6298. var a = 2.0 / (right - left);
  6299. var b = 2.0 / (top - bottom);
  6300. var c = 2.0 / (f - n);
  6301. var d = -(f + n) / (f - n);
  6302. var i0 = (left + right) / (left - right);
  6303. var i1 = (top + bottom) / (bottom - top);
  6304. 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);
  6305. };
  6306. /**
  6307. * Creates a right-handed orthographic projection matrix
  6308. * @param left defines the viewport left coordinate
  6309. * @param right defines the viewport right coordinate
  6310. * @param bottom defines the viewport bottom coordinate
  6311. * @param top defines the viewport top coordinate
  6312. * @param znear defines the near clip plane
  6313. * @param zfar defines the far clip plane
  6314. * @returns a new matrix as a right-handed orthographic projection matrix
  6315. */
  6316. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  6317. var matrix = Matrix.Zero();
  6318. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  6319. return matrix;
  6320. };
  6321. /**
  6322. * Stores a right-handed orthographic projection into a given matrix
  6323. * @param left defines the viewport left coordinate
  6324. * @param right defines the viewport right coordinate
  6325. * @param bottom defines the viewport bottom coordinate
  6326. * @param top defines the viewport top coordinate
  6327. * @param znear defines the near clip plane
  6328. * @param zfar defines the far clip plane
  6329. * @param result defines the target matrix
  6330. */
  6331. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6332. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  6333. result.m[10] *= -1.0;
  6334. };
  6335. /**
  6336. * Creates a left-handed perspective projection matrix
  6337. * @param width defines the viewport width
  6338. * @param height defines the viewport height
  6339. * @param znear defines the near clip plane
  6340. * @param zfar defines the far clip plane
  6341. * @returns a new matrix as a left-handed perspective projection matrix
  6342. */
  6343. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  6344. var matrix = Matrix.Zero();
  6345. var n = znear;
  6346. var f = zfar;
  6347. var a = 2.0 * n / width;
  6348. var b = 2.0 * n / height;
  6349. var c = (f + n) / (f - n);
  6350. var d = -2.0 * f * n / (f - n);
  6351. 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);
  6352. return matrix;
  6353. };
  6354. /**
  6355. * Creates a left-handed perspective projection matrix
  6356. * @param fov defines the horizontal field of view
  6357. * @param aspect defines the aspect ratio
  6358. * @param znear defines the near clip plane
  6359. * @param zfar defines the far clip plane
  6360. * @returns a new matrix as a left-handed perspective projection matrix
  6361. */
  6362. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  6363. var matrix = Matrix.Zero();
  6364. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  6365. return matrix;
  6366. };
  6367. /**
  6368. * Stores a left-handed perspective projection into a given matrix
  6369. * @param fov defines the horizontal field of view
  6370. * @param aspect defines the aspect ratio
  6371. * @param znear defines the near clip plane
  6372. * @param zfar defines the far clip plane
  6373. * @param result defines the target matrix
  6374. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6375. */
  6376. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6377. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6378. var n = znear;
  6379. var f = zfar;
  6380. var t = 1.0 / (Math.tan(fov * 0.5));
  6381. var a = isVerticalFovFixed ? (t / aspect) : t;
  6382. var b = isVerticalFovFixed ? t : (t * aspect);
  6383. var c = (f + n) / (f - n);
  6384. var d = -2.0 * f * n / (f - n);
  6385. 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);
  6386. };
  6387. /**
  6388. * Creates a right-handed perspective projection matrix
  6389. * @param fov defines the horizontal field of view
  6390. * @param aspect defines the aspect ratio
  6391. * @param znear defines the near clip plane
  6392. * @param zfar defines the far clip plane
  6393. * @returns a new matrix as a right-handed perspective projection matrix
  6394. */
  6395. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  6396. var matrix = Matrix.Zero();
  6397. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  6398. return matrix;
  6399. };
  6400. /**
  6401. * Stores a right-handed perspective projection into a given matrix
  6402. * @param fov defines the horizontal field of view
  6403. * @param aspect defines the aspect ratio
  6404. * @param znear defines the near clip plane
  6405. * @param zfar defines the far clip plane
  6406. * @param result defines the target matrix
  6407. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6408. */
  6409. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6410. //alternatively this could be expressed as:
  6411. // m = PerspectiveFovLHToRef
  6412. // m[10] *= -1.0;
  6413. // m[11] *= -1.0;
  6414. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6415. var n = znear;
  6416. var f = zfar;
  6417. var t = 1.0 / (Math.tan(fov * 0.5));
  6418. var a = isVerticalFovFixed ? (t / aspect) : t;
  6419. var b = isVerticalFovFixed ? t : (t * aspect);
  6420. var c = -(f + n) / (f - n);
  6421. var d = -2 * f * n / (f - n);
  6422. 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);
  6423. };
  6424. /**
  6425. * Stores a perspective projection for WebVR info a given matrix
  6426. * @param fov defines the field of view
  6427. * @param znear defines the near clip plane
  6428. * @param zfar defines the far clip plane
  6429. * @param result defines the target matrix
  6430. * @param rightHanded defines if the matrix must be in right-handed mode (false by default)
  6431. */
  6432. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  6433. if (rightHanded === void 0) { rightHanded = false; }
  6434. var rightHandedFactor = rightHanded ? -1 : 1;
  6435. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  6436. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  6437. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  6438. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  6439. var xScale = 2.0 / (leftTan + rightTan);
  6440. var yScale = 2.0 / (upTan + downTan);
  6441. result.m[0] = xScale;
  6442. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  6443. result.m[5] = yScale;
  6444. result.m[6] = result.m[7] = 0.0;
  6445. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  6446. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  6447. result.m[10] = -zfar / (znear - zfar);
  6448. result.m[11] = 1.0 * rightHandedFactor;
  6449. result.m[12] = result.m[13] = result.m[15] = 0.0;
  6450. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  6451. result._markAsUpdated();
  6452. };
  6453. /**
  6454. * Computes a complete transformation matrix
  6455. * @param viewport defines the viewport to use
  6456. * @param world defines the world matrix
  6457. * @param view defines the view matrix
  6458. * @param projection defines the projection matrix
  6459. * @param zmin defines the near clip plane
  6460. * @param zmax defines the far clip plane
  6461. * @returns the transformation matrix
  6462. */
  6463. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  6464. var cw = viewport.width;
  6465. var ch = viewport.height;
  6466. var cx = viewport.x;
  6467. var cy = viewport.y;
  6468. 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);
  6469. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  6470. };
  6471. /**
  6472. * Extracts a 2x2 matrix from a given matrix and store the result in a Float32Array
  6473. * @param matrix defines the matrix to use
  6474. * @returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the given matrix
  6475. */
  6476. Matrix.GetAsMatrix2x2 = function (matrix) {
  6477. return new Float32Array([
  6478. matrix.m[0], matrix.m[1],
  6479. matrix.m[4], matrix.m[5]
  6480. ]);
  6481. };
  6482. /**
  6483. * Extracts a 3x3 matrix from a given matrix and store the result in a Float32Array
  6484. * @param matrix defines the matrix to use
  6485. * @returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the given matrix
  6486. */
  6487. Matrix.GetAsMatrix3x3 = function (matrix) {
  6488. return new Float32Array([
  6489. matrix.m[0], matrix.m[1], matrix.m[2],
  6490. matrix.m[4], matrix.m[5], matrix.m[6],
  6491. matrix.m[8], matrix.m[9], matrix.m[10]
  6492. ]);
  6493. };
  6494. /**
  6495. * Compute the transpose of a given matrix
  6496. * @param matrix defines the matrix to transpose
  6497. * @returns the new matrix
  6498. */
  6499. Matrix.Transpose = function (matrix) {
  6500. var result = new Matrix();
  6501. Matrix.TransposeToRef(matrix, result);
  6502. return result;
  6503. };
  6504. /**
  6505. * Compute the transpose of a matrix and store it in a target matrix
  6506. * @param matrix defines the matrix to transpose
  6507. * @param result defines the target matrix
  6508. */
  6509. Matrix.TransposeToRef = function (matrix, result) {
  6510. result.m[0] = matrix.m[0];
  6511. result.m[1] = matrix.m[4];
  6512. result.m[2] = matrix.m[8];
  6513. result.m[3] = matrix.m[12];
  6514. result.m[4] = matrix.m[1];
  6515. result.m[5] = matrix.m[5];
  6516. result.m[6] = matrix.m[9];
  6517. result.m[7] = matrix.m[13];
  6518. result.m[8] = matrix.m[2];
  6519. result.m[9] = matrix.m[6];
  6520. result.m[10] = matrix.m[10];
  6521. result.m[11] = matrix.m[14];
  6522. result.m[12] = matrix.m[3];
  6523. result.m[13] = matrix.m[7];
  6524. result.m[14] = matrix.m[11];
  6525. result.m[15] = matrix.m[15];
  6526. };
  6527. /**
  6528. * Computes a reflection matrix from a plane
  6529. * @param plane defines the reflection plane
  6530. * @returns a new matrix
  6531. */
  6532. Matrix.Reflection = function (plane) {
  6533. var matrix = new Matrix();
  6534. Matrix.ReflectionToRef(plane, matrix);
  6535. return matrix;
  6536. };
  6537. /**
  6538. * Computes a reflection matrix from a plane
  6539. * @param plane defines the reflection plane
  6540. * @param result defines the target matrix
  6541. */
  6542. Matrix.ReflectionToRef = function (plane, result) {
  6543. plane.normalize();
  6544. var x = plane.normal.x;
  6545. var y = plane.normal.y;
  6546. var z = plane.normal.z;
  6547. var temp = -2 * x;
  6548. var temp2 = -2 * y;
  6549. var temp3 = -2 * z;
  6550. result.m[0] = (temp * x) + 1;
  6551. result.m[1] = temp2 * x;
  6552. result.m[2] = temp3 * x;
  6553. result.m[3] = 0.0;
  6554. result.m[4] = temp * y;
  6555. result.m[5] = (temp2 * y) + 1;
  6556. result.m[6] = temp3 * y;
  6557. result.m[7] = 0.0;
  6558. result.m[8] = temp * z;
  6559. result.m[9] = temp2 * z;
  6560. result.m[10] = (temp3 * z) + 1;
  6561. result.m[11] = 0.0;
  6562. result.m[12] = temp * plane.d;
  6563. result.m[13] = temp2 * plane.d;
  6564. result.m[14] = temp3 * plane.d;
  6565. result.m[15] = 1.0;
  6566. result._markAsUpdated();
  6567. };
  6568. /**
  6569. * Sets the given matrix as a rotation matrix composed from the 3 left handed axes
  6570. * @param xaxis defines the value of the 1st axis
  6571. * @param yaxis defines the value of the 2nd axis
  6572. * @param zaxis defines the value of the 3rd axis
  6573. * @param result defines the target matrix
  6574. */
  6575. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  6576. result.m[0] = xaxis.x;
  6577. result.m[1] = xaxis.y;
  6578. result.m[2] = xaxis.z;
  6579. result.m[3] = 0.0;
  6580. result.m[4] = yaxis.x;
  6581. result.m[5] = yaxis.y;
  6582. result.m[6] = yaxis.z;
  6583. result.m[7] = 0.0;
  6584. result.m[8] = zaxis.x;
  6585. result.m[9] = zaxis.y;
  6586. result.m[10] = zaxis.z;
  6587. result.m[11] = 0.0;
  6588. result.m[12] = 0.0;
  6589. result.m[13] = 0.0;
  6590. result.m[14] = 0.0;
  6591. result.m[15] = 1.0;
  6592. result._markAsUpdated();
  6593. };
  6594. /**
  6595. * Creates a rotation matrix from a quaternion and stores it in a target matrix
  6596. * @param quat defines the quaternion to use
  6597. * @param result defines the target matrix
  6598. */
  6599. Matrix.FromQuaternionToRef = function (quat, result) {
  6600. var xx = quat.x * quat.x;
  6601. var yy = quat.y * quat.y;
  6602. var zz = quat.z * quat.z;
  6603. var xy = quat.x * quat.y;
  6604. var zw = quat.z * quat.w;
  6605. var zx = quat.z * quat.x;
  6606. var yw = quat.y * quat.w;
  6607. var yz = quat.y * quat.z;
  6608. var xw = quat.x * quat.w;
  6609. result.m[0] = 1.0 - (2.0 * (yy + zz));
  6610. result.m[1] = 2.0 * (xy + zw);
  6611. result.m[2] = 2.0 * (zx - yw);
  6612. result.m[3] = 0.0;
  6613. result.m[4] = 2.0 * (xy - zw);
  6614. result.m[5] = 1.0 - (2.0 * (zz + xx));
  6615. result.m[6] = 2.0 * (yz + xw);
  6616. result.m[7] = 0.0;
  6617. result.m[8] = 2.0 * (zx + yw);
  6618. result.m[9] = 2.0 * (yz - xw);
  6619. result.m[10] = 1.0 - (2.0 * (yy + xx));
  6620. result.m[11] = 0.0;
  6621. result.m[12] = 0.0;
  6622. result.m[13] = 0.0;
  6623. result.m[14] = 0.0;
  6624. result.m[15] = 1.0;
  6625. result._markAsUpdated();
  6626. };
  6627. Matrix._tempQuaternion = new Quaternion();
  6628. Matrix._xAxis = Vector3.Zero();
  6629. Matrix._yAxis = Vector3.Zero();
  6630. Matrix._zAxis = Vector3.Zero();
  6631. Matrix._updateFlagSeed = 0;
  6632. Matrix._identityReadOnly = Matrix.Identity();
  6633. return Matrix;
  6634. }());
  6635. BABYLON.Matrix = Matrix;
  6636. var Plane = /** @class */ (function () {
  6637. /**
  6638. * Creates a Plane object according to the given floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  6639. */
  6640. function Plane(a, b, c, d) {
  6641. this.normal = new Vector3(a, b, c);
  6642. this.d = d;
  6643. }
  6644. /**
  6645. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  6646. */
  6647. Plane.prototype.asArray = function () {
  6648. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  6649. };
  6650. // Methods
  6651. /**
  6652. * Returns a new plane copied from the current Plane.
  6653. */
  6654. Plane.prototype.clone = function () {
  6655. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  6656. };
  6657. /**
  6658. * Returns the string "Plane".
  6659. */
  6660. Plane.prototype.getClassName = function () {
  6661. return "Plane";
  6662. };
  6663. /**
  6664. * Returns the Plane hash code.
  6665. */
  6666. Plane.prototype.getHashCode = function () {
  6667. var hash = this.normal.getHashCode();
  6668. hash = (hash * 397) ^ (this.d || 0);
  6669. return hash;
  6670. };
  6671. /**
  6672. * Normalize the current Plane in place.
  6673. * Returns the updated Plane.
  6674. */
  6675. Plane.prototype.normalize = function () {
  6676. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  6677. var magnitude = 0.0;
  6678. if (norm !== 0) {
  6679. magnitude = 1.0 / norm;
  6680. }
  6681. this.normal.x *= magnitude;
  6682. this.normal.y *= magnitude;
  6683. this.normal.z *= magnitude;
  6684. this.d *= magnitude;
  6685. return this;
  6686. };
  6687. /**
  6688. * Returns a new Plane as the result of the transformation of the current Plane by the given matrix.
  6689. */
  6690. Plane.prototype.transform = function (transformation) {
  6691. var transposedMatrix = Matrix.Transpose(transformation);
  6692. var x = this.normal.x;
  6693. var y = this.normal.y;
  6694. var z = this.normal.z;
  6695. var d = this.d;
  6696. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6697. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6698. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6699. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6700. return new Plane(normalX, normalY, normalZ, finalD);
  6701. };
  6702. /**
  6703. * Returns the dot product (float) of the point coordinates and the plane normal.
  6704. */
  6705. Plane.prototype.dotCoordinate = function (point) {
  6706. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6707. };
  6708. /**
  6709. * Updates the current Plane from the plane defined by the three given points.
  6710. * Returns the updated Plane.
  6711. */
  6712. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6713. var x1 = point2.x - point1.x;
  6714. var y1 = point2.y - point1.y;
  6715. var z1 = point2.z - point1.z;
  6716. var x2 = point3.x - point1.x;
  6717. var y2 = point3.y - point1.y;
  6718. var z2 = point3.z - point1.z;
  6719. var yz = (y1 * z2) - (z1 * y2);
  6720. var xz = (z1 * x2) - (x1 * z2);
  6721. var xy = (x1 * y2) - (y1 * x2);
  6722. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6723. var invPyth;
  6724. if (pyth !== 0) {
  6725. invPyth = 1.0 / pyth;
  6726. }
  6727. else {
  6728. invPyth = 0.0;
  6729. }
  6730. this.normal.x = yz * invPyth;
  6731. this.normal.y = xz * invPyth;
  6732. this.normal.z = xy * invPyth;
  6733. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6734. return this;
  6735. };
  6736. /**
  6737. * Boolean : True is the vector "direction" is the same side than the plane normal.
  6738. */
  6739. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6740. var dot = Vector3.Dot(this.normal, direction);
  6741. return (dot <= epsilon);
  6742. };
  6743. /**
  6744. * Returns the signed distance (float) from the given point to the Plane.
  6745. */
  6746. Plane.prototype.signedDistanceTo = function (point) {
  6747. return Vector3.Dot(point, this.normal) + this.d;
  6748. };
  6749. // Statics
  6750. /**
  6751. * Returns a new Plane from the given array.
  6752. */
  6753. Plane.FromArray = function (array) {
  6754. return new Plane(array[0], array[1], array[2], array[3]);
  6755. };
  6756. /**
  6757. * Returns a new Plane defined by the three given points.
  6758. */
  6759. Plane.FromPoints = function (point1, point2, point3) {
  6760. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6761. result.copyFromPoints(point1, point2, point3);
  6762. return result;
  6763. };
  6764. /**
  6765. * Returns a new Plane the normal vector to this plane at the given origin point.
  6766. * Note : the vector "normal" is updated because normalized.
  6767. */
  6768. Plane.FromPositionAndNormal = function (origin, normal) {
  6769. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6770. normal.normalize();
  6771. result.normal = normal;
  6772. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6773. return result;
  6774. };
  6775. /**
  6776. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the given other point.
  6777. */
  6778. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6779. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6780. return Vector3.Dot(point, normal) + d;
  6781. };
  6782. return Plane;
  6783. }());
  6784. BABYLON.Plane = Plane;
  6785. var Viewport = /** @class */ (function () {
  6786. /**
  6787. * Creates a Viewport object located at (x, y) and sized (width, height).
  6788. */
  6789. function Viewport(x, y, width, height) {
  6790. this.x = x;
  6791. this.y = y;
  6792. this.width = width;
  6793. this.height = height;
  6794. }
  6795. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6796. if (renderWidthOrEngine.getRenderWidth) {
  6797. var engine = renderWidthOrEngine;
  6798. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6799. }
  6800. var renderWidth = renderWidthOrEngine;
  6801. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6802. };
  6803. /**
  6804. * Returns a new Viewport copied from the current one.
  6805. */
  6806. Viewport.prototype.clone = function () {
  6807. return new Viewport(this.x, this.y, this.width, this.height);
  6808. };
  6809. return Viewport;
  6810. }());
  6811. BABYLON.Viewport = Viewport;
  6812. var Frustum = /** @class */ (function () {
  6813. function Frustum() {
  6814. }
  6815. /**
  6816. * Returns a new array of 6 Frustum planes computed by the given transformation matrix.
  6817. */
  6818. Frustum.GetPlanes = function (transform) {
  6819. var frustumPlanes = [];
  6820. for (var index = 0; index < 6; index++) {
  6821. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6822. }
  6823. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6824. return frustumPlanes;
  6825. };
  6826. Frustum.GetNearPlaneToRef = 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.GetFarPlaneToRef = function (transform, frustumPlane) {
  6834. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6835. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6836. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6837. frustumPlane.d = transform.m[15] - transform.m[14];
  6838. frustumPlane.normalize();
  6839. };
  6840. Frustum.GetLeftPlaneToRef = 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.GetRightPlaneToRef = function (transform, frustumPlane) {
  6848. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6849. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6850. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6851. frustumPlane.d = transform.m[15] - transform.m[12];
  6852. frustumPlane.normalize();
  6853. };
  6854. Frustum.GetTopPlaneToRef = 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. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6862. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6863. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6864. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6865. frustumPlane.d = transform.m[15] + transform.m[13];
  6866. frustumPlane.normalize();
  6867. };
  6868. /**
  6869. * Sets the given array "frustumPlanes" with the 6 Frustum planes computed by the given transformation matrix.
  6870. */
  6871. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6872. // Near
  6873. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6874. // Far
  6875. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6876. // Left
  6877. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6878. // Right
  6879. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6880. // Top
  6881. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6882. // Bottom
  6883. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6884. };
  6885. return Frustum;
  6886. }());
  6887. BABYLON.Frustum = Frustum;
  6888. /** Defines supported spaces */
  6889. var Space;
  6890. (function (Space) {
  6891. /** Local (object) space */
  6892. Space[Space["LOCAL"] = 0] = "LOCAL";
  6893. /** World space */
  6894. Space[Space["WORLD"] = 1] = "WORLD";
  6895. /** Bone space */
  6896. Space[Space["BONE"] = 2] = "BONE";
  6897. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6898. /** Defines the 3 main axes */
  6899. var Axis = /** @class */ (function () {
  6900. function Axis() {
  6901. }
  6902. /** X axis */
  6903. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6904. /** Y axis */
  6905. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6906. /** Z axis */
  6907. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6908. return Axis;
  6909. }());
  6910. BABYLON.Axis = Axis;
  6911. ;
  6912. var BezierCurve = /** @class */ (function () {
  6913. function BezierCurve() {
  6914. }
  6915. /**
  6916. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the given x1, y1, x2, y2 floats.
  6917. */
  6918. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6919. // Extract X (which is equal to time here)
  6920. var f0 = 1 - 3 * x2 + 3 * x1;
  6921. var f1 = 3 * x2 - 6 * x1;
  6922. var f2 = 3 * x1;
  6923. var refinedT = t;
  6924. for (var i = 0; i < 5; i++) {
  6925. var refinedT2 = refinedT * refinedT;
  6926. var refinedT3 = refinedT2 * refinedT;
  6927. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6928. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6929. refinedT -= (x - t) * slope;
  6930. refinedT = Math.min(1, Math.max(0, refinedT));
  6931. }
  6932. // Resolve cubic bezier for the given x
  6933. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6934. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6935. Math.pow(refinedT, 3);
  6936. };
  6937. return BezierCurve;
  6938. }());
  6939. BABYLON.BezierCurve = BezierCurve;
  6940. /**
  6941. * Defines potential orientation for back face culling
  6942. */
  6943. var Orientation;
  6944. (function (Orientation) {
  6945. /**
  6946. * Clockwise
  6947. */
  6948. Orientation[Orientation["CW"] = 0] = "CW";
  6949. /** Counter clockwise */
  6950. Orientation[Orientation["CCW"] = 1] = "CCW";
  6951. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6952. /**
  6953. * Defines angle representation
  6954. */
  6955. var Angle = /** @class */ (function () {
  6956. /**
  6957. * Creates an Angle object of "radians" radians (float).
  6958. */
  6959. function Angle(radians) {
  6960. this._radians = radians;
  6961. if (this._radians < 0.0)
  6962. this._radians += (2.0 * Math.PI);
  6963. }
  6964. /**
  6965. * Get value in degrees
  6966. * @returns the Angle value in degrees (float)
  6967. */
  6968. Angle.prototype.degrees = function () {
  6969. return this._radians * 180.0 / Math.PI;
  6970. };
  6971. /**
  6972. * Get value in radians
  6973. * @returns the Angle value in radians (float)
  6974. */
  6975. Angle.prototype.radians = function () {
  6976. return this._radians;
  6977. };
  6978. /**
  6979. * Gets a new Angle object valued with the angle value in radians between the two given vectors
  6980. * @param a defines first vector
  6981. * @param b defines second vector
  6982. * @returns a new Angle
  6983. */
  6984. Angle.BetweenTwoPoints = function (a, b) {
  6985. var delta = b.subtract(a);
  6986. var theta = Math.atan2(delta.y, delta.x);
  6987. return new Angle(theta);
  6988. };
  6989. /**
  6990. * Gets a new Angle object from the given float in radians
  6991. * @param radians defines the angle value in radians
  6992. * @returns a new Angle
  6993. */
  6994. Angle.FromRadians = function (radians) {
  6995. return new Angle(radians);
  6996. };
  6997. /**
  6998. * Gets a new Angle object from the given float in degrees
  6999. * @param degrees defines the angle value in degrees
  7000. * @returns a new Angle
  7001. */
  7002. Angle.FromDegrees = function (degrees) {
  7003. return new Angle(degrees * Math.PI / 180.0);
  7004. };
  7005. return Angle;
  7006. }());
  7007. BABYLON.Angle = Angle;
  7008. var Arc2 = /** @class */ (function () {
  7009. /**
  7010. * Creates an Arc object from the three given points : start, middle and end.
  7011. */
  7012. function Arc2(startPoint, midPoint, endPoint) {
  7013. this.startPoint = startPoint;
  7014. this.midPoint = midPoint;
  7015. this.endPoint = endPoint;
  7016. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  7017. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  7018. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  7019. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  7020. 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);
  7021. this.radius = this.centerPoint.subtract(this.startPoint).length();
  7022. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  7023. var a1 = this.startAngle.degrees();
  7024. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  7025. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  7026. // angles correction
  7027. if (a2 - a1 > +180.0)
  7028. a2 -= 360.0;
  7029. if (a2 - a1 < -180.0)
  7030. a2 += 360.0;
  7031. if (a3 - a2 > +180.0)
  7032. a3 -= 360.0;
  7033. if (a3 - a2 < -180.0)
  7034. a3 += 360.0;
  7035. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  7036. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  7037. }
  7038. return Arc2;
  7039. }());
  7040. BABYLON.Arc2 = Arc2;
  7041. var Path2 = /** @class */ (function () {
  7042. /**
  7043. * Creates a Path2 object from the starting 2D coordinates x and y.
  7044. */
  7045. function Path2(x, y) {
  7046. this._points = new Array();
  7047. this._length = 0.0;
  7048. this.closed = false;
  7049. this._points.push(new Vector2(x, y));
  7050. }
  7051. /**
  7052. * Adds a new segment until the given coordinates (x, y) to the current Path2.
  7053. * Returns the updated Path2.
  7054. */
  7055. Path2.prototype.addLineTo = function (x, y) {
  7056. if (this.closed) {
  7057. return this;
  7058. }
  7059. var newPoint = new Vector2(x, y);
  7060. var previousPoint = this._points[this._points.length - 1];
  7061. this._points.push(newPoint);
  7062. this._length += newPoint.subtract(previousPoint).length();
  7063. return this;
  7064. };
  7065. /**
  7066. * 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.
  7067. * Returns the updated Path2.
  7068. */
  7069. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  7070. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  7071. if (this.closed) {
  7072. return this;
  7073. }
  7074. var startPoint = this._points[this._points.length - 1];
  7075. var midPoint = new Vector2(midX, midY);
  7076. var endPoint = new Vector2(endX, endY);
  7077. var arc = new Arc2(startPoint, midPoint, endPoint);
  7078. var increment = arc.angle.radians() / numberOfSegments;
  7079. if (arc.orientation === Orientation.CW)
  7080. increment *= -1;
  7081. var currentAngle = arc.startAngle.radians() + increment;
  7082. for (var i = 0; i < numberOfSegments; i++) {
  7083. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  7084. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  7085. this.addLineTo(x, y);
  7086. currentAngle += increment;
  7087. }
  7088. return this;
  7089. };
  7090. /**
  7091. * Closes the Path2.
  7092. * Returns the Path2.
  7093. */
  7094. Path2.prototype.close = function () {
  7095. this.closed = true;
  7096. return this;
  7097. };
  7098. /**
  7099. * Returns the Path2 total length (float).
  7100. */
  7101. Path2.prototype.length = function () {
  7102. var result = this._length;
  7103. if (!this.closed) {
  7104. var lastPoint = this._points[this._points.length - 1];
  7105. var firstPoint = this._points[0];
  7106. result += (firstPoint.subtract(lastPoint).length());
  7107. }
  7108. return result;
  7109. };
  7110. /**
  7111. * Returns the Path2 internal array of points.
  7112. */
  7113. Path2.prototype.getPoints = function () {
  7114. return this._points;
  7115. };
  7116. /**
  7117. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  7118. */
  7119. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  7120. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  7121. return Vector2.Zero();
  7122. }
  7123. var lengthPosition = normalizedLengthPosition * this.length();
  7124. var previousOffset = 0;
  7125. for (var i = 0; i < this._points.length; i++) {
  7126. var j = (i + 1) % this._points.length;
  7127. var a = this._points[i];
  7128. var b = this._points[j];
  7129. var bToA = b.subtract(a);
  7130. var nextOffset = (bToA.length() + previousOffset);
  7131. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  7132. var dir = bToA.normalize();
  7133. var localOffset = lengthPosition - previousOffset;
  7134. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  7135. }
  7136. previousOffset = nextOffset;
  7137. }
  7138. return Vector2.Zero();
  7139. };
  7140. /**
  7141. * Returns a new Path2 starting at the coordinates (x, y).
  7142. */
  7143. Path2.StartingAt = function (x, y) {
  7144. return new Path2(x, y);
  7145. };
  7146. return Path2;
  7147. }());
  7148. BABYLON.Path2 = Path2;
  7149. var Path3D = /** @class */ (function () {
  7150. /**
  7151. * new Path3D(path, normal, raw)
  7152. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  7153. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  7154. * path : an array of Vector3, the curve axis of the Path3D
  7155. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  7156. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  7157. */
  7158. function Path3D(path, firstNormal, raw) {
  7159. if (firstNormal === void 0) { firstNormal = null; }
  7160. this.path = path;
  7161. this._curve = new Array();
  7162. this._distances = new Array();
  7163. this._tangents = new Array();
  7164. this._normals = new Array();
  7165. this._binormals = new Array();
  7166. for (var p = 0; p < path.length; p++) {
  7167. this._curve[p] = path[p].clone(); // hard copy
  7168. }
  7169. this._raw = raw || false;
  7170. this._compute(firstNormal);
  7171. }
  7172. /**
  7173. * Returns the Path3D array of successive Vector3 designing its curve.
  7174. */
  7175. Path3D.prototype.getCurve = function () {
  7176. return this._curve;
  7177. };
  7178. /**
  7179. * Returns an array populated with tangent vectors on each Path3D curve point.
  7180. */
  7181. Path3D.prototype.getTangents = function () {
  7182. return this._tangents;
  7183. };
  7184. /**
  7185. * Returns an array populated with normal vectors on each Path3D curve point.
  7186. */
  7187. Path3D.prototype.getNormals = function () {
  7188. return this._normals;
  7189. };
  7190. /**
  7191. * Returns an array populated with binormal vectors on each Path3D curve point.
  7192. */
  7193. Path3D.prototype.getBinormals = function () {
  7194. return this._binormals;
  7195. };
  7196. /**
  7197. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  7198. */
  7199. Path3D.prototype.getDistances = function () {
  7200. return this._distances;
  7201. };
  7202. /**
  7203. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  7204. * Returns the same object updated.
  7205. */
  7206. Path3D.prototype.update = function (path, firstNormal) {
  7207. if (firstNormal === void 0) { firstNormal = null; }
  7208. for (var p = 0; p < path.length; p++) {
  7209. this._curve[p].x = path[p].x;
  7210. this._curve[p].y = path[p].y;
  7211. this._curve[p].z = path[p].z;
  7212. }
  7213. this._compute(firstNormal);
  7214. return this;
  7215. };
  7216. // private function compute() : computes tangents, normals and binormals
  7217. Path3D.prototype._compute = function (firstNormal) {
  7218. var l = this._curve.length;
  7219. // first and last tangents
  7220. this._tangents[0] = this._getFirstNonNullVector(0);
  7221. if (!this._raw) {
  7222. this._tangents[0].normalize();
  7223. }
  7224. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  7225. if (!this._raw) {
  7226. this._tangents[l - 1].normalize();
  7227. }
  7228. // normals and binormals at first point : arbitrary vector with _normalVector()
  7229. var tg0 = this._tangents[0];
  7230. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  7231. this._normals[0] = pp0;
  7232. if (!this._raw) {
  7233. this._normals[0].normalize();
  7234. }
  7235. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  7236. if (!this._raw) {
  7237. this._binormals[0].normalize();
  7238. }
  7239. this._distances[0] = 0.0;
  7240. // normals and binormals : next points
  7241. var prev; // previous vector (segment)
  7242. var cur; // current vector (segment)
  7243. var curTang; // current tangent
  7244. // previous normal
  7245. var prevBinor; // previous binormal
  7246. for (var i = 1; i < l; i++) {
  7247. // tangents
  7248. prev = this._getLastNonNullVector(i);
  7249. if (i < l - 1) {
  7250. cur = this._getFirstNonNullVector(i);
  7251. this._tangents[i] = prev.add(cur);
  7252. this._tangents[i].normalize();
  7253. }
  7254. this._distances[i] = this._distances[i - 1] + prev.length();
  7255. // normals and binormals
  7256. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  7257. curTang = this._tangents[i];
  7258. prevBinor = this._binormals[i - 1];
  7259. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  7260. if (!this._raw) {
  7261. this._normals[i].normalize();
  7262. }
  7263. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  7264. if (!this._raw) {
  7265. this._binormals[i].normalize();
  7266. }
  7267. }
  7268. };
  7269. // private function getFirstNonNullVector(index)
  7270. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  7271. Path3D.prototype._getFirstNonNullVector = function (index) {
  7272. var i = 1;
  7273. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  7274. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  7275. i++;
  7276. nNVector = this._curve[index + i].subtract(this._curve[index]);
  7277. }
  7278. return nNVector;
  7279. };
  7280. // private function getLastNonNullVector(index)
  7281. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  7282. Path3D.prototype._getLastNonNullVector = function (index) {
  7283. var i = 1;
  7284. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  7285. while (nLVector.length() === 0 && index > i + 1) {
  7286. i++;
  7287. nLVector = this._curve[index].subtract(this._curve[index - i]);
  7288. }
  7289. return nLVector;
  7290. };
  7291. // private function normalVector(v0, vt, va) :
  7292. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  7293. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  7294. Path3D.prototype._normalVector = function (v0, vt, va) {
  7295. var normal0;
  7296. var tgl = vt.length();
  7297. if (tgl === 0.0) {
  7298. tgl = 1.0;
  7299. }
  7300. if (va === undefined || va === null) {
  7301. var point;
  7302. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) { // search for a point in the plane
  7303. point = new Vector3(0.0, -1.0, 0.0);
  7304. }
  7305. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  7306. point = new Vector3(1.0, 0.0, 0.0);
  7307. }
  7308. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  7309. point = new Vector3(0.0, 0.0, 1.0);
  7310. }
  7311. else {
  7312. point = Vector3.Zero();
  7313. }
  7314. normal0 = Vector3.Cross(vt, point);
  7315. }
  7316. else {
  7317. normal0 = Vector3.Cross(vt, va);
  7318. Vector3.CrossToRef(normal0, vt, normal0);
  7319. }
  7320. normal0.normalize();
  7321. return normal0;
  7322. };
  7323. return Path3D;
  7324. }());
  7325. BABYLON.Path3D = Path3D;
  7326. var Curve3 = /** @class */ (function () {
  7327. /**
  7328. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  7329. * A Curve3 is designed from a series of successive Vector3.
  7330. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  7331. */
  7332. function Curve3(points) {
  7333. this._length = 0.0;
  7334. this._points = points;
  7335. this._length = this._computeLength(points);
  7336. }
  7337. /**
  7338. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  7339. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  7340. * @param v1 (Vector3) the control point
  7341. * @param v2 (Vector3) the end point of the Quadratic Bezier
  7342. * @param nbPoints (integer) the wanted number of points in the curve
  7343. */
  7344. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  7345. nbPoints = nbPoints > 2 ? nbPoints : 3;
  7346. var bez = new Array();
  7347. var equation = function (t, val0, val1, val2) {
  7348. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  7349. return res;
  7350. };
  7351. for (var i = 0; i <= nbPoints; i++) {
  7352. 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)));
  7353. }
  7354. return new Curve3(bez);
  7355. };
  7356. /**
  7357. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  7358. * @param v0 (Vector3) the origin point of the Cubic Bezier
  7359. * @param v1 (Vector3) the first control point
  7360. * @param v2 (Vector3) the second control point
  7361. * @param v3 (Vector3) the end point of the Cubic Bezier
  7362. * @param nbPoints (integer) the wanted number of points in the curve
  7363. */
  7364. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  7365. nbPoints = nbPoints > 3 ? nbPoints : 4;
  7366. var bez = new Array();
  7367. var equation = function (t, val0, val1, val2, val3) {
  7368. 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;
  7369. return res;
  7370. };
  7371. for (var i = 0; i <= nbPoints; i++) {
  7372. 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)));
  7373. }
  7374. return new Curve3(bez);
  7375. };
  7376. /**
  7377. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  7378. * @param p1 (Vector3) the origin point of the Hermite Spline
  7379. * @param t1 (Vector3) the tangent vector at the origin point
  7380. * @param p2 (Vector3) the end point of the Hermite Spline
  7381. * @param t2 (Vector3) the tangent vector at the end point
  7382. * @param nbPoints (integer) the wanted number of points in the curve
  7383. */
  7384. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  7385. var hermite = new Array();
  7386. var step = 1.0 / nbPoints;
  7387. for (var i = 0; i <= nbPoints; i++) {
  7388. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  7389. }
  7390. return new Curve3(hermite);
  7391. };
  7392. /**
  7393. * Returns a Curve3 object along a CatmullRom Spline curve :
  7394. * @param points (array of Vector3) the points the spline must pass through. At least, four points required
  7395. * @param nbPoints (integer) the wanted number of points between each curve control points
  7396. * @param closed (boolean) optional with default false, when true forms a closed loop from the points
  7397. */
  7398. Curve3.CreateCatmullRomSpline = function (points, nbPoints, closed) {
  7399. var catmullRom = new Array();
  7400. var step = 1.0 / nbPoints;
  7401. var amount = 0.0;
  7402. if (closed) {
  7403. var pointsCount = points.length;
  7404. for (var i = 0; i < pointsCount; i++) {
  7405. amount = 0;
  7406. for (var c = 0; c < nbPoints; c++) {
  7407. catmullRom.push(Vector3.CatmullRom(points[i % pointsCount], points[(i + 1) % pointsCount], points[(i + 2) % pointsCount], points[(i + 3) % pointsCount], amount));
  7408. amount += step;
  7409. }
  7410. }
  7411. catmullRom.push(catmullRom[0]);
  7412. }
  7413. else {
  7414. var totalPoints = new Array();
  7415. totalPoints.push(points[0].clone());
  7416. Array.prototype.push.apply(totalPoints, points);
  7417. totalPoints.push(points[points.length - 1].clone());
  7418. for (var i = 0; i < totalPoints.length - 3; i++) {
  7419. amount = 0;
  7420. for (var c = 0; c < nbPoints; c++) {
  7421. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7422. amount += step;
  7423. }
  7424. }
  7425. i--;
  7426. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7427. }
  7428. return new Curve3(catmullRom);
  7429. };
  7430. /**
  7431. * Returns the Curve3 stored array of successive Vector3
  7432. */
  7433. Curve3.prototype.getPoints = function () {
  7434. return this._points;
  7435. };
  7436. /**
  7437. * Returns the computed length (float) of the curve.
  7438. */
  7439. Curve3.prototype.length = function () {
  7440. return this._length;
  7441. };
  7442. /**
  7443. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  7444. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  7445. * curveA and curveB keep unchanged.
  7446. */
  7447. Curve3.prototype.continue = function (curve) {
  7448. var lastPoint = this._points[this._points.length - 1];
  7449. var continuedPoints = this._points.slice();
  7450. var curvePoints = curve.getPoints();
  7451. for (var i = 1; i < curvePoints.length; i++) {
  7452. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  7453. }
  7454. var continuedCurve = new Curve3(continuedPoints);
  7455. return continuedCurve;
  7456. };
  7457. Curve3.prototype._computeLength = function (path) {
  7458. var l = 0;
  7459. for (var i = 1; i < path.length; i++) {
  7460. l += (path[i].subtract(path[i - 1])).length();
  7461. }
  7462. return l;
  7463. };
  7464. return Curve3;
  7465. }());
  7466. BABYLON.Curve3 = Curve3;
  7467. // Vertex formats
  7468. var PositionNormalVertex = /** @class */ (function () {
  7469. function PositionNormalVertex(position, normal) {
  7470. if (position === void 0) { position = Vector3.Zero(); }
  7471. if (normal === void 0) { normal = Vector3.Up(); }
  7472. this.position = position;
  7473. this.normal = normal;
  7474. }
  7475. PositionNormalVertex.prototype.clone = function () {
  7476. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  7477. };
  7478. return PositionNormalVertex;
  7479. }());
  7480. BABYLON.PositionNormalVertex = PositionNormalVertex;
  7481. var PositionNormalTextureVertex = /** @class */ (function () {
  7482. function PositionNormalTextureVertex(position, normal, uv) {
  7483. if (position === void 0) { position = Vector3.Zero(); }
  7484. if (normal === void 0) { normal = Vector3.Up(); }
  7485. if (uv === void 0) { uv = Vector2.Zero(); }
  7486. this.position = position;
  7487. this.normal = normal;
  7488. this.uv = uv;
  7489. }
  7490. PositionNormalTextureVertex.prototype.clone = function () {
  7491. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  7492. };
  7493. return PositionNormalTextureVertex;
  7494. }());
  7495. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  7496. // Temporary pre-allocated objects for engine internal use
  7497. // usage in any internal function :
  7498. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  7499. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  7500. var Tmp = /** @class */ (function () {
  7501. function Tmp() {
  7502. }
  7503. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  7504. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  7505. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  7506. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  7507. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  7508. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  7509. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  7510. Matrix.Zero(), Matrix.Zero(),
  7511. Matrix.Zero(), Matrix.Zero(),
  7512. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  7513. return Tmp;
  7514. }());
  7515. BABYLON.Tmp = Tmp;
  7516. // Same as Tmp but not exported to keep it only for math functions to avoid conflicts
  7517. var MathTmp = /** @class */ (function () {
  7518. function MathTmp() {
  7519. }
  7520. MathTmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()];
  7521. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  7522. MathTmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero(), Quaternion.Zero()];
  7523. return MathTmp;
  7524. }());
  7525. })(BABYLON || (BABYLON = {}));
  7526. //# sourceMappingURL=babylon.math.js.map
  7527. var BABYLON;
  7528. (function (BABYLON) {
  7529. var Scalar = /** @class */ (function () {
  7530. function Scalar() {
  7531. }
  7532. /**
  7533. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  7534. */
  7535. Scalar.WithinEpsilon = function (a, b, epsilon) {
  7536. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  7537. var num = a - b;
  7538. return -epsilon <= num && num <= epsilon;
  7539. };
  7540. /**
  7541. * Returns a string : the upper case translation of the number i to hexadecimal.
  7542. */
  7543. Scalar.ToHex = function (i) {
  7544. var str = i.toString(16);
  7545. if (i <= 15) {
  7546. return ("0" + str).toUpperCase();
  7547. }
  7548. return str.toUpperCase();
  7549. };
  7550. /**
  7551. * Returns -1 if value is negative and +1 is value is positive.
  7552. * Returns the value itself if it's equal to zero.
  7553. */
  7554. Scalar.Sign = function (value) {
  7555. value = +value; // convert to a number
  7556. if (value === 0 || isNaN(value))
  7557. return value;
  7558. return value > 0 ? 1 : -1;
  7559. };
  7560. /**
  7561. * Returns the value itself if it's between min and max.
  7562. * Returns min if the value is lower than min.
  7563. * Returns max if the value is greater than max.
  7564. */
  7565. Scalar.Clamp = function (value, min, max) {
  7566. if (min === void 0) { min = 0; }
  7567. if (max === void 0) { max = 1; }
  7568. return Math.min(max, Math.max(min, value));
  7569. };
  7570. /**
  7571. * Returns the log2 of value.
  7572. */
  7573. Scalar.Log2 = function (value) {
  7574. return Math.log(value) * Math.LOG2E;
  7575. };
  7576. /**
  7577. * Loops the value, so that it is never larger than length and never smaller than 0.
  7578. *
  7579. * This is similar to the modulo operator but it works with floating point numbers.
  7580. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  7581. * With t = 5 and length = 2.5, the result would be 0.0.
  7582. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  7583. */
  7584. Scalar.Repeat = function (value, length) {
  7585. return value - Math.floor(value / length) * length;
  7586. };
  7587. /**
  7588. * Normalize the value between 0.0 and 1.0 using min and max values
  7589. */
  7590. Scalar.Normalize = function (value, min, max) {
  7591. return (value - min) / (max - min);
  7592. };
  7593. /**
  7594. * Denormalize the value from 0.0 and 1.0 using min and max values
  7595. */
  7596. Scalar.Denormalize = function (normalized, min, max) {
  7597. return (normalized * (max - min) + min);
  7598. };
  7599. /**
  7600. * Calculates the shortest difference between two given angles given in degrees.
  7601. */
  7602. Scalar.DeltaAngle = function (current, target) {
  7603. var num = Scalar.Repeat(target - current, 360.0);
  7604. if (num > 180.0) {
  7605. num -= 360.0;
  7606. }
  7607. return num;
  7608. };
  7609. /**
  7610. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  7611. *
  7612. * The returned value will move back and forth between 0 and length
  7613. */
  7614. Scalar.PingPong = function (tx, length) {
  7615. var t = Scalar.Repeat(tx, length * 2.0);
  7616. return length - Math.abs(t - length);
  7617. };
  7618. /**
  7619. * Interpolates between min and max with smoothing at the limits.
  7620. *
  7621. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  7622. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  7623. */
  7624. Scalar.SmoothStep = function (from, to, tx) {
  7625. var t = Scalar.Clamp(tx);
  7626. t = -2.0 * t * t * t + 3.0 * t * t;
  7627. return to * t + from * (1.0 - t);
  7628. };
  7629. /**
  7630. * Moves a value current towards target.
  7631. *
  7632. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  7633. * Negative values of maxDelta pushes the value away from target.
  7634. */
  7635. Scalar.MoveTowards = function (current, target, maxDelta) {
  7636. var result = 0;
  7637. if (Math.abs(target - current) <= maxDelta) {
  7638. result = target;
  7639. }
  7640. else {
  7641. result = current + Scalar.Sign(target - current) * maxDelta;
  7642. }
  7643. return result;
  7644. };
  7645. /**
  7646. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7647. *
  7648. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  7649. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  7650. */
  7651. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  7652. var num = Scalar.DeltaAngle(current, target);
  7653. var result = 0;
  7654. if (-maxDelta < num && num < maxDelta) {
  7655. result = target;
  7656. }
  7657. else {
  7658. target = current + num;
  7659. result = Scalar.MoveTowards(current, target, maxDelta);
  7660. }
  7661. return result;
  7662. };
  7663. /**
  7664. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  7665. */
  7666. Scalar.Lerp = function (start, end, amount) {
  7667. return start + ((end - start) * amount);
  7668. };
  7669. /**
  7670. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7671. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  7672. */
  7673. Scalar.LerpAngle = function (start, end, amount) {
  7674. var num = Scalar.Repeat(end - start, 360.0);
  7675. if (num > 180.0) {
  7676. num -= 360.0;
  7677. }
  7678. return start + num * Scalar.Clamp(amount);
  7679. };
  7680. /**
  7681. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  7682. */
  7683. Scalar.InverseLerp = function (a, b, value) {
  7684. var result = 0;
  7685. if (a != b) {
  7686. result = Scalar.Clamp((value - a) / (b - a));
  7687. }
  7688. else {
  7689. result = 0.0;
  7690. }
  7691. return result;
  7692. };
  7693. /**
  7694. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  7695. */
  7696. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  7697. var squared = amount * amount;
  7698. var cubed = amount * squared;
  7699. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  7700. var part2 = (-2.0 * cubed) + (3.0 * squared);
  7701. var part3 = (cubed - (2.0 * squared)) + amount;
  7702. var part4 = cubed - squared;
  7703. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  7704. };
  7705. /**
  7706. * Returns a random float number between and min and max values
  7707. */
  7708. Scalar.RandomRange = function (min, max) {
  7709. if (min === max)
  7710. return min;
  7711. return ((Math.random() * (max - min)) + min);
  7712. };
  7713. /**
  7714. * This function returns percentage of a number in a given range.
  7715. *
  7716. * RangeToPercent(40,20,60) will return 0.5 (50%)
  7717. * RangeToPercent(34,0,100) will return 0.34 (34%)
  7718. */
  7719. Scalar.RangeToPercent = function (number, min, max) {
  7720. return ((number - min) / (max - min));
  7721. };
  7722. /**
  7723. * This function returns number that corresponds to the percentage in a given range.
  7724. *
  7725. * PercentToRange(0.34,0,100) will return 34.
  7726. */
  7727. Scalar.PercentToRange = function (percent, min, max) {
  7728. return ((max - min) * percent + min);
  7729. };
  7730. /**
  7731. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  7732. * @param angle The angle to normalize in radian.
  7733. * @return The converted angle.
  7734. */
  7735. Scalar.NormalizeRadians = function (angle) {
  7736. // More precise but slower version kept for reference.
  7737. // angle = angle % Tools.TwoPi;
  7738. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  7739. //if (angle > Math.PI) {
  7740. // angle -= Tools.TwoPi;
  7741. //}
  7742. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  7743. return angle;
  7744. };
  7745. /**
  7746. * Two pi constants convenient for computation.
  7747. */
  7748. Scalar.TwoPi = Math.PI * 2;
  7749. return Scalar;
  7750. }());
  7751. BABYLON.Scalar = Scalar;
  7752. })(BABYLON || (BABYLON = {}));
  7753. //# sourceMappingURL=babylon.math.scalar.js.map
  7754. //# sourceMappingURL=babylon.mixins.js.map
  7755. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  7756. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  7757. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  7758. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  7759. //# sourceMappingURL=babylon.webgl2.js.map
  7760. var BABYLON;
  7761. (function (BABYLON) {
  7762. var __decoratorInitialStore = {};
  7763. var __mergedStore = {};
  7764. var _copySource = function (creationFunction, source, instanciate) {
  7765. var destination = creationFunction();
  7766. // Tags
  7767. if (BABYLON.Tags) {
  7768. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7769. }
  7770. var classStore = getMergedStore(destination);
  7771. // Properties
  7772. for (var property in classStore) {
  7773. var propertyDescriptor = classStore[property];
  7774. var sourceProperty = source[property];
  7775. var propertyType = propertyDescriptor.type;
  7776. if (sourceProperty !== undefined && sourceProperty !== null) {
  7777. switch (propertyType) {
  7778. case 0: // Value
  7779. case 6: // Mesh reference
  7780. case 11: // Camera reference
  7781. destination[property] = sourceProperty;
  7782. break;
  7783. case 1: // Texture
  7784. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  7785. break;
  7786. case 2: // Color3
  7787. case 3: // FresnelParameters
  7788. case 4: // Vector2
  7789. case 5: // Vector3
  7790. case 7: // Color Curves
  7791. case 10: // Quaternion
  7792. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7793. break;
  7794. }
  7795. }
  7796. }
  7797. return destination;
  7798. };
  7799. function getDirectStore(target) {
  7800. var classKey = target.getClassName();
  7801. if (!__decoratorInitialStore[classKey]) {
  7802. __decoratorInitialStore[classKey] = {};
  7803. }
  7804. return __decoratorInitialStore[classKey];
  7805. }
  7806. /**
  7807. * Return the list of properties flagged as serializable
  7808. * @param target: host object
  7809. */
  7810. function getMergedStore(target) {
  7811. var classKey = target.getClassName();
  7812. if (__mergedStore[classKey]) {
  7813. return __mergedStore[classKey];
  7814. }
  7815. __mergedStore[classKey] = {};
  7816. var store = __mergedStore[classKey];
  7817. var currentTarget = target;
  7818. var currentKey = classKey;
  7819. while (currentKey) {
  7820. var initialStore = __decoratorInitialStore[currentKey];
  7821. for (var property in initialStore) {
  7822. store[property] = initialStore[property];
  7823. }
  7824. var parent_1 = void 0;
  7825. var done = false;
  7826. do {
  7827. parent_1 = Object.getPrototypeOf(currentTarget);
  7828. if (!parent_1.getClassName) {
  7829. done = true;
  7830. break;
  7831. }
  7832. if (parent_1.getClassName() !== currentKey) {
  7833. break;
  7834. }
  7835. currentTarget = parent_1;
  7836. } while (parent_1);
  7837. if (done) {
  7838. break;
  7839. }
  7840. currentKey = parent_1.getClassName();
  7841. currentTarget = parent_1;
  7842. }
  7843. return store;
  7844. }
  7845. function generateSerializableMember(type, sourceName) {
  7846. return function (target, propertyKey) {
  7847. var classStore = getDirectStore(target);
  7848. if (!classStore[propertyKey]) {
  7849. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7850. }
  7851. };
  7852. }
  7853. function generateExpandMember(setCallback, targetKey) {
  7854. if (targetKey === void 0) { targetKey = null; }
  7855. return function (target, propertyKey) {
  7856. var key = targetKey || ("_" + propertyKey);
  7857. Object.defineProperty(target, propertyKey, {
  7858. get: function () {
  7859. return this[key];
  7860. },
  7861. set: function (value) {
  7862. if (this[key] === value) {
  7863. return;
  7864. }
  7865. this[key] = value;
  7866. target[setCallback].apply(this);
  7867. },
  7868. enumerable: true,
  7869. configurable: true
  7870. });
  7871. };
  7872. }
  7873. function expandToProperty(callback, targetKey) {
  7874. if (targetKey === void 0) { targetKey = null; }
  7875. return generateExpandMember(callback, targetKey);
  7876. }
  7877. BABYLON.expandToProperty = expandToProperty;
  7878. function serialize(sourceName) {
  7879. return generateSerializableMember(0, sourceName); // value member
  7880. }
  7881. BABYLON.serialize = serialize;
  7882. function serializeAsTexture(sourceName) {
  7883. return generateSerializableMember(1, sourceName); // texture member
  7884. }
  7885. BABYLON.serializeAsTexture = serializeAsTexture;
  7886. function serializeAsColor3(sourceName) {
  7887. return generateSerializableMember(2, sourceName); // color3 member
  7888. }
  7889. BABYLON.serializeAsColor3 = serializeAsColor3;
  7890. function serializeAsFresnelParameters(sourceName) {
  7891. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7892. }
  7893. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7894. function serializeAsVector2(sourceName) {
  7895. return generateSerializableMember(4, sourceName); // vector2 member
  7896. }
  7897. BABYLON.serializeAsVector2 = serializeAsVector2;
  7898. function serializeAsVector3(sourceName) {
  7899. return generateSerializableMember(5, sourceName); // vector3 member
  7900. }
  7901. BABYLON.serializeAsVector3 = serializeAsVector3;
  7902. function serializeAsMeshReference(sourceName) {
  7903. return generateSerializableMember(6, sourceName); // mesh reference member
  7904. }
  7905. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7906. function serializeAsColorCurves(sourceName) {
  7907. return generateSerializableMember(7, sourceName); // color curves
  7908. }
  7909. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7910. function serializeAsColor4(sourceName) {
  7911. return generateSerializableMember(8, sourceName); // color 4
  7912. }
  7913. BABYLON.serializeAsColor4 = serializeAsColor4;
  7914. function serializeAsImageProcessingConfiguration(sourceName) {
  7915. return generateSerializableMember(9, sourceName); // image processing
  7916. }
  7917. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7918. function serializeAsQuaternion(sourceName) {
  7919. return generateSerializableMember(10, sourceName); // quaternion member
  7920. }
  7921. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7922. /**
  7923. * Decorator used to define property that can be serialized as reference to a camera
  7924. * @param sourceName defines the name of the property to decorate
  7925. */
  7926. function serializeAsCameraReference(sourceName) {
  7927. return generateSerializableMember(11, sourceName); // camera reference member
  7928. }
  7929. BABYLON.serializeAsCameraReference = serializeAsCameraReference;
  7930. var SerializationHelper = /** @class */ (function () {
  7931. function SerializationHelper() {
  7932. }
  7933. SerializationHelper.Serialize = function (entity, serializationObject) {
  7934. if (!serializationObject) {
  7935. serializationObject = {};
  7936. }
  7937. // Tags
  7938. if (BABYLON.Tags) {
  7939. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7940. }
  7941. var serializedProperties = getMergedStore(entity);
  7942. // Properties
  7943. for (var property in serializedProperties) {
  7944. var propertyDescriptor = serializedProperties[property];
  7945. var targetPropertyName = propertyDescriptor.sourceName || property;
  7946. var propertyType = propertyDescriptor.type;
  7947. var sourceProperty = entity[property];
  7948. if (sourceProperty !== undefined && sourceProperty !== null) {
  7949. switch (propertyType) {
  7950. case 0: // Value
  7951. serializationObject[targetPropertyName] = sourceProperty;
  7952. break;
  7953. case 1: // Texture
  7954. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7955. break;
  7956. case 2: // Color3
  7957. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7958. break;
  7959. case 3: // FresnelParameters
  7960. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7961. break;
  7962. case 4: // Vector2
  7963. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7964. break;
  7965. case 5: // Vector3
  7966. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7967. break;
  7968. case 6: // Mesh reference
  7969. serializationObject[targetPropertyName] = sourceProperty.id;
  7970. break;
  7971. case 7: // Color Curves
  7972. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7973. break;
  7974. case 8: // Color 4
  7975. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7976. break;
  7977. case 9: // Image Processing
  7978. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7979. break;
  7980. case 10: // Quaternion
  7981. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7982. break;
  7983. case 11: // Camera reference
  7984. serializationObject[targetPropertyName] = sourceProperty.id;
  7985. break;
  7986. }
  7987. }
  7988. }
  7989. return serializationObject;
  7990. };
  7991. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7992. if (rootUrl === void 0) { rootUrl = null; }
  7993. var destination = creationFunction();
  7994. if (!rootUrl) {
  7995. rootUrl = "";
  7996. }
  7997. // Tags
  7998. if (BABYLON.Tags) {
  7999. BABYLON.Tags.AddTagsTo(destination, source.tags);
  8000. }
  8001. var classStore = getMergedStore(destination);
  8002. // Properties
  8003. for (var property in classStore) {
  8004. var propertyDescriptor = classStore[property];
  8005. var sourceProperty = source[propertyDescriptor.sourceName || property];
  8006. var propertyType = propertyDescriptor.type;
  8007. if (sourceProperty !== undefined && sourceProperty !== null) {
  8008. var dest = destination;
  8009. switch (propertyType) {
  8010. case 0: // Value
  8011. dest[property] = sourceProperty;
  8012. break;
  8013. case 1: // Texture
  8014. if (scene) {
  8015. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  8016. }
  8017. break;
  8018. case 2: // Color3
  8019. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  8020. break;
  8021. case 3: // FresnelParameters
  8022. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  8023. break;
  8024. case 4: // Vector2
  8025. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  8026. break;
  8027. case 5: // Vector3
  8028. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  8029. break;
  8030. case 6: // Mesh reference
  8031. if (scene) {
  8032. dest[property] = scene.getLastMeshByID(sourceProperty);
  8033. }
  8034. break;
  8035. case 7: // Color Curves
  8036. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  8037. break;
  8038. case 8: // Color 4
  8039. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  8040. break;
  8041. case 9: // Image Processing
  8042. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  8043. break;
  8044. case 10: // Quaternion
  8045. dest[property] = BABYLON.Quaternion.FromArray(sourceProperty);
  8046. break;
  8047. case 11: // Camera reference
  8048. if (scene) {
  8049. dest[property] = scene.getCameraByID(sourceProperty);
  8050. }
  8051. break;
  8052. }
  8053. }
  8054. }
  8055. return destination;
  8056. };
  8057. SerializationHelper.Clone = function (creationFunction, source) {
  8058. return _copySource(creationFunction, source, false);
  8059. };
  8060. SerializationHelper.Instanciate = function (creationFunction, source) {
  8061. return _copySource(creationFunction, source, true);
  8062. };
  8063. return SerializationHelper;
  8064. }());
  8065. BABYLON.SerializationHelper = SerializationHelper;
  8066. })(BABYLON || (BABYLON = {}));
  8067. //# sourceMappingURL=babylon.decorators.js.map
  8068. var BABYLON;
  8069. (function (BABYLON) {
  8070. /**
  8071. * Wrapper class for promise with external resolve and reject.
  8072. */
  8073. var Deferred = /** @class */ (function () {
  8074. /**
  8075. * Constructor for this deferred object.
  8076. */
  8077. function Deferred() {
  8078. var _this = this;
  8079. this.promise = new Promise(function (resolve, reject) {
  8080. _this._resolve = resolve;
  8081. _this._reject = reject;
  8082. });
  8083. }
  8084. Object.defineProperty(Deferred.prototype, "resolve", {
  8085. /**
  8086. * The resolve method of the promise associated with this deferred object.
  8087. */
  8088. get: function () {
  8089. return this._resolve;
  8090. },
  8091. enumerable: true,
  8092. configurable: true
  8093. });
  8094. Object.defineProperty(Deferred.prototype, "reject", {
  8095. /**
  8096. * The reject method of the promise associated with this deferred object.
  8097. */
  8098. get: function () {
  8099. return this._reject;
  8100. },
  8101. enumerable: true,
  8102. configurable: true
  8103. });
  8104. return Deferred;
  8105. }());
  8106. BABYLON.Deferred = Deferred;
  8107. })(BABYLON || (BABYLON = {}));
  8108. //# sourceMappingURL=babylon.deferred.js.map
  8109. var BABYLON;
  8110. (function (BABYLON) {
  8111. /**
  8112. * A class serves as a medium between the observable and its observers
  8113. */
  8114. var EventState = /** @class */ (function () {
  8115. /**
  8116. * Create a new EventState
  8117. * @param mask defines the mask associated with this state
  8118. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8119. * @param target defines the original target of the state
  8120. * @param currentTarget defines the current target of the state
  8121. */
  8122. function EventState(mask, skipNextObservers, target, currentTarget) {
  8123. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8124. this.initalize(mask, skipNextObservers, target, currentTarget);
  8125. }
  8126. /**
  8127. * Initialize the current event state
  8128. * @param mask defines the mask associated with this state
  8129. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8130. * @param target defines the original target of the state
  8131. * @param currentTarget defines the current target of the state
  8132. * @returns the current event state
  8133. */
  8134. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  8135. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8136. this.mask = mask;
  8137. this.skipNextObservers = skipNextObservers;
  8138. this.target = target;
  8139. this.currentTarget = currentTarget;
  8140. return this;
  8141. };
  8142. return EventState;
  8143. }());
  8144. BABYLON.EventState = EventState;
  8145. /**
  8146. * Represent an Observer registered to a given Observable object.
  8147. */
  8148. var Observer = /** @class */ (function () {
  8149. /**
  8150. * Creates a new observer
  8151. * @param callback defines the callback to call when the observer is notified
  8152. * @param mask defines the mask of the observer (used to filter notifications)
  8153. * @param scope defines the current scope used to restore the JS context
  8154. */
  8155. function Observer(
  8156. /**
  8157. * Defines the callback to call when the observer is notified
  8158. */
  8159. callback,
  8160. /**
  8161. * Defines the mask of the observer (used to filter notifications)
  8162. */
  8163. mask,
  8164. /**
  8165. * Defines the current scope used to restore the JS context
  8166. */
  8167. scope) {
  8168. if (scope === void 0) { scope = null; }
  8169. this.callback = callback;
  8170. this.mask = mask;
  8171. this.scope = scope;
  8172. /** @hidden */
  8173. this._willBeUnregistered = false;
  8174. /**
  8175. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  8176. */
  8177. this.unregisterOnNextCall = false;
  8178. }
  8179. return Observer;
  8180. }());
  8181. BABYLON.Observer = Observer;
  8182. /**
  8183. * Represent a list of observers registered to multiple Observables object.
  8184. */
  8185. var MultiObserver = /** @class */ (function () {
  8186. function MultiObserver() {
  8187. }
  8188. /**
  8189. * Release associated resources
  8190. */
  8191. MultiObserver.prototype.dispose = function () {
  8192. if (this._observers && this._observables) {
  8193. for (var index = 0; index < this._observers.length; index++) {
  8194. this._observables[index].remove(this._observers[index]);
  8195. }
  8196. }
  8197. this._observers = null;
  8198. this._observables = null;
  8199. };
  8200. /**
  8201. * Raise a callback when one of the observable will notify
  8202. * @param observables defines a list of observables to watch
  8203. * @param callback defines the callback to call on notification
  8204. * @param mask defines the mask used to filter notifications
  8205. * @param scope defines the current scope used to restore the JS context
  8206. * @returns the new MultiObserver
  8207. */
  8208. MultiObserver.Watch = function (observables, callback, mask, scope) {
  8209. if (mask === void 0) { mask = -1; }
  8210. if (scope === void 0) { scope = null; }
  8211. var result = new MultiObserver();
  8212. result._observers = new Array();
  8213. result._observables = observables;
  8214. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  8215. var observable = observables_1[_i];
  8216. var observer = observable.add(callback, mask, false, scope);
  8217. if (observer) {
  8218. result._observers.push(observer);
  8219. }
  8220. }
  8221. return result;
  8222. };
  8223. return MultiObserver;
  8224. }());
  8225. BABYLON.MultiObserver = MultiObserver;
  8226. /**
  8227. * The Observable class is a simple implementation of the Observable pattern.
  8228. *
  8229. * 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.
  8230. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  8231. * 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).
  8232. * 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.
  8233. */
  8234. var Observable = /** @class */ (function () {
  8235. /**
  8236. * Creates a new observable
  8237. * @param onObserverAdded defines a callback to call when a new observer is added
  8238. */
  8239. function Observable(onObserverAdded) {
  8240. this._observers = new Array();
  8241. this._eventState = new EventState(0);
  8242. if (onObserverAdded) {
  8243. this._onObserverAdded = onObserverAdded;
  8244. }
  8245. }
  8246. /**
  8247. * Create a new Observer with the specified callback
  8248. * @param callback the callback that will be executed for that Observer
  8249. * @param mask the mask used to filter observers
  8250. * @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.
  8251. * @param scope optional scope for the callback to be called from
  8252. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  8253. * @returns the new observer created for the callback
  8254. */
  8255. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  8256. if (mask === void 0) { mask = -1; }
  8257. if (insertFirst === void 0) { insertFirst = false; }
  8258. if (scope === void 0) { scope = null; }
  8259. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  8260. if (!callback) {
  8261. return null;
  8262. }
  8263. var observer = new Observer(callback, mask, scope);
  8264. observer.unregisterOnNextCall = unregisterOnFirstCall;
  8265. if (insertFirst) {
  8266. this._observers.unshift(observer);
  8267. }
  8268. else {
  8269. this._observers.push(observer);
  8270. }
  8271. if (this._onObserverAdded) {
  8272. this._onObserverAdded(observer);
  8273. }
  8274. return observer;
  8275. };
  8276. /**
  8277. * Create a new Observer with the specified callback and unregisters after the next notification
  8278. * @param callback the callback that will be executed for that Observer
  8279. * @returns the new observer created for the callback
  8280. */
  8281. Observable.prototype.addOnce = function (callback) {
  8282. return this.add(callback, undefined, undefined, undefined, true);
  8283. };
  8284. /**
  8285. * Remove an Observer from the Observable object
  8286. * @param observer the instance of the Observer to remove
  8287. * @returns false if it doesn't belong to this Observable
  8288. */
  8289. Observable.prototype.remove = function (observer) {
  8290. if (!observer) {
  8291. return false;
  8292. }
  8293. var index = this._observers.indexOf(observer);
  8294. if (index !== -1) {
  8295. this._observers.splice(index, 1);
  8296. return true;
  8297. }
  8298. return false;
  8299. };
  8300. /**
  8301. * Remove a callback from the Observable object
  8302. * @param callback the callback to remove
  8303. * @param scope optional scope. If used only the callbacks with this scope will be removed
  8304. * @returns false if it doesn't belong to this Observable
  8305. */
  8306. Observable.prototype.removeCallback = function (callback, scope) {
  8307. for (var index = 0; index < this._observers.length; index++) {
  8308. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  8309. this._observers.splice(index, 1);
  8310. return true;
  8311. }
  8312. }
  8313. return false;
  8314. };
  8315. Observable.prototype._deferUnregister = function (observer) {
  8316. var _this = this;
  8317. observer.unregisterOnNextCall = false;
  8318. observer._willBeUnregistered = true;
  8319. BABYLON.Tools.SetImmediate(function () {
  8320. _this.remove(observer);
  8321. });
  8322. };
  8323. /**
  8324. * Notify all Observers by calling their respective callback with the given data
  8325. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  8326. * @param eventData defines the data to send to all observers
  8327. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  8328. * @param target defines the original target of the state
  8329. * @param currentTarget defines the current target of the state
  8330. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  8331. */
  8332. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  8333. if (mask === void 0) { mask = -1; }
  8334. if (!this._observers.length) {
  8335. return true;
  8336. }
  8337. var state = this._eventState;
  8338. state.mask = mask;
  8339. state.target = target;
  8340. state.currentTarget = currentTarget;
  8341. state.skipNextObservers = false;
  8342. state.lastReturnValue = eventData;
  8343. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8344. var obs = _a[_i];
  8345. if (obs._willBeUnregistered) {
  8346. continue;
  8347. }
  8348. if (obs.mask & mask) {
  8349. if (obs.scope) {
  8350. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  8351. }
  8352. else {
  8353. state.lastReturnValue = obs.callback(eventData, state);
  8354. }
  8355. if (obs.unregisterOnNextCall) {
  8356. this._deferUnregister(obs);
  8357. }
  8358. }
  8359. if (state.skipNextObservers) {
  8360. return false;
  8361. }
  8362. }
  8363. return true;
  8364. };
  8365. /**
  8366. * Calling this will execute each callback, expecting it to be a promise or return a value.
  8367. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  8368. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  8369. * and it is crucial that all callbacks will be executed.
  8370. * The order of the callbacks is kept, callbacks are not executed parallel.
  8371. *
  8372. * @param eventData The data to be sent to each callback
  8373. * @param mask is used to filter observers defaults to -1
  8374. * @param target defines the callback target (see EventState)
  8375. * @param currentTarget defines he current object in the bubbling phase
  8376. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  8377. */
  8378. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  8379. var _this = this;
  8380. if (mask === void 0) { mask = -1; }
  8381. // create an empty promise
  8382. var p = Promise.resolve(eventData);
  8383. // no observers? return this promise.
  8384. if (!this._observers.length) {
  8385. return p;
  8386. }
  8387. var state = this._eventState;
  8388. state.mask = mask;
  8389. state.target = target;
  8390. state.currentTarget = currentTarget;
  8391. state.skipNextObservers = false;
  8392. // execute one callback after another (not using Promise.all, the order is important)
  8393. this._observers.forEach(function (obs) {
  8394. if (state.skipNextObservers) {
  8395. return;
  8396. }
  8397. if (obs._willBeUnregistered) {
  8398. return;
  8399. }
  8400. if (obs.mask & mask) {
  8401. if (obs.scope) {
  8402. p = p.then(function (lastReturnedValue) {
  8403. state.lastReturnValue = lastReturnedValue;
  8404. return obs.callback.apply(obs.scope, [eventData, state]);
  8405. });
  8406. }
  8407. else {
  8408. p = p.then(function (lastReturnedValue) {
  8409. state.lastReturnValue = lastReturnedValue;
  8410. return obs.callback(eventData, state);
  8411. });
  8412. }
  8413. if (obs.unregisterOnNextCall) {
  8414. _this._deferUnregister(obs);
  8415. }
  8416. }
  8417. });
  8418. // return the eventData
  8419. return p.then(function () { return eventData; });
  8420. };
  8421. /**
  8422. * Notify a specific observer
  8423. * @param observer defines the observer to notify
  8424. * @param eventData defines the data to be sent to each callback
  8425. * @param mask is used to filter observers defaults to -1
  8426. */
  8427. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  8428. if (mask === void 0) { mask = -1; }
  8429. var state = this._eventState;
  8430. state.mask = mask;
  8431. state.skipNextObservers = false;
  8432. observer.callback(eventData, state);
  8433. };
  8434. /**
  8435. * Gets a boolean indicating if the observable has at least one observer
  8436. * @returns true is the Observable has at least one Observer registered
  8437. */
  8438. Observable.prototype.hasObservers = function () {
  8439. return this._observers.length > 0;
  8440. };
  8441. /**
  8442. * Clear the list of observers
  8443. */
  8444. Observable.prototype.clear = function () {
  8445. this._observers = new Array();
  8446. this._onObserverAdded = null;
  8447. };
  8448. /**
  8449. * Clone the current observable
  8450. * @returns a new observable
  8451. */
  8452. Observable.prototype.clone = function () {
  8453. var result = new Observable();
  8454. result._observers = this._observers.slice(0);
  8455. return result;
  8456. };
  8457. /**
  8458. * Does this observable handles observer registered with a given mask
  8459. * @param mask defines the mask to be tested
  8460. * @return whether or not one observer registered with the given mask is handeled
  8461. **/
  8462. Observable.prototype.hasSpecificMask = function (mask) {
  8463. if (mask === void 0) { mask = -1; }
  8464. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8465. var obs = _a[_i];
  8466. if (obs.mask & mask || obs.mask === mask) {
  8467. return true;
  8468. }
  8469. }
  8470. return false;
  8471. };
  8472. return Observable;
  8473. }());
  8474. BABYLON.Observable = Observable;
  8475. })(BABYLON || (BABYLON = {}));
  8476. //# sourceMappingURL=babylon.observable.js.map
  8477. var BABYLON;
  8478. (function (BABYLON) {
  8479. var SmartArray = /** @class */ (function () {
  8480. function SmartArray(capacity) {
  8481. this.length = 0;
  8482. this.data = new Array(capacity);
  8483. this._id = SmartArray._GlobalId++;
  8484. }
  8485. SmartArray.prototype.push = function (value) {
  8486. this.data[this.length++] = value;
  8487. if (this.length > this.data.length) {
  8488. this.data.length *= 2;
  8489. }
  8490. };
  8491. SmartArray.prototype.forEach = function (func) {
  8492. for (var index = 0; index < this.length; index++) {
  8493. func(this.data[index]);
  8494. }
  8495. };
  8496. SmartArray.prototype.sort = function (compareFn) {
  8497. this.data.sort(compareFn);
  8498. };
  8499. SmartArray.prototype.reset = function () {
  8500. this.length = 0;
  8501. };
  8502. SmartArray.prototype.dispose = function () {
  8503. this.reset();
  8504. if (this.data) {
  8505. this.data.length = 0;
  8506. this.data = [];
  8507. }
  8508. };
  8509. SmartArray.prototype.concat = function (array) {
  8510. if (array.length === 0) {
  8511. return;
  8512. }
  8513. if (this.length + array.length > this.data.length) {
  8514. this.data.length = (this.length + array.length) * 2;
  8515. }
  8516. for (var index = 0; index < array.length; index++) {
  8517. this.data[this.length++] = (array.data || array)[index];
  8518. }
  8519. };
  8520. SmartArray.prototype.indexOf = function (value) {
  8521. var position = this.data.indexOf(value);
  8522. if (position >= this.length) {
  8523. return -1;
  8524. }
  8525. return position;
  8526. };
  8527. SmartArray.prototype.contains = function (value) {
  8528. return this.data.indexOf(value) !== -1;
  8529. };
  8530. // Statics
  8531. SmartArray._GlobalId = 0;
  8532. return SmartArray;
  8533. }());
  8534. BABYLON.SmartArray = SmartArray;
  8535. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  8536. __extends(SmartArrayNoDuplicate, _super);
  8537. function SmartArrayNoDuplicate() {
  8538. var _this = _super !== null && _super.apply(this, arguments) || this;
  8539. _this._duplicateId = 0;
  8540. return _this;
  8541. }
  8542. SmartArrayNoDuplicate.prototype.push = function (value) {
  8543. _super.prototype.push.call(this, value);
  8544. if (!value.__smartArrayFlags) {
  8545. value.__smartArrayFlags = {};
  8546. }
  8547. value.__smartArrayFlags[this._id] = this._duplicateId;
  8548. };
  8549. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  8550. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  8551. return false;
  8552. }
  8553. this.push(value);
  8554. return true;
  8555. };
  8556. SmartArrayNoDuplicate.prototype.reset = function () {
  8557. _super.prototype.reset.call(this);
  8558. this._duplicateId++;
  8559. };
  8560. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  8561. if (array.length === 0) {
  8562. return;
  8563. }
  8564. if (this.length + array.length > this.data.length) {
  8565. this.data.length = (this.length + array.length) * 2;
  8566. }
  8567. for (var index = 0; index < array.length; index++) {
  8568. var item = (array.data || array)[index];
  8569. this.pushNoDuplicate(item);
  8570. }
  8571. };
  8572. return SmartArrayNoDuplicate;
  8573. }(SmartArray));
  8574. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  8575. })(BABYLON || (BABYLON = {}));
  8576. //# sourceMappingURL=babylon.smartArray.js.map
  8577. var BABYLON;
  8578. (function (BABYLON) {
  8579. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  8580. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  8581. var LoadFileError = /** @class */ (function (_super) {
  8582. __extends(LoadFileError, _super);
  8583. function LoadFileError(message, request) {
  8584. var _this = _super.call(this, message) || this;
  8585. _this.request = request;
  8586. _this.name = "LoadFileError";
  8587. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  8588. return _this;
  8589. }
  8590. // Polyfill for Object.setPrototypeOf if necessary.
  8591. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  8592. return LoadFileError;
  8593. }(Error));
  8594. BABYLON.LoadFileError = LoadFileError;
  8595. var RetryStrategy = /** @class */ (function () {
  8596. function RetryStrategy() {
  8597. }
  8598. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  8599. if (maxRetries === void 0) { maxRetries = 3; }
  8600. if (baseInterval === void 0) { baseInterval = 500; }
  8601. return function (url, request, retryIndex) {
  8602. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  8603. return -1;
  8604. }
  8605. return Math.pow(2, retryIndex) * baseInterval;
  8606. };
  8607. };
  8608. return RetryStrategy;
  8609. }());
  8610. BABYLON.RetryStrategy = RetryStrategy;
  8611. // Screenshots
  8612. var screenshotCanvas;
  8613. var cloneValue = function (source, destinationObject) {
  8614. if (!source)
  8615. return null;
  8616. if (source instanceof BABYLON.Mesh) {
  8617. return null;
  8618. }
  8619. if (source instanceof BABYLON.SubMesh) {
  8620. return source.clone(destinationObject);
  8621. }
  8622. else if (source.clone) {
  8623. return source.clone();
  8624. }
  8625. return null;
  8626. };
  8627. var Tools = /** @class */ (function () {
  8628. function Tools() {
  8629. }
  8630. /**
  8631. * Interpolates between a and b via alpha
  8632. * @param a The lower value (returned when alpha = 0)
  8633. * @param b The upper value (returned when alpha = 1)
  8634. * @param alpha The interpolation-factor
  8635. * @return The mixed value
  8636. */
  8637. Tools.Mix = function (a, b, alpha) {
  8638. return a * (1 - alpha) + b * alpha;
  8639. };
  8640. Tools.Instantiate = function (className) {
  8641. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  8642. return Tools.RegisteredExternalClasses[className];
  8643. }
  8644. var arr = className.split(".");
  8645. var fn = (window || this);
  8646. for (var i = 0, len = arr.length; i < len; i++) {
  8647. fn = fn[arr[i]];
  8648. }
  8649. if (typeof fn !== "function") {
  8650. return null;
  8651. }
  8652. return fn;
  8653. };
  8654. /**
  8655. * Provides a slice function that will work even on IE
  8656. * @param data defines the array to slice
  8657. * @param start defines the start of the data (optional)
  8658. * @param end defines the end of the data (optional)
  8659. * @returns the new sliced array
  8660. */
  8661. Tools.Slice = function (data, start, end) {
  8662. if (data.slice) {
  8663. return data.slice(start, end);
  8664. }
  8665. return Array.prototype.slice.call(data, start, end);
  8666. };
  8667. Tools.SetImmediate = function (action) {
  8668. if (window.setImmediate) {
  8669. window.setImmediate(action);
  8670. }
  8671. else {
  8672. setTimeout(action, 1);
  8673. }
  8674. };
  8675. Tools.IsExponentOfTwo = function (value) {
  8676. var count = 1;
  8677. do {
  8678. count *= 2;
  8679. } while (count < value);
  8680. return count === value;
  8681. };
  8682. /**
  8683. * Returns the nearest 32-bit single precision float representation of a Number
  8684. * @param value A Number. If the parameter is of a different type, it will get converted
  8685. * to a number or to NaN if it cannot be converted
  8686. * @returns number
  8687. */
  8688. Tools.FloatRound = function (value) {
  8689. if (Math.fround) {
  8690. return Math.fround(value);
  8691. }
  8692. return (Tools._tmpFloatArray[0] = value);
  8693. };
  8694. /**
  8695. * Find the next highest power of two.
  8696. * @param x Number to start search from.
  8697. * @return Next highest power of two.
  8698. */
  8699. Tools.CeilingPOT = function (x) {
  8700. x--;
  8701. x |= x >> 1;
  8702. x |= x >> 2;
  8703. x |= x >> 4;
  8704. x |= x >> 8;
  8705. x |= x >> 16;
  8706. x++;
  8707. return x;
  8708. };
  8709. /**
  8710. * Find the next lowest power of two.
  8711. * @param x Number to start search from.
  8712. * @return Next lowest power of two.
  8713. */
  8714. Tools.FloorPOT = function (x) {
  8715. x = x | (x >> 1);
  8716. x = x | (x >> 2);
  8717. x = x | (x >> 4);
  8718. x = x | (x >> 8);
  8719. x = x | (x >> 16);
  8720. return x - (x >> 1);
  8721. };
  8722. /**
  8723. * Find the nearest power of two.
  8724. * @param x Number to start search from.
  8725. * @return Next nearest power of two.
  8726. */
  8727. Tools.NearestPOT = function (x) {
  8728. var c = Tools.CeilingPOT(x);
  8729. var f = Tools.FloorPOT(x);
  8730. return (c - x) > (x - f) ? f : c;
  8731. };
  8732. Tools.GetExponentOfTwo = function (value, max, mode) {
  8733. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  8734. var pot;
  8735. switch (mode) {
  8736. case BABYLON.Engine.SCALEMODE_FLOOR:
  8737. pot = Tools.FloorPOT(value);
  8738. break;
  8739. case BABYLON.Engine.SCALEMODE_NEAREST:
  8740. pot = Tools.NearestPOT(value);
  8741. break;
  8742. case BABYLON.Engine.SCALEMODE_CEILING:
  8743. default:
  8744. pot = Tools.CeilingPOT(value);
  8745. break;
  8746. }
  8747. return Math.min(pot, max);
  8748. };
  8749. Tools.GetFilename = function (path) {
  8750. var index = path.lastIndexOf("/");
  8751. if (index < 0)
  8752. return path;
  8753. return path.substring(index + 1);
  8754. };
  8755. /**
  8756. * Extracts the "folder" part of a path (everything before the filename).
  8757. * @param uri The URI to extract the info from
  8758. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  8759. * @returns The "folder" part of the path
  8760. */
  8761. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  8762. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  8763. var index = uri.lastIndexOf("/");
  8764. if (index < 0) {
  8765. if (returnUnchangedIfNoSlash) {
  8766. return uri;
  8767. }
  8768. return "";
  8769. }
  8770. return uri.substring(0, index + 1);
  8771. };
  8772. Tools.GetDOMTextContent = function (element) {
  8773. var result = "";
  8774. var child = element.firstChild;
  8775. while (child) {
  8776. if (child.nodeType === 3) {
  8777. result += child.textContent;
  8778. }
  8779. child = child.nextSibling;
  8780. }
  8781. return result;
  8782. };
  8783. Tools.ToDegrees = function (angle) {
  8784. return angle * 180 / Math.PI;
  8785. };
  8786. Tools.ToRadians = function (angle) {
  8787. return angle * Math.PI / 180;
  8788. };
  8789. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8790. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8791. var output = "";
  8792. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8793. var i = 0;
  8794. var bytes = new Uint8Array(buffer);
  8795. while (i < bytes.length) {
  8796. chr1 = bytes[i++];
  8797. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8798. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8799. enc1 = chr1 >> 2;
  8800. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8801. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8802. enc4 = chr3 & 63;
  8803. if (isNaN(chr2)) {
  8804. enc3 = enc4 = 64;
  8805. }
  8806. else if (isNaN(chr3)) {
  8807. enc4 = 64;
  8808. }
  8809. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8810. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8811. }
  8812. return "data:image/png;base64," + output;
  8813. };
  8814. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  8815. if (bias === void 0) { bias = null; }
  8816. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8817. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8818. for (var index = indexStart; index < indexStart + indexCount; index++) {
  8819. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  8820. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8821. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8822. }
  8823. if (bias) {
  8824. minimum.x -= minimum.x * bias.x + bias.y;
  8825. minimum.y -= minimum.y * bias.x + bias.y;
  8826. minimum.z -= minimum.z * bias.x + bias.y;
  8827. maximum.x += maximum.x * bias.x + bias.y;
  8828. maximum.y += maximum.y * bias.x + bias.y;
  8829. maximum.z += maximum.z * bias.x + bias.y;
  8830. }
  8831. return {
  8832. minimum: minimum,
  8833. maximum: maximum
  8834. };
  8835. };
  8836. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  8837. if (bias === void 0) { bias = null; }
  8838. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8839. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8840. if (!stride) {
  8841. stride = 3;
  8842. }
  8843. for (var index = start; index < start + count; index++) {
  8844. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  8845. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8846. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8847. }
  8848. if (bias) {
  8849. minimum.x -= minimum.x * bias.x + bias.y;
  8850. minimum.y -= minimum.y * bias.x + bias.y;
  8851. minimum.z -= minimum.z * bias.x + bias.y;
  8852. maximum.x += maximum.x * bias.x + bias.y;
  8853. maximum.y += maximum.y * bias.x + bias.y;
  8854. maximum.z += maximum.z * bias.x + bias.y;
  8855. }
  8856. return {
  8857. minimum: minimum,
  8858. maximum: maximum
  8859. };
  8860. };
  8861. Tools.Vector2ArrayFeeder = function (array) {
  8862. return function (index) {
  8863. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  8864. var length = isFloatArray ? array.length / 2 : array.length;
  8865. if (index >= length) {
  8866. return null;
  8867. }
  8868. if (isFloatArray) {
  8869. var fa = array;
  8870. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  8871. }
  8872. var a = array;
  8873. return a[index];
  8874. };
  8875. };
  8876. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  8877. if (bias === void 0) { bias = null; }
  8878. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  8879. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  8880. var i = 0;
  8881. var cur = feeder(i++);
  8882. while (cur) {
  8883. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  8884. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  8885. cur = feeder(i++);
  8886. }
  8887. if (bias) {
  8888. minimum.x -= minimum.x * bias.x + bias.y;
  8889. minimum.y -= minimum.y * bias.x + bias.y;
  8890. maximum.x += maximum.x * bias.x + bias.y;
  8891. maximum.y += maximum.y * bias.x + bias.y;
  8892. }
  8893. return {
  8894. minimum: minimum,
  8895. maximum: maximum
  8896. };
  8897. };
  8898. Tools.MakeArray = function (obj, allowsNullUndefined) {
  8899. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  8900. return null;
  8901. return Array.isArray(obj) ? obj : [obj];
  8902. };
  8903. // Misc.
  8904. Tools.GetPointerPrefix = function () {
  8905. var eventPrefix = "pointer";
  8906. // Check if pointer events are supported
  8907. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  8908. eventPrefix = "mouse";
  8909. }
  8910. return eventPrefix;
  8911. };
  8912. /**
  8913. * @param func - the function to be called
  8914. * @param requester - the object that will request the next frame. Falls back to window.
  8915. */
  8916. Tools.QueueNewFrame = function (func, requester) {
  8917. if (!Tools.IsWindowObjectExist()) {
  8918. return setTimeout(func, 16);
  8919. }
  8920. if (!requester) {
  8921. requester = window;
  8922. }
  8923. if (requester.requestAnimationFrame) {
  8924. return requester.requestAnimationFrame(func);
  8925. }
  8926. else if (requester.msRequestAnimationFrame) {
  8927. return requester.msRequestAnimationFrame(func);
  8928. }
  8929. else if (requester.webkitRequestAnimationFrame) {
  8930. return requester.webkitRequestAnimationFrame(func);
  8931. }
  8932. else if (requester.mozRequestAnimationFrame) {
  8933. return requester.mozRequestAnimationFrame(func);
  8934. }
  8935. else if (requester.oRequestAnimationFrame) {
  8936. return requester.oRequestAnimationFrame(func);
  8937. }
  8938. else {
  8939. return window.setTimeout(func, 16);
  8940. }
  8941. };
  8942. Tools.RequestFullscreen = function (element) {
  8943. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8944. if (!requestFunction)
  8945. return;
  8946. requestFunction.call(element);
  8947. };
  8948. Tools.ExitFullscreen = function () {
  8949. if (document.exitFullscreen) {
  8950. document.exitFullscreen();
  8951. }
  8952. else if (document.mozCancelFullScreen) {
  8953. document.mozCancelFullScreen();
  8954. }
  8955. else if (document.webkitCancelFullScreen) {
  8956. document.webkitCancelFullScreen();
  8957. }
  8958. else if (document.msCancelFullScreen) {
  8959. document.msCancelFullScreen();
  8960. }
  8961. };
  8962. Tools.SetCorsBehavior = function (url, element) {
  8963. if (url && url.indexOf("data:") === 0) {
  8964. return;
  8965. }
  8966. if (Tools.CorsBehavior) {
  8967. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  8968. element.crossOrigin = Tools.CorsBehavior;
  8969. }
  8970. else {
  8971. var result = Tools.CorsBehavior(url);
  8972. if (result) {
  8973. element.crossOrigin = result;
  8974. }
  8975. }
  8976. }
  8977. };
  8978. // External files
  8979. Tools.CleanUrl = function (url) {
  8980. url = url.replace(/#/mg, "%23");
  8981. return url;
  8982. };
  8983. /**
  8984. * Loads an image as an HTMLImageElement.
  8985. * @param input url string, ArrayBuffer, or Blob to load
  8986. * @param onLoad callback called when the image successfully loads
  8987. * @param onError callback called when the image fails to load
  8988. * @param database database for caching
  8989. * @returns the HTMLImageElement of the loaded image
  8990. */
  8991. Tools.LoadImage = function (input, onLoad, onError, database) {
  8992. var url;
  8993. var usingObjectURL = false;
  8994. if (input instanceof ArrayBuffer) {
  8995. url = URL.createObjectURL(new Blob([input]));
  8996. usingObjectURL = true;
  8997. }
  8998. else if (input instanceof Blob) {
  8999. url = URL.createObjectURL(input);
  9000. usingObjectURL = true;
  9001. }
  9002. else {
  9003. url = Tools.CleanUrl(input);
  9004. url = Tools.PreprocessUrl(input);
  9005. }
  9006. var img = new Image();
  9007. Tools.SetCorsBehavior(url, img);
  9008. var loadHandler = function () {
  9009. if (usingObjectURL && img.src) {
  9010. URL.revokeObjectURL(img.src);
  9011. }
  9012. img.removeEventListener("load", loadHandler);
  9013. img.removeEventListener("error", errorHandler);
  9014. onLoad(img);
  9015. };
  9016. var errorHandler = function (err) {
  9017. if (usingObjectURL && img.src) {
  9018. URL.revokeObjectURL(img.src);
  9019. }
  9020. img.removeEventListener("load", loadHandler);
  9021. img.removeEventListener("error", errorHandler);
  9022. Tools.Error("Error while trying to load image: " + input);
  9023. if (onError) {
  9024. onError("Error while trying to load image: " + input, err);
  9025. }
  9026. };
  9027. img.addEventListener("load", loadHandler);
  9028. img.addEventListener("error", errorHandler);
  9029. var noIndexedDB = function () {
  9030. img.src = url;
  9031. };
  9032. var loadFromIndexedDB = function () {
  9033. if (database) {
  9034. database.loadImageFromDB(url, img);
  9035. }
  9036. };
  9037. //ANY database to do!
  9038. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  9039. database.openAsync(loadFromIndexedDB, noIndexedDB);
  9040. }
  9041. else {
  9042. if (url.indexOf("file:") !== -1) {
  9043. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  9044. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  9045. try {
  9046. var blobURL;
  9047. try {
  9048. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  9049. }
  9050. catch (ex) {
  9051. // Chrome doesn't support oneTimeOnly parameter
  9052. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  9053. }
  9054. img.src = blobURL;
  9055. usingObjectURL = true;
  9056. }
  9057. catch (e) {
  9058. img.src = "";
  9059. }
  9060. return img;
  9061. }
  9062. }
  9063. noIndexedDB();
  9064. }
  9065. return img;
  9066. };
  9067. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  9068. url = Tools.CleanUrl(url);
  9069. url = Tools.PreprocessUrl(url);
  9070. // If file and file input are set
  9071. if (url.indexOf("file:") !== -1) {
  9072. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  9073. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  9074. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  9075. }
  9076. }
  9077. var loadUrl = Tools.BaseUrl + url;
  9078. var aborted = false;
  9079. var fileRequest = {
  9080. onCompleteObservable: new BABYLON.Observable(),
  9081. abort: function () { return aborted = true; },
  9082. };
  9083. var requestFile = function () {
  9084. var request = new XMLHttpRequest();
  9085. var retryHandle = null;
  9086. fileRequest.abort = function () {
  9087. aborted = true;
  9088. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  9089. request.abort();
  9090. }
  9091. if (retryHandle !== null) {
  9092. clearTimeout(retryHandle);
  9093. retryHandle = null;
  9094. }
  9095. };
  9096. var retryLoop = function (retryIndex) {
  9097. request.open('GET', loadUrl, true);
  9098. if (useArrayBuffer) {
  9099. request.responseType = "arraybuffer";
  9100. }
  9101. if (onProgress) {
  9102. request.addEventListener("progress", onProgress);
  9103. }
  9104. var onLoadEnd = function () {
  9105. request.removeEventListener("loadend", onLoadEnd);
  9106. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9107. fileRequest.onCompleteObservable.clear();
  9108. };
  9109. request.addEventListener("loadend", onLoadEnd);
  9110. var onReadyStateChange = function () {
  9111. if (aborted) {
  9112. return;
  9113. }
  9114. // In case of undefined state in some browsers.
  9115. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  9116. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  9117. request.removeEventListener("readystatechange", onReadyStateChange);
  9118. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  9119. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  9120. return;
  9121. }
  9122. var retryStrategy = Tools.DefaultRetryStrategy;
  9123. if (retryStrategy) {
  9124. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  9125. if (waitTime !== -1) {
  9126. // Prevent the request from completing for retry.
  9127. request.removeEventListener("loadend", onLoadEnd);
  9128. request = new XMLHttpRequest();
  9129. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  9130. return;
  9131. }
  9132. }
  9133. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  9134. if (onError) {
  9135. onError(request, e);
  9136. }
  9137. else {
  9138. throw e;
  9139. }
  9140. }
  9141. };
  9142. request.addEventListener("readystatechange", onReadyStateChange);
  9143. request.send();
  9144. };
  9145. retryLoop(0);
  9146. };
  9147. // Caching all files
  9148. if (database && database.enableSceneOffline) {
  9149. var noIndexedDB_1 = function () {
  9150. if (!aborted) {
  9151. requestFile();
  9152. }
  9153. };
  9154. var loadFromIndexedDB = function () {
  9155. // TODO: database needs to support aborting and should return a IFileRequest
  9156. if (aborted) {
  9157. return;
  9158. }
  9159. if (database) {
  9160. database.loadFileFromDB(url, function (data) {
  9161. if (!aborted) {
  9162. onSuccess(data);
  9163. }
  9164. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9165. }, onProgress ? function (event) {
  9166. if (!aborted) {
  9167. onProgress(event);
  9168. }
  9169. } : undefined, noIndexedDB_1, useArrayBuffer);
  9170. }
  9171. };
  9172. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  9173. }
  9174. else {
  9175. requestFile();
  9176. }
  9177. return fileRequest;
  9178. };
  9179. /**
  9180. * Load a script (identified by an url). When the url returns, the
  9181. * content of this file is added into a new script element, attached to the DOM (body element)
  9182. */
  9183. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  9184. var head = document.getElementsByTagName('head')[0];
  9185. var script = document.createElement('script');
  9186. script.type = 'text/javascript';
  9187. script.src = scriptUrl;
  9188. script.onload = function () {
  9189. if (onSuccess) {
  9190. onSuccess();
  9191. }
  9192. };
  9193. script.onerror = function (e) {
  9194. if (onError) {
  9195. onError("Unable to load script '" + scriptUrl + "'", e);
  9196. }
  9197. };
  9198. head.appendChild(script);
  9199. };
  9200. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  9201. var reader = new FileReader();
  9202. var request = {
  9203. onCompleteObservable: new BABYLON.Observable(),
  9204. abort: function () { return reader.abort(); },
  9205. };
  9206. reader.onloadend = function (e) {
  9207. request.onCompleteObservable.notifyObservers(request);
  9208. };
  9209. reader.onload = function (e) {
  9210. //target doesn't have result from ts 1.3
  9211. callback(e.target['result']);
  9212. };
  9213. reader.onprogress = progressCallback;
  9214. reader.readAsDataURL(fileToLoad);
  9215. return request;
  9216. };
  9217. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  9218. var reader = new FileReader();
  9219. var request = {
  9220. onCompleteObservable: new BABYLON.Observable(),
  9221. abort: function () { return reader.abort(); },
  9222. };
  9223. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  9224. reader.onerror = function (e) {
  9225. Tools.Log("Error while reading file: " + fileToLoad.name);
  9226. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  9227. };
  9228. reader.onload = function (e) {
  9229. //target doesn't have result from ts 1.3
  9230. callback(e.target['result']);
  9231. };
  9232. if (progressCallBack) {
  9233. reader.onprogress = progressCallBack;
  9234. }
  9235. if (!useArrayBuffer) {
  9236. // Asynchronous read
  9237. reader.readAsText(fileToLoad);
  9238. }
  9239. else {
  9240. reader.readAsArrayBuffer(fileToLoad);
  9241. }
  9242. return request;
  9243. };
  9244. //returns a downloadable url to a file content.
  9245. Tools.FileAsURL = function (content) {
  9246. var fileBlob = new Blob([content]);
  9247. var url = window.URL || window.webkitURL;
  9248. var link = url.createObjectURL(fileBlob);
  9249. return link;
  9250. };
  9251. // Misc.
  9252. Tools.Format = function (value, decimals) {
  9253. if (decimals === void 0) { decimals = 2; }
  9254. return value.toFixed(decimals);
  9255. };
  9256. Tools.CheckExtends = function (v, min, max) {
  9257. if (v.x < min.x)
  9258. min.x = v.x;
  9259. if (v.y < min.y)
  9260. min.y = v.y;
  9261. if (v.z < min.z)
  9262. min.z = v.z;
  9263. if (v.x > max.x)
  9264. max.x = v.x;
  9265. if (v.y > max.y)
  9266. max.y = v.y;
  9267. if (v.z > max.z)
  9268. max.z = v.z;
  9269. };
  9270. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  9271. for (var prop in source) {
  9272. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  9273. continue;
  9274. }
  9275. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  9276. continue;
  9277. }
  9278. var sourceValue = source[prop];
  9279. var typeOfSourceValue = typeof sourceValue;
  9280. if (typeOfSourceValue === "function") {
  9281. continue;
  9282. }
  9283. try {
  9284. if (typeOfSourceValue === "object") {
  9285. if (sourceValue instanceof Array) {
  9286. destination[prop] = [];
  9287. if (sourceValue.length > 0) {
  9288. if (typeof sourceValue[0] == "object") {
  9289. for (var index = 0; index < sourceValue.length; index++) {
  9290. var clonedValue = cloneValue(sourceValue[index], destination);
  9291. if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done
  9292. destination[prop].push(clonedValue);
  9293. }
  9294. }
  9295. }
  9296. else {
  9297. destination[prop] = sourceValue.slice(0);
  9298. }
  9299. }
  9300. }
  9301. else {
  9302. destination[prop] = cloneValue(sourceValue, destination);
  9303. }
  9304. }
  9305. else {
  9306. destination[prop] = sourceValue;
  9307. }
  9308. }
  9309. catch (e) {
  9310. // Just ignore error (it could be because of a read-only property)
  9311. }
  9312. }
  9313. };
  9314. Tools.IsEmpty = function (obj) {
  9315. for (var i in obj) {
  9316. if (obj.hasOwnProperty(i)) {
  9317. return false;
  9318. }
  9319. }
  9320. return true;
  9321. };
  9322. Tools.RegisterTopRootEvents = function (events) {
  9323. for (var index = 0; index < events.length; index++) {
  9324. var event = events[index];
  9325. window.addEventListener(event.name, event.handler, false);
  9326. try {
  9327. if (window.parent) {
  9328. window.parent.addEventListener(event.name, event.handler, false);
  9329. }
  9330. }
  9331. catch (e) {
  9332. // Silently fails...
  9333. }
  9334. }
  9335. };
  9336. Tools.UnregisterTopRootEvents = function (events) {
  9337. for (var index = 0; index < events.length; index++) {
  9338. var event = events[index];
  9339. window.removeEventListener(event.name, event.handler);
  9340. try {
  9341. if (window.parent) {
  9342. window.parent.removeEventListener(event.name, event.handler);
  9343. }
  9344. }
  9345. catch (e) {
  9346. // Silently fails...
  9347. }
  9348. }
  9349. };
  9350. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  9351. if (mimeType === void 0) { mimeType = "image/png"; }
  9352. // Read the contents of the framebuffer
  9353. var numberOfChannelsByLine = width * 4;
  9354. var halfHeight = height / 2;
  9355. //Reading datas from WebGL
  9356. var data = engine.readPixels(0, 0, width, height);
  9357. //To flip image on Y axis.
  9358. for (var i = 0; i < halfHeight; i++) {
  9359. for (var j = 0; j < numberOfChannelsByLine; j++) {
  9360. var currentCell = j + i * numberOfChannelsByLine;
  9361. var targetLine = height - i - 1;
  9362. var targetCell = j + targetLine * numberOfChannelsByLine;
  9363. var temp = data[currentCell];
  9364. data[currentCell] = data[targetCell];
  9365. data[targetCell] = temp;
  9366. }
  9367. }
  9368. // Create a 2D canvas to store the result
  9369. if (!screenshotCanvas) {
  9370. screenshotCanvas = document.createElement('canvas');
  9371. }
  9372. screenshotCanvas.width = width;
  9373. screenshotCanvas.height = height;
  9374. var context = screenshotCanvas.getContext('2d');
  9375. if (context) {
  9376. // Copy the pixels to a 2D canvas
  9377. var imageData = context.createImageData(width, height);
  9378. var castData = (imageData.data);
  9379. castData.set(data);
  9380. context.putImageData(imageData, 0, 0);
  9381. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  9382. }
  9383. };
  9384. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  9385. if (mimeType === void 0) { mimeType = "image/png"; }
  9386. var base64Image = screenshotCanvas.toDataURL(mimeType);
  9387. if (successCallback) {
  9388. successCallback(base64Image);
  9389. }
  9390. else {
  9391. // We need HTMLCanvasElement.toBlob for HD screenshots
  9392. if (!screenshotCanvas.toBlob) {
  9393. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  9394. screenshotCanvas.toBlob = function (callback, type, quality) {
  9395. var _this = this;
  9396. setTimeout(function () {
  9397. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  9398. for (var i = 0; i < len; i++) {
  9399. arr[i] = binStr.charCodeAt(i);
  9400. }
  9401. callback(new Blob([arr], { type: type || 'image/png' }));
  9402. });
  9403. };
  9404. }
  9405. screenshotCanvas.toBlob(function (blob) {
  9406. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  9407. if (("download" in document.createElement("a"))) {
  9408. if (!fileName) {
  9409. var date = new Date();
  9410. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  9411. fileName = "screenshot_" + stringDate + ".png";
  9412. }
  9413. Tools.Download(blob, fileName);
  9414. }
  9415. else {
  9416. var url = URL.createObjectURL(blob);
  9417. var newWindow = window.open("");
  9418. if (!newWindow)
  9419. return;
  9420. var img = newWindow.document.createElement("img");
  9421. img.onload = function () {
  9422. // no longer need to read the blob so it's revoked
  9423. URL.revokeObjectURL(url);
  9424. };
  9425. img.src = url;
  9426. newWindow.document.body.appendChild(img);
  9427. }
  9428. });
  9429. }
  9430. };
  9431. /**
  9432. * Downloads a blob in the browser
  9433. * @param blob defines the blob to download
  9434. * @param fileName defines the name of the downloaded file
  9435. */
  9436. Tools.Download = function (blob, fileName) {
  9437. var url = window.URL.createObjectURL(blob);
  9438. var a = document.createElement("a");
  9439. document.body.appendChild(a);
  9440. a.style.display = "none";
  9441. a.href = url;
  9442. a.download = fileName;
  9443. a.addEventListener("click", function () {
  9444. if (a.parentElement) {
  9445. a.parentElement.removeChild(a);
  9446. }
  9447. });
  9448. a.click();
  9449. window.URL.revokeObjectURL(url);
  9450. };
  9451. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  9452. if (mimeType === void 0) { mimeType = "image/png"; }
  9453. var width;
  9454. var height;
  9455. // If a precision value is specified
  9456. if (size.precision) {
  9457. width = Math.round(engine.getRenderWidth() * size.precision);
  9458. height = Math.round(width / engine.getAspectRatio(camera));
  9459. }
  9460. else if (size.width && size.height) {
  9461. width = size.width;
  9462. height = size.height;
  9463. }
  9464. //If passing only width, computing height to keep display canvas ratio.
  9465. else if (size.width && !size.height) {
  9466. width = size.width;
  9467. height = Math.round(width / engine.getAspectRatio(camera));
  9468. }
  9469. //If passing only height, computing width to keep display canvas ratio.
  9470. else if (size.height && !size.width) {
  9471. height = size.height;
  9472. width = Math.round(height * engine.getAspectRatio(camera));
  9473. }
  9474. //Assuming here that "size" parameter is a number
  9475. else if (!isNaN(size)) {
  9476. height = size;
  9477. width = size;
  9478. }
  9479. else {
  9480. Tools.Error("Invalid 'size' parameter !");
  9481. return;
  9482. }
  9483. if (!screenshotCanvas) {
  9484. screenshotCanvas = document.createElement('canvas');
  9485. }
  9486. screenshotCanvas.width = width;
  9487. screenshotCanvas.height = height;
  9488. var renderContext = screenshotCanvas.getContext("2d");
  9489. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  9490. var newWidth = width;
  9491. var newHeight = newWidth / ratio;
  9492. if (newHeight > height) {
  9493. newHeight = height;
  9494. newWidth = newHeight * ratio;
  9495. }
  9496. var offsetX = Math.max(0, width - newWidth) / 2;
  9497. var offsetY = Math.max(0, height - newHeight) / 2;
  9498. var renderingCanvas = engine.getRenderingCanvas();
  9499. if (renderContext && renderingCanvas) {
  9500. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  9501. }
  9502. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  9503. };
  9504. /**
  9505. * Generates an image screenshot from the specified camera.
  9506. *
  9507. * @param engine The engine to use for rendering
  9508. * @param camera The camera to use for rendering
  9509. * @param size This parameter can be set to a single number or to an object with the
  9510. * following (optional) properties: precision, width, height. If a single number is passed,
  9511. * it will be used for both width and height. If an object is passed, the screenshot size
  9512. * will be derived from the parameters. The precision property is a multiplier allowing
  9513. * rendering at a higher or lower resolution.
  9514. * @param successCallback The callback receives a single parameter which contains the
  9515. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  9516. * src parameter of an <img> to display it.
  9517. * @param mimeType The MIME type of the screenshot image (default: image/png).
  9518. * Check your browser for supported MIME types.
  9519. * @param samples Texture samples (default: 1)
  9520. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  9521. * @param fileName A name for for the downloaded file.
  9522. * @constructor
  9523. */
  9524. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  9525. if (mimeType === void 0) { mimeType = "image/png"; }
  9526. if (samples === void 0) { samples = 1; }
  9527. if (antialiasing === void 0) { antialiasing = false; }
  9528. var width;
  9529. var height;
  9530. //If a precision value is specified
  9531. if (size.precision) {
  9532. width = Math.round(engine.getRenderWidth() * size.precision);
  9533. height = Math.round(width / engine.getAspectRatio(camera));
  9534. size = { width: width, height: height };
  9535. }
  9536. else if (size.width && size.height) {
  9537. width = size.width;
  9538. height = size.height;
  9539. }
  9540. //If passing only width, computing height to keep display canvas ratio.
  9541. else if (size.width && !size.height) {
  9542. width = size.width;
  9543. height = Math.round(width / engine.getAspectRatio(camera));
  9544. size = { width: width, height: height };
  9545. }
  9546. //If passing only height, computing width to keep display canvas ratio.
  9547. else if (size.height && !size.width) {
  9548. height = size.height;
  9549. width = Math.round(height * engine.getAspectRatio(camera));
  9550. size = { width: width, height: height };
  9551. }
  9552. //Assuming here that "size" parameter is a number
  9553. else if (!isNaN(size)) {
  9554. height = size;
  9555. width = size;
  9556. }
  9557. else {
  9558. Tools.Error("Invalid 'size' parameter !");
  9559. return;
  9560. }
  9561. var scene = camera.getScene();
  9562. var previousCamera = null;
  9563. if (scene.activeCamera !== camera) {
  9564. previousCamera = scene.activeCamera;
  9565. scene.activeCamera = camera;
  9566. }
  9567. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  9568. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9569. texture.renderList = null;
  9570. texture.samples = samples;
  9571. if (antialiasing) {
  9572. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  9573. }
  9574. texture.onAfterRenderObservable.add(function () {
  9575. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  9576. });
  9577. scene.incrementRenderId();
  9578. scene.resetCachedMaterial();
  9579. texture.render(true);
  9580. texture.dispose();
  9581. if (previousCamera) {
  9582. scene.activeCamera = previousCamera;
  9583. }
  9584. camera.getProjectionMatrix(true); // Force cache refresh;
  9585. };
  9586. // XHR response validator for local file scenario
  9587. Tools.ValidateXHRData = function (xhr, dataType) {
  9588. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  9589. if (dataType === void 0) { dataType = 7; }
  9590. try {
  9591. if (dataType & 1) {
  9592. if (xhr.responseText && xhr.responseText.length > 0) {
  9593. return true;
  9594. }
  9595. else if (dataType === 1) {
  9596. return false;
  9597. }
  9598. }
  9599. if (dataType & 2) {
  9600. // Check header width and height since there is no "TGA" magic number
  9601. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  9602. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  9603. return true;
  9604. }
  9605. else if (dataType === 2) {
  9606. return false;
  9607. }
  9608. }
  9609. if (dataType & 4) {
  9610. // Check for the "DDS" magic number
  9611. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  9612. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  9613. return true;
  9614. }
  9615. else {
  9616. return false;
  9617. }
  9618. }
  9619. }
  9620. catch (e) {
  9621. // Global protection
  9622. }
  9623. return false;
  9624. };
  9625. /**
  9626. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  9627. * Be aware Math.random() could cause collisions, but:
  9628. * "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"
  9629. */
  9630. Tools.RandomId = function () {
  9631. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  9632. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  9633. return v.toString(16);
  9634. });
  9635. };
  9636. /**
  9637. * Test if the given uri is a base64 string.
  9638. * @param uri The uri to test
  9639. * @return True if the uri is a base64 string or false otherwise.
  9640. */
  9641. Tools.IsBase64 = function (uri) {
  9642. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  9643. };
  9644. /**
  9645. * Decode the given base64 uri.
  9646. * @param uri The uri to decode
  9647. * @return The decoded base64 data.
  9648. */
  9649. Tools.DecodeBase64 = function (uri) {
  9650. var decodedString = atob(uri.split(",")[1]);
  9651. var bufferLength = decodedString.length;
  9652. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  9653. for (var i = 0; i < bufferLength; i++) {
  9654. bufferView[i] = decodedString.charCodeAt(i);
  9655. }
  9656. return bufferView.buffer;
  9657. };
  9658. Object.defineProperty(Tools, "NoneLogLevel", {
  9659. get: function () {
  9660. return Tools._NoneLogLevel;
  9661. },
  9662. enumerable: true,
  9663. configurable: true
  9664. });
  9665. Object.defineProperty(Tools, "MessageLogLevel", {
  9666. get: function () {
  9667. return Tools._MessageLogLevel;
  9668. },
  9669. enumerable: true,
  9670. configurable: true
  9671. });
  9672. Object.defineProperty(Tools, "WarningLogLevel", {
  9673. get: function () {
  9674. return Tools._WarningLogLevel;
  9675. },
  9676. enumerable: true,
  9677. configurable: true
  9678. });
  9679. Object.defineProperty(Tools, "ErrorLogLevel", {
  9680. get: function () {
  9681. return Tools._ErrorLogLevel;
  9682. },
  9683. enumerable: true,
  9684. configurable: true
  9685. });
  9686. Object.defineProperty(Tools, "AllLogLevel", {
  9687. get: function () {
  9688. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  9689. },
  9690. enumerable: true,
  9691. configurable: true
  9692. });
  9693. Tools._AddLogEntry = function (entry) {
  9694. Tools._LogCache = entry + Tools._LogCache;
  9695. if (Tools.OnNewCacheEntry) {
  9696. Tools.OnNewCacheEntry(entry);
  9697. }
  9698. };
  9699. Tools._FormatMessage = function (message) {
  9700. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  9701. var date = new Date();
  9702. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  9703. };
  9704. Tools._LogDisabled = function (message) {
  9705. // nothing to do
  9706. };
  9707. Tools._LogEnabled = function (message) {
  9708. var formattedMessage = Tools._FormatMessage(message);
  9709. console.log("BJS - " + formattedMessage);
  9710. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  9711. Tools._AddLogEntry(entry);
  9712. };
  9713. Tools._WarnDisabled = function (message) {
  9714. // nothing to do
  9715. };
  9716. Tools._WarnEnabled = function (message) {
  9717. var formattedMessage = Tools._FormatMessage(message);
  9718. console.warn("BJS - " + formattedMessage);
  9719. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  9720. Tools._AddLogEntry(entry);
  9721. };
  9722. Tools._ErrorDisabled = function (message) {
  9723. // nothing to do
  9724. };
  9725. Tools._ErrorEnabled = function (message) {
  9726. Tools.errorsCount++;
  9727. var formattedMessage = Tools._FormatMessage(message);
  9728. console.error("BJS - " + formattedMessage);
  9729. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  9730. Tools._AddLogEntry(entry);
  9731. };
  9732. Object.defineProperty(Tools, "LogCache", {
  9733. get: function () {
  9734. return Tools._LogCache;
  9735. },
  9736. enumerable: true,
  9737. configurable: true
  9738. });
  9739. Tools.ClearLogCache = function () {
  9740. Tools._LogCache = "";
  9741. Tools.errorsCount = 0;
  9742. };
  9743. Object.defineProperty(Tools, "LogLevels", {
  9744. set: function (level) {
  9745. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  9746. Tools.Log = Tools._LogEnabled;
  9747. }
  9748. else {
  9749. Tools.Log = Tools._LogDisabled;
  9750. }
  9751. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  9752. Tools.Warn = Tools._WarnEnabled;
  9753. }
  9754. else {
  9755. Tools.Warn = Tools._WarnDisabled;
  9756. }
  9757. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  9758. Tools.Error = Tools._ErrorEnabled;
  9759. }
  9760. else {
  9761. Tools.Error = Tools._ErrorDisabled;
  9762. }
  9763. },
  9764. enumerable: true,
  9765. configurable: true
  9766. });
  9767. Tools.IsWindowObjectExist = function () {
  9768. return (typeof window) !== "undefined";
  9769. };
  9770. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  9771. get: function () {
  9772. return Tools._PerformanceNoneLogLevel;
  9773. },
  9774. enumerable: true,
  9775. configurable: true
  9776. });
  9777. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  9778. get: function () {
  9779. return Tools._PerformanceUserMarkLogLevel;
  9780. },
  9781. enumerable: true,
  9782. configurable: true
  9783. });
  9784. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  9785. get: function () {
  9786. return Tools._PerformanceConsoleLogLevel;
  9787. },
  9788. enumerable: true,
  9789. configurable: true
  9790. });
  9791. Object.defineProperty(Tools, "PerformanceLogLevel", {
  9792. set: function (level) {
  9793. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  9794. Tools.StartPerformanceCounter = Tools._StartUserMark;
  9795. Tools.EndPerformanceCounter = Tools._EndUserMark;
  9796. return;
  9797. }
  9798. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  9799. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  9800. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  9801. return;
  9802. }
  9803. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9804. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9805. },
  9806. enumerable: true,
  9807. configurable: true
  9808. });
  9809. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  9810. };
  9811. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  9812. };
  9813. Tools._StartUserMark = function (counterName, condition) {
  9814. if (condition === void 0) { condition = true; }
  9815. if (!Tools._performance) {
  9816. if (!Tools.IsWindowObjectExist()) {
  9817. return;
  9818. }
  9819. Tools._performance = window.performance;
  9820. }
  9821. if (!condition || !Tools._performance.mark) {
  9822. return;
  9823. }
  9824. Tools._performance.mark(counterName + "-Begin");
  9825. };
  9826. Tools._EndUserMark = function (counterName, condition) {
  9827. if (condition === void 0) { condition = true; }
  9828. if (!condition || !Tools._performance.mark) {
  9829. return;
  9830. }
  9831. Tools._performance.mark(counterName + "-End");
  9832. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  9833. };
  9834. Tools._StartPerformanceConsole = function (counterName, condition) {
  9835. if (condition === void 0) { condition = true; }
  9836. if (!condition) {
  9837. return;
  9838. }
  9839. Tools._StartUserMark(counterName, condition);
  9840. if (console.time) {
  9841. console.time(counterName);
  9842. }
  9843. };
  9844. Tools._EndPerformanceConsole = function (counterName, condition) {
  9845. if (condition === void 0) { condition = true; }
  9846. if (!condition) {
  9847. return;
  9848. }
  9849. Tools._EndUserMark(counterName, condition);
  9850. if (console.time) {
  9851. console.timeEnd(counterName);
  9852. }
  9853. };
  9854. Object.defineProperty(Tools, "Now", {
  9855. get: function () {
  9856. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  9857. return window.performance.now();
  9858. }
  9859. return Date.now();
  9860. },
  9861. enumerable: true,
  9862. configurable: true
  9863. });
  9864. /**
  9865. * This method will return the name of the class used to create the instance of the given object.
  9866. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  9867. * @param object the object to get the class name from
  9868. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  9869. */
  9870. Tools.GetClassName = function (object, isType) {
  9871. if (isType === void 0) { isType = false; }
  9872. var name = null;
  9873. if (!isType && object.getClassName) {
  9874. name = object.getClassName();
  9875. }
  9876. else {
  9877. if (object instanceof Object) {
  9878. var classObj = isType ? object : Object.getPrototypeOf(object);
  9879. name = classObj.constructor["__bjsclassName__"];
  9880. }
  9881. if (!name) {
  9882. name = typeof object;
  9883. }
  9884. }
  9885. return name;
  9886. };
  9887. Tools.First = function (array, predicate) {
  9888. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  9889. var el = array_1[_i];
  9890. if (predicate(el)) {
  9891. return el;
  9892. }
  9893. }
  9894. return null;
  9895. };
  9896. /**
  9897. * This method will return the name of the full name of the class, including its owning module (if any).
  9898. * 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).
  9899. * @param object the object to get the class name from
  9900. * @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.
  9901. */
  9902. Tools.getFullClassName = function (object, isType) {
  9903. if (isType === void 0) { isType = false; }
  9904. var className = null;
  9905. var moduleName = null;
  9906. if (!isType && object.getClassName) {
  9907. className = object.getClassName();
  9908. }
  9909. else {
  9910. if (object instanceof Object) {
  9911. var classObj = isType ? object : Object.getPrototypeOf(object);
  9912. className = classObj.constructor["__bjsclassName__"];
  9913. moduleName = classObj.constructor["__bjsmoduleName__"];
  9914. }
  9915. if (!className) {
  9916. className = typeof object;
  9917. }
  9918. }
  9919. if (!className) {
  9920. return null;
  9921. }
  9922. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  9923. };
  9924. /**
  9925. * 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.
  9926. * @param array
  9927. */
  9928. Tools.arrayOrStringFeeder = function (array) {
  9929. return function (index) {
  9930. if (index >= array.length) {
  9931. return null;
  9932. }
  9933. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  9934. if (val && val.getHashCode) {
  9935. val = val.getHashCode();
  9936. }
  9937. if (typeof val === "string") {
  9938. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  9939. }
  9940. return val;
  9941. };
  9942. };
  9943. /**
  9944. * Compute the hashCode of a stream of number
  9945. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  9946. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  9947. * @return the hash code computed
  9948. */
  9949. Tools.hashCodeFromStream = function (feeder) {
  9950. // Based from here: http://stackoverflow.com/a/7616484/802124
  9951. var hash = 0;
  9952. var index = 0;
  9953. var chr = feeder(index++);
  9954. while (chr != null) {
  9955. hash = ((hash << 5) - hash) + chr;
  9956. hash |= 0; // Convert to 32bit integer
  9957. chr = feeder(index++);
  9958. }
  9959. return hash;
  9960. };
  9961. /**
  9962. * Returns a promise that resolves after the given amount of time.
  9963. * @param delay Number of milliseconds to delay
  9964. * @returns Promise that resolves after the given amount of time
  9965. */
  9966. Tools.DelayAsync = function (delay) {
  9967. return new Promise(function (resolve) {
  9968. setTimeout(function () {
  9969. resolve();
  9970. }, delay);
  9971. });
  9972. };
  9973. Tools.BaseUrl = "";
  9974. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  9975. /**
  9976. * Default behaviour for cors in the application.
  9977. * It can be a string if the expected behavior is identical in the entire app.
  9978. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  9979. */
  9980. Tools.CorsBehavior = "anonymous";
  9981. Tools.UseFallbackTexture = true;
  9982. /**
  9983. * Use this object to register external classes like custom textures or material
  9984. * to allow the laoders to instantiate them
  9985. */
  9986. Tools.RegisteredExternalClasses = {};
  9987. // Used in case of a texture loading problem
  9988. Tools.fallbackTexture = "data:image/jpg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QBmRXhpZgAATU0AKgAAAAgABAEaAAUAAAABAAAAPgEbAAUAAAABAAAARgEoAAMAAAABAAIAAAExAAIAAAAQAAAATgAAAAAAAABgAAAAAQAAAGAAAAABcGFpbnQubmV0IDQuMC41AP/bAEMABAIDAwMCBAMDAwQEBAQFCQYFBQUFCwgIBgkNCw0NDQsMDA4QFBEODxMPDAwSGBITFRYXFxcOERkbGRYaFBYXFv/bAEMBBAQEBQUFCgYGChYPDA8WFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFv/AABEIAQABAAMBIgACEQEDEQH/xAAfAAABBQEBAQEBAQAAAAAAAAAAAQIDBAUGBwgJCgv/xAC1EAACAQMDAgQDBQUEBAAAAX0BAgMABBEFEiExQQYTUWEHInEUMoGRoQgjQrHBFVLR8CQzYnKCCQoWFx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+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";
  9989. Tools._tmpFloatArray = new Float32Array(1);
  9990. Tools.PreprocessUrl = function (url) {
  9991. return url;
  9992. };
  9993. // Logs
  9994. Tools._NoneLogLevel = 0;
  9995. Tools._MessageLogLevel = 1;
  9996. Tools._WarningLogLevel = 2;
  9997. Tools._ErrorLogLevel = 4;
  9998. Tools._LogCache = "";
  9999. Tools.errorsCount = 0;
  10000. Tools.Log = Tools._LogEnabled;
  10001. Tools.Warn = Tools._WarnEnabled;
  10002. Tools.Error = Tools._ErrorEnabled;
  10003. // Performances
  10004. Tools._PerformanceNoneLogLevel = 0;
  10005. Tools._PerformanceUserMarkLogLevel = 1;
  10006. Tools._PerformanceConsoleLogLevel = 2;
  10007. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  10008. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  10009. return Tools;
  10010. }());
  10011. BABYLON.Tools = Tools;
  10012. /**
  10013. * This class is used to track a performance counter which is number based.
  10014. * The user has access to many properties which give statistics of different nature
  10015. *
  10016. * The implementer can track two kinds of Performance Counter: time and count
  10017. * 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.
  10018. * 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.
  10019. */
  10020. var PerfCounter = /** @class */ (function () {
  10021. function PerfCounter() {
  10022. this._startMonitoringTime = 0;
  10023. this._min = 0;
  10024. this._max = 0;
  10025. this._average = 0;
  10026. this._lastSecAverage = 0;
  10027. this._current = 0;
  10028. this._totalValueCount = 0;
  10029. this._totalAccumulated = 0;
  10030. this._lastSecAccumulated = 0;
  10031. this._lastSecTime = 0;
  10032. this._lastSecValueCount = 0;
  10033. }
  10034. Object.defineProperty(PerfCounter.prototype, "min", {
  10035. /**
  10036. * Returns the smallest value ever
  10037. */
  10038. get: function () {
  10039. return this._min;
  10040. },
  10041. enumerable: true,
  10042. configurable: true
  10043. });
  10044. Object.defineProperty(PerfCounter.prototype, "max", {
  10045. /**
  10046. * Returns the biggest value ever
  10047. */
  10048. get: function () {
  10049. return this._max;
  10050. },
  10051. enumerable: true,
  10052. configurable: true
  10053. });
  10054. Object.defineProperty(PerfCounter.prototype, "average", {
  10055. /**
  10056. * Returns the average value since the performance counter is running
  10057. */
  10058. get: function () {
  10059. return this._average;
  10060. },
  10061. enumerable: true,
  10062. configurable: true
  10063. });
  10064. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  10065. /**
  10066. * Returns the average value of the last second the counter was monitored
  10067. */
  10068. get: function () {
  10069. return this._lastSecAverage;
  10070. },
  10071. enumerable: true,
  10072. configurable: true
  10073. });
  10074. Object.defineProperty(PerfCounter.prototype, "current", {
  10075. /**
  10076. * Returns the current value
  10077. */
  10078. get: function () {
  10079. return this._current;
  10080. },
  10081. enumerable: true,
  10082. configurable: true
  10083. });
  10084. Object.defineProperty(PerfCounter.prototype, "total", {
  10085. get: function () {
  10086. return this._totalAccumulated;
  10087. },
  10088. enumerable: true,
  10089. configurable: true
  10090. });
  10091. Object.defineProperty(PerfCounter.prototype, "count", {
  10092. get: function () {
  10093. return this._totalValueCount;
  10094. },
  10095. enumerable: true,
  10096. configurable: true
  10097. });
  10098. /**
  10099. * Call this method to start monitoring a new frame.
  10100. * 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.
  10101. */
  10102. PerfCounter.prototype.fetchNewFrame = function () {
  10103. this._totalValueCount++;
  10104. this._current = 0;
  10105. this._lastSecValueCount++;
  10106. };
  10107. /**
  10108. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  10109. * @param newCount the count value to add to the monitored count
  10110. * @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.
  10111. */
  10112. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  10113. if (!PerfCounter.Enabled) {
  10114. return;
  10115. }
  10116. this._current += newCount;
  10117. if (fetchResult) {
  10118. this._fetchResult();
  10119. }
  10120. };
  10121. /**
  10122. * Start monitoring this performance counter
  10123. */
  10124. PerfCounter.prototype.beginMonitoring = function () {
  10125. if (!PerfCounter.Enabled) {
  10126. return;
  10127. }
  10128. this._startMonitoringTime = Tools.Now;
  10129. };
  10130. /**
  10131. * Compute the time lapsed since the previous beginMonitoring() call.
  10132. * @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
  10133. */
  10134. PerfCounter.prototype.endMonitoring = function (newFrame) {
  10135. if (newFrame === void 0) { newFrame = true; }
  10136. if (!PerfCounter.Enabled) {
  10137. return;
  10138. }
  10139. if (newFrame) {
  10140. this.fetchNewFrame();
  10141. }
  10142. var currentTime = Tools.Now;
  10143. this._current = currentTime - this._startMonitoringTime;
  10144. if (newFrame) {
  10145. this._fetchResult();
  10146. }
  10147. };
  10148. PerfCounter.prototype._fetchResult = function () {
  10149. this._totalAccumulated += this._current;
  10150. this._lastSecAccumulated += this._current;
  10151. // Min/Max update
  10152. this._min = Math.min(this._min, this._current);
  10153. this._max = Math.max(this._max, this._current);
  10154. this._average = this._totalAccumulated / this._totalValueCount;
  10155. // Reset last sec?
  10156. var now = Tools.Now;
  10157. if ((now - this._lastSecTime) > 1000) {
  10158. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  10159. this._lastSecTime = now;
  10160. this._lastSecAccumulated = 0;
  10161. this._lastSecValueCount = 0;
  10162. }
  10163. };
  10164. PerfCounter.Enabled = true;
  10165. return PerfCounter;
  10166. }());
  10167. BABYLON.PerfCounter = PerfCounter;
  10168. /**
  10169. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  10170. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  10171. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  10172. * @param name The name of the class, case should be preserved
  10173. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  10174. */
  10175. function className(name, module) {
  10176. return function (target) {
  10177. target["__bjsclassName__"] = name;
  10178. target["__bjsmoduleName__"] = (module != null) ? module : null;
  10179. };
  10180. }
  10181. BABYLON.className = className;
  10182. /**
  10183. * An implementation of a loop for asynchronous functions.
  10184. */
  10185. var AsyncLoop = /** @class */ (function () {
  10186. /**
  10187. * Constroctor.
  10188. * @param iterations the number of iterations.
  10189. * @param _fn the function to run each iteration
  10190. * @param _successCallback the callback that will be called upon succesful execution
  10191. * @param offset starting offset.
  10192. */
  10193. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  10194. if (offset === void 0) { offset = 0; }
  10195. this.iterations = iterations;
  10196. this._fn = _fn;
  10197. this._successCallback = _successCallback;
  10198. this.index = offset - 1;
  10199. this._done = false;
  10200. }
  10201. /**
  10202. * Execute the next iteration. Must be called after the last iteration was finished.
  10203. */
  10204. AsyncLoop.prototype.executeNext = function () {
  10205. if (!this._done) {
  10206. if (this.index + 1 < this.iterations) {
  10207. ++this.index;
  10208. this._fn(this);
  10209. }
  10210. else {
  10211. this.breakLoop();
  10212. }
  10213. }
  10214. };
  10215. /**
  10216. * Break the loop and run the success callback.
  10217. */
  10218. AsyncLoop.prototype.breakLoop = function () {
  10219. this._done = true;
  10220. this._successCallback();
  10221. };
  10222. /**
  10223. * Helper function
  10224. */
  10225. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  10226. if (offset === void 0) { offset = 0; }
  10227. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  10228. loop.executeNext();
  10229. return loop;
  10230. };
  10231. /**
  10232. * A for-loop that will run a given number of iterations synchronous and the rest async.
  10233. * @param iterations total number of iterations
  10234. * @param syncedIterations number of synchronous iterations in each async iteration.
  10235. * @param fn the function to call each iteration.
  10236. * @param callback a success call back that will be called when iterating stops.
  10237. * @param breakFunction a break condition (optional)
  10238. * @param timeout timeout settings for the setTimeout function. default - 0.
  10239. * @constructor
  10240. */
  10241. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  10242. if (timeout === void 0) { timeout = 0; }
  10243. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  10244. if (breakFunction && breakFunction())
  10245. loop.breakLoop();
  10246. else {
  10247. setTimeout(function () {
  10248. for (var i = 0; i < syncedIterations; ++i) {
  10249. var iteration = (loop.index * syncedIterations) + i;
  10250. if (iteration >= iterations)
  10251. break;
  10252. fn(iteration);
  10253. if (breakFunction && breakFunction()) {
  10254. loop.breakLoop();
  10255. break;
  10256. }
  10257. }
  10258. loop.executeNext();
  10259. }, timeout);
  10260. }
  10261. }, callback);
  10262. };
  10263. return AsyncLoop;
  10264. }());
  10265. BABYLON.AsyncLoop = AsyncLoop;
  10266. })(BABYLON || (BABYLON = {}));
  10267. //# sourceMappingURL=babylon.tools.js.map
  10268. var BABYLON;
  10269. (function (BABYLON) {
  10270. var PromiseStates;
  10271. (function (PromiseStates) {
  10272. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  10273. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  10274. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  10275. })(PromiseStates || (PromiseStates = {}));
  10276. var FulFillmentAgregator = /** @class */ (function () {
  10277. function FulFillmentAgregator() {
  10278. this.count = 0;
  10279. this.target = 0;
  10280. this.results = [];
  10281. }
  10282. return FulFillmentAgregator;
  10283. }());
  10284. var InternalPromise = /** @class */ (function () {
  10285. function InternalPromise(resolver) {
  10286. var _this = this;
  10287. this._state = PromiseStates.Pending;
  10288. this._children = new Array();
  10289. this._rejectWasConsumed = false;
  10290. if (!resolver) {
  10291. return;
  10292. }
  10293. try {
  10294. resolver(function (value) {
  10295. _this._resolve(value);
  10296. }, function (reason) {
  10297. _this._reject(reason);
  10298. });
  10299. }
  10300. catch (e) {
  10301. this._reject(e);
  10302. }
  10303. }
  10304. Object.defineProperty(InternalPromise.prototype, "_result", {
  10305. get: function () {
  10306. return this._resultValue;
  10307. },
  10308. set: function (value) {
  10309. this._resultValue = value;
  10310. if (this._parent && this._parent._result === undefined) {
  10311. this._parent._result = value;
  10312. }
  10313. },
  10314. enumerable: true,
  10315. configurable: true
  10316. });
  10317. InternalPromise.prototype.catch = function (onRejected) {
  10318. return this.then(undefined, onRejected);
  10319. };
  10320. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  10321. var _this = this;
  10322. var newPromise = new InternalPromise();
  10323. newPromise._onFulfilled = onFulfilled;
  10324. newPromise._onRejected = onRejected;
  10325. // Composition
  10326. this._children.push(newPromise);
  10327. newPromise._parent = this;
  10328. if (this._state !== PromiseStates.Pending) {
  10329. BABYLON.Tools.SetImmediate(function () {
  10330. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  10331. var returnedValue = newPromise._resolve(_this._result);
  10332. if (returnedValue !== undefined && returnedValue !== null) {
  10333. if (returnedValue._state !== undefined) {
  10334. var returnedPromise = returnedValue;
  10335. newPromise._children.push(returnedPromise);
  10336. returnedPromise._parent = newPromise;
  10337. newPromise = returnedPromise;
  10338. }
  10339. else {
  10340. newPromise._result = returnedValue;
  10341. }
  10342. }
  10343. }
  10344. else {
  10345. newPromise._reject(_this._reason);
  10346. }
  10347. });
  10348. }
  10349. return newPromise;
  10350. };
  10351. InternalPromise.prototype._moveChildren = function (children) {
  10352. var _this = this;
  10353. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  10354. this._children.forEach(function (child) {
  10355. child._parent = _this;
  10356. });
  10357. if (this._state === PromiseStates.Fulfilled) {
  10358. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  10359. var child = _b[_i];
  10360. child._resolve(this._result);
  10361. }
  10362. }
  10363. else if (this._state === PromiseStates.Rejected) {
  10364. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  10365. var child = _d[_c];
  10366. child._reject(this._reason);
  10367. }
  10368. }
  10369. var _a;
  10370. };
  10371. InternalPromise.prototype._resolve = function (value) {
  10372. try {
  10373. this._state = PromiseStates.Fulfilled;
  10374. var returnedValue = null;
  10375. if (this._onFulfilled) {
  10376. returnedValue = this._onFulfilled(value);
  10377. }
  10378. if (returnedValue !== undefined && returnedValue !== null) {
  10379. if (returnedValue._state !== undefined) {
  10380. // Transmit children
  10381. var returnedPromise = returnedValue;
  10382. returnedPromise._parent = this;
  10383. returnedPromise._moveChildren(this._children);
  10384. value = returnedPromise._result;
  10385. }
  10386. else {
  10387. value = returnedValue;
  10388. }
  10389. }
  10390. this._result = value;
  10391. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10392. var child = _a[_i];
  10393. child._resolve(value);
  10394. }
  10395. this._children.length = 0;
  10396. delete this._onFulfilled;
  10397. delete this._onRejected;
  10398. }
  10399. catch (e) {
  10400. this._reject(e, true);
  10401. }
  10402. };
  10403. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  10404. if (onLocalThrow === void 0) { onLocalThrow = false; }
  10405. this._state = PromiseStates.Rejected;
  10406. this._reason = reason;
  10407. if (this._onRejected && !onLocalThrow) {
  10408. try {
  10409. this._onRejected(reason);
  10410. this._rejectWasConsumed = true;
  10411. }
  10412. catch (e) {
  10413. reason = e;
  10414. }
  10415. }
  10416. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10417. var child = _a[_i];
  10418. if (this._rejectWasConsumed) {
  10419. child._resolve(null);
  10420. }
  10421. else {
  10422. child._reject(reason);
  10423. }
  10424. }
  10425. this._children.length = 0;
  10426. delete this._onFulfilled;
  10427. delete this._onRejected;
  10428. };
  10429. InternalPromise.resolve = function (value) {
  10430. var newPromise = new InternalPromise();
  10431. newPromise._resolve(value);
  10432. return newPromise;
  10433. };
  10434. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  10435. promise.then(function (value) {
  10436. agregator.results[index] = value;
  10437. agregator.count++;
  10438. if (agregator.count === agregator.target) {
  10439. agregator.rootPromise._resolve(agregator.results);
  10440. }
  10441. return null;
  10442. }, function (reason) {
  10443. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  10444. agregator.rootPromise._reject(reason);
  10445. }
  10446. });
  10447. };
  10448. InternalPromise.all = function (promises) {
  10449. var newPromise = new InternalPromise();
  10450. var agregator = new FulFillmentAgregator();
  10451. agregator.target = promises.length;
  10452. agregator.rootPromise = newPromise;
  10453. if (promises.length) {
  10454. for (var index = 0; index < promises.length; index++) {
  10455. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  10456. }
  10457. }
  10458. else {
  10459. newPromise._resolve([]);
  10460. }
  10461. return newPromise;
  10462. };
  10463. InternalPromise.race = function (promises) {
  10464. var newPromise = new InternalPromise();
  10465. if (promises.length) {
  10466. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  10467. var promise = promises_1[_i];
  10468. promise.then(function (value) {
  10469. if (newPromise) {
  10470. newPromise._resolve(value);
  10471. newPromise = null;
  10472. }
  10473. return null;
  10474. }, function (reason) {
  10475. if (newPromise) {
  10476. newPromise._reject(reason);
  10477. newPromise = null;
  10478. }
  10479. });
  10480. }
  10481. }
  10482. return newPromise;
  10483. };
  10484. return InternalPromise;
  10485. }());
  10486. /**
  10487. * Helper class that provides a small promise polyfill
  10488. */
  10489. var PromisePolyfill = /** @class */ (function () {
  10490. function PromisePolyfill() {
  10491. }
  10492. /**
  10493. * Static function used to check if the polyfill is required
  10494. * If this is the case then the function will inject the polyfill to window.Promise
  10495. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  10496. */
  10497. PromisePolyfill.Apply = function (force) {
  10498. if (force === void 0) { force = false; }
  10499. if (force || typeof Promise === 'undefined') {
  10500. var root = window;
  10501. root.Promise = InternalPromise;
  10502. }
  10503. };
  10504. return PromisePolyfill;
  10505. }());
  10506. BABYLON.PromisePolyfill = PromisePolyfill;
  10507. })(BABYLON || (BABYLON = {}));
  10508. //# sourceMappingURL=babylon.promise.js.map
  10509. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  10510. var BABYLON;
  10511. (function (BABYLON) {
  10512. /**
  10513. * Helper class to push actions to a pool of workers.
  10514. */
  10515. var WorkerPool = /** @class */ (function () {
  10516. /**
  10517. * Constructor
  10518. * @param workers Array of workers to use for actions
  10519. */
  10520. function WorkerPool(workers) {
  10521. this._pendingActions = new Array();
  10522. this._workerInfos = workers.map(function (worker) { return ({
  10523. worker: worker,
  10524. active: false
  10525. }); });
  10526. }
  10527. /**
  10528. * Terminates all workers and clears any pending actions.
  10529. */
  10530. WorkerPool.prototype.dispose = function () {
  10531. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10532. var workerInfo = _a[_i];
  10533. workerInfo.worker.terminate();
  10534. }
  10535. delete this._workerInfos;
  10536. delete this._pendingActions;
  10537. };
  10538. /**
  10539. * Pushes an action to the worker pool. If all the workers are active, the action will be
  10540. * pended until a worker has completed its action.
  10541. * @param action The action to perform. Call onComplete when the action is complete.
  10542. */
  10543. WorkerPool.prototype.push = function (action) {
  10544. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10545. var workerInfo = _a[_i];
  10546. if (!workerInfo.active) {
  10547. this._execute(workerInfo, action);
  10548. return;
  10549. }
  10550. }
  10551. this._pendingActions.push(action);
  10552. };
  10553. WorkerPool.prototype._execute = function (workerInfo, action) {
  10554. var _this = this;
  10555. workerInfo.active = true;
  10556. action(workerInfo.worker, function () {
  10557. workerInfo.active = false;
  10558. var nextAction = _this._pendingActions.shift();
  10559. if (nextAction) {
  10560. _this._execute(workerInfo, nextAction);
  10561. }
  10562. });
  10563. };
  10564. return WorkerPool;
  10565. }());
  10566. BABYLON.WorkerPool = WorkerPool;
  10567. })(BABYLON || (BABYLON = {}));
  10568. //# sourceMappingURL=babylon.workerPool.js.map
  10569. var BABYLON;
  10570. (function (BABYLON) {
  10571. /**
  10572. * @hidden
  10573. **/
  10574. var _AlphaState = /** @class */ (function () {
  10575. /**
  10576. * Initializes the state.
  10577. */
  10578. function _AlphaState() {
  10579. this._isAlphaBlendDirty = false;
  10580. this._isBlendFunctionParametersDirty = false;
  10581. this._isBlendEquationParametersDirty = false;
  10582. this._isBlendConstantsDirty = false;
  10583. this._alphaBlend = false;
  10584. this._blendFunctionParameters = new Array(4);
  10585. this._blendEquationParameters = new Array(2);
  10586. this._blendConstants = new Array(4);
  10587. this.reset();
  10588. }
  10589. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  10590. get: function () {
  10591. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  10592. },
  10593. enumerable: true,
  10594. configurable: true
  10595. });
  10596. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  10597. get: function () {
  10598. return this._alphaBlend;
  10599. },
  10600. set: function (value) {
  10601. if (this._alphaBlend === value) {
  10602. return;
  10603. }
  10604. this._alphaBlend = value;
  10605. this._isAlphaBlendDirty = true;
  10606. },
  10607. enumerable: true,
  10608. configurable: true
  10609. });
  10610. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  10611. if (this._blendConstants[0] === r &&
  10612. this._blendConstants[1] === g &&
  10613. this._blendConstants[2] === b &&
  10614. this._blendConstants[3] === a) {
  10615. return;
  10616. }
  10617. this._blendConstants[0] = r;
  10618. this._blendConstants[1] = g;
  10619. this._blendConstants[2] = b;
  10620. this._blendConstants[3] = a;
  10621. this._isBlendConstantsDirty = true;
  10622. };
  10623. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  10624. if (this._blendFunctionParameters[0] === value0 &&
  10625. this._blendFunctionParameters[1] === value1 &&
  10626. this._blendFunctionParameters[2] === value2 &&
  10627. this._blendFunctionParameters[3] === value3) {
  10628. return;
  10629. }
  10630. this._blendFunctionParameters[0] = value0;
  10631. this._blendFunctionParameters[1] = value1;
  10632. this._blendFunctionParameters[2] = value2;
  10633. this._blendFunctionParameters[3] = value3;
  10634. this._isBlendFunctionParametersDirty = true;
  10635. };
  10636. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  10637. if (this._blendEquationParameters[0] === rgb &&
  10638. this._blendEquationParameters[1] === alpha) {
  10639. return;
  10640. }
  10641. this._blendEquationParameters[0] = rgb;
  10642. this._blendEquationParameters[1] = alpha;
  10643. this._isBlendEquationParametersDirty = true;
  10644. };
  10645. _AlphaState.prototype.reset = function () {
  10646. this._alphaBlend = false;
  10647. this._blendFunctionParameters[0] = null;
  10648. this._blendFunctionParameters[1] = null;
  10649. this._blendFunctionParameters[2] = null;
  10650. this._blendFunctionParameters[3] = null;
  10651. this._blendEquationParameters[0] = null;
  10652. this._blendEquationParameters[1] = null;
  10653. this._blendConstants[0] = null;
  10654. this._blendConstants[1] = null;
  10655. this._blendConstants[2] = null;
  10656. this._blendConstants[3] = null;
  10657. this._isAlphaBlendDirty = true;
  10658. this._isBlendFunctionParametersDirty = false;
  10659. this._isBlendEquationParametersDirty = false;
  10660. this._isBlendConstantsDirty = false;
  10661. };
  10662. _AlphaState.prototype.apply = function (gl) {
  10663. if (!this.isDirty) {
  10664. return;
  10665. }
  10666. // Alpha blend
  10667. if (this._isAlphaBlendDirty) {
  10668. if (this._alphaBlend) {
  10669. gl.enable(gl.BLEND);
  10670. }
  10671. else {
  10672. gl.disable(gl.BLEND);
  10673. }
  10674. this._isAlphaBlendDirty = false;
  10675. }
  10676. // Alpha function
  10677. if (this._isBlendFunctionParametersDirty) {
  10678. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  10679. this._isBlendFunctionParametersDirty = false;
  10680. }
  10681. // Alpha equation
  10682. if (this._isBlendEquationParametersDirty) {
  10683. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  10684. this._isBlendEquationParametersDirty = false;
  10685. }
  10686. // Constants
  10687. if (this._isBlendConstantsDirty) {
  10688. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  10689. this._isBlendConstantsDirty = false;
  10690. }
  10691. };
  10692. return _AlphaState;
  10693. }());
  10694. BABYLON._AlphaState = _AlphaState;
  10695. })(BABYLON || (BABYLON = {}));
  10696. //# sourceMappingURL=babylon.alphaCullingState.js.map
  10697. var BABYLON;
  10698. (function (BABYLON) {
  10699. /**
  10700. * @hidden
  10701. **/
  10702. var _DepthCullingState = /** @class */ (function () {
  10703. /**
  10704. * Initializes the state.
  10705. */
  10706. function _DepthCullingState() {
  10707. this._isDepthTestDirty = false;
  10708. this._isDepthMaskDirty = false;
  10709. this._isDepthFuncDirty = false;
  10710. this._isCullFaceDirty = false;
  10711. this._isCullDirty = false;
  10712. this._isZOffsetDirty = false;
  10713. this._isFrontFaceDirty = false;
  10714. this.reset();
  10715. }
  10716. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  10717. get: function () {
  10718. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  10719. },
  10720. enumerable: true,
  10721. configurable: true
  10722. });
  10723. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  10724. get: function () {
  10725. return this._zOffset;
  10726. },
  10727. set: function (value) {
  10728. if (this._zOffset === value) {
  10729. return;
  10730. }
  10731. this._zOffset = value;
  10732. this._isZOffsetDirty = true;
  10733. },
  10734. enumerable: true,
  10735. configurable: true
  10736. });
  10737. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  10738. get: function () {
  10739. return this._cullFace;
  10740. },
  10741. set: function (value) {
  10742. if (this._cullFace === value) {
  10743. return;
  10744. }
  10745. this._cullFace = value;
  10746. this._isCullFaceDirty = true;
  10747. },
  10748. enumerable: true,
  10749. configurable: true
  10750. });
  10751. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  10752. get: function () {
  10753. return this._cull;
  10754. },
  10755. set: function (value) {
  10756. if (this._cull === value) {
  10757. return;
  10758. }
  10759. this._cull = value;
  10760. this._isCullDirty = true;
  10761. },
  10762. enumerable: true,
  10763. configurable: true
  10764. });
  10765. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  10766. get: function () {
  10767. return this._depthFunc;
  10768. },
  10769. set: function (value) {
  10770. if (this._depthFunc === value) {
  10771. return;
  10772. }
  10773. this._depthFunc = value;
  10774. this._isDepthFuncDirty = true;
  10775. },
  10776. enumerable: true,
  10777. configurable: true
  10778. });
  10779. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  10780. get: function () {
  10781. return this._depthMask;
  10782. },
  10783. set: function (value) {
  10784. if (this._depthMask === value) {
  10785. return;
  10786. }
  10787. this._depthMask = value;
  10788. this._isDepthMaskDirty = true;
  10789. },
  10790. enumerable: true,
  10791. configurable: true
  10792. });
  10793. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  10794. get: function () {
  10795. return this._depthTest;
  10796. },
  10797. set: function (value) {
  10798. if (this._depthTest === value) {
  10799. return;
  10800. }
  10801. this._depthTest = value;
  10802. this._isDepthTestDirty = true;
  10803. },
  10804. enumerable: true,
  10805. configurable: true
  10806. });
  10807. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  10808. get: function () {
  10809. return this._frontFace;
  10810. },
  10811. set: function (value) {
  10812. if (this._frontFace === value) {
  10813. return;
  10814. }
  10815. this._frontFace = value;
  10816. this._isFrontFaceDirty = true;
  10817. },
  10818. enumerable: true,
  10819. configurable: true
  10820. });
  10821. _DepthCullingState.prototype.reset = function () {
  10822. this._depthMask = true;
  10823. this._depthTest = true;
  10824. this._depthFunc = null;
  10825. this._cullFace = null;
  10826. this._cull = null;
  10827. this._zOffset = 0;
  10828. this._frontFace = null;
  10829. this._isDepthTestDirty = true;
  10830. this._isDepthMaskDirty = true;
  10831. this._isDepthFuncDirty = false;
  10832. this._isCullFaceDirty = false;
  10833. this._isCullDirty = false;
  10834. this._isZOffsetDirty = false;
  10835. this._isFrontFaceDirty = false;
  10836. };
  10837. _DepthCullingState.prototype.apply = function (gl) {
  10838. if (!this.isDirty) {
  10839. return;
  10840. }
  10841. // Cull
  10842. if (this._isCullDirty) {
  10843. if (this.cull) {
  10844. gl.enable(gl.CULL_FACE);
  10845. }
  10846. else {
  10847. gl.disable(gl.CULL_FACE);
  10848. }
  10849. this._isCullDirty = false;
  10850. }
  10851. // Cull face
  10852. if (this._isCullFaceDirty) {
  10853. gl.cullFace(this.cullFace);
  10854. this._isCullFaceDirty = false;
  10855. }
  10856. // Depth mask
  10857. if (this._isDepthMaskDirty) {
  10858. gl.depthMask(this.depthMask);
  10859. this._isDepthMaskDirty = false;
  10860. }
  10861. // Depth test
  10862. if (this._isDepthTestDirty) {
  10863. if (this.depthTest) {
  10864. gl.enable(gl.DEPTH_TEST);
  10865. }
  10866. else {
  10867. gl.disable(gl.DEPTH_TEST);
  10868. }
  10869. this._isDepthTestDirty = false;
  10870. }
  10871. // Depth func
  10872. if (this._isDepthFuncDirty) {
  10873. gl.depthFunc(this.depthFunc);
  10874. this._isDepthFuncDirty = false;
  10875. }
  10876. // zOffset
  10877. if (this._isZOffsetDirty) {
  10878. if (this.zOffset) {
  10879. gl.enable(gl.POLYGON_OFFSET_FILL);
  10880. gl.polygonOffset(this.zOffset, 0);
  10881. }
  10882. else {
  10883. gl.disable(gl.POLYGON_OFFSET_FILL);
  10884. }
  10885. this._isZOffsetDirty = false;
  10886. }
  10887. // Front face
  10888. if (this._isFrontFaceDirty) {
  10889. gl.frontFace(this.frontFace);
  10890. this._isFrontFaceDirty = false;
  10891. }
  10892. };
  10893. return _DepthCullingState;
  10894. }());
  10895. BABYLON._DepthCullingState = _DepthCullingState;
  10896. })(BABYLON || (BABYLON = {}));
  10897. //# sourceMappingURL=babylon.depthCullingState.js.map
  10898. var BABYLON;
  10899. (function (BABYLON) {
  10900. /**
  10901. * @hidden
  10902. **/
  10903. var _StencilState = /** @class */ (function () {
  10904. function _StencilState() {
  10905. this._isStencilTestDirty = false;
  10906. this._isStencilMaskDirty = false;
  10907. this._isStencilFuncDirty = false;
  10908. this._isStencilOpDirty = false;
  10909. this.reset();
  10910. }
  10911. Object.defineProperty(_StencilState.prototype, "isDirty", {
  10912. get: function () {
  10913. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  10914. },
  10915. enumerable: true,
  10916. configurable: true
  10917. });
  10918. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  10919. get: function () {
  10920. return this._stencilFunc;
  10921. },
  10922. set: function (value) {
  10923. if (this._stencilFunc === value) {
  10924. return;
  10925. }
  10926. this._stencilFunc = value;
  10927. this._isStencilFuncDirty = true;
  10928. },
  10929. enumerable: true,
  10930. configurable: true
  10931. });
  10932. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  10933. get: function () {
  10934. return this._stencilFuncRef;
  10935. },
  10936. set: function (value) {
  10937. if (this._stencilFuncRef === value) {
  10938. return;
  10939. }
  10940. this._stencilFuncRef = value;
  10941. this._isStencilFuncDirty = true;
  10942. },
  10943. enumerable: true,
  10944. configurable: true
  10945. });
  10946. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  10947. get: function () {
  10948. return this._stencilFuncMask;
  10949. },
  10950. set: function (value) {
  10951. if (this._stencilFuncMask === value) {
  10952. return;
  10953. }
  10954. this._stencilFuncMask = value;
  10955. this._isStencilFuncDirty = true;
  10956. },
  10957. enumerable: true,
  10958. configurable: true
  10959. });
  10960. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  10961. get: function () {
  10962. return this._stencilOpStencilFail;
  10963. },
  10964. set: function (value) {
  10965. if (this._stencilOpStencilFail === value) {
  10966. return;
  10967. }
  10968. this._stencilOpStencilFail = value;
  10969. this._isStencilOpDirty = true;
  10970. },
  10971. enumerable: true,
  10972. configurable: true
  10973. });
  10974. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  10975. get: function () {
  10976. return this._stencilOpDepthFail;
  10977. },
  10978. set: function (value) {
  10979. if (this._stencilOpDepthFail === value) {
  10980. return;
  10981. }
  10982. this._stencilOpDepthFail = value;
  10983. this._isStencilOpDirty = true;
  10984. },
  10985. enumerable: true,
  10986. configurable: true
  10987. });
  10988. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  10989. get: function () {
  10990. return this._stencilOpStencilDepthPass;
  10991. },
  10992. set: function (value) {
  10993. if (this._stencilOpStencilDepthPass === value) {
  10994. return;
  10995. }
  10996. this._stencilOpStencilDepthPass = value;
  10997. this._isStencilOpDirty = true;
  10998. },
  10999. enumerable: true,
  11000. configurable: true
  11001. });
  11002. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  11003. get: function () {
  11004. return this._stencilMask;
  11005. },
  11006. set: function (value) {
  11007. if (this._stencilMask === value) {
  11008. return;
  11009. }
  11010. this._stencilMask = value;
  11011. this._isStencilMaskDirty = true;
  11012. },
  11013. enumerable: true,
  11014. configurable: true
  11015. });
  11016. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  11017. get: function () {
  11018. return this._stencilTest;
  11019. },
  11020. set: function (value) {
  11021. if (this._stencilTest === value) {
  11022. return;
  11023. }
  11024. this._stencilTest = value;
  11025. this._isStencilTestDirty = true;
  11026. },
  11027. enumerable: true,
  11028. configurable: true
  11029. });
  11030. _StencilState.prototype.reset = function () {
  11031. this._stencilTest = false;
  11032. this._stencilMask = 0xFF;
  11033. this._stencilFunc = BABYLON.Engine.ALWAYS;
  11034. this._stencilFuncRef = 1;
  11035. this._stencilFuncMask = 0xFF;
  11036. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  11037. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  11038. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  11039. this._isStencilTestDirty = true;
  11040. this._isStencilMaskDirty = true;
  11041. this._isStencilFuncDirty = true;
  11042. this._isStencilOpDirty = true;
  11043. };
  11044. _StencilState.prototype.apply = function (gl) {
  11045. if (!this.isDirty) {
  11046. return;
  11047. }
  11048. // Stencil test
  11049. if (this._isStencilTestDirty) {
  11050. if (this.stencilTest) {
  11051. gl.enable(gl.STENCIL_TEST);
  11052. }
  11053. else {
  11054. gl.disable(gl.STENCIL_TEST);
  11055. }
  11056. this._isStencilTestDirty = false;
  11057. }
  11058. // Stencil mask
  11059. if (this._isStencilMaskDirty) {
  11060. gl.stencilMask(this.stencilMask);
  11061. this._isStencilMaskDirty = false;
  11062. }
  11063. // Stencil func
  11064. if (this._isStencilFuncDirty) {
  11065. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  11066. this._isStencilFuncDirty = false;
  11067. }
  11068. // Stencil op
  11069. if (this._isStencilOpDirty) {
  11070. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  11071. this._isStencilOpDirty = false;
  11072. }
  11073. };
  11074. return _StencilState;
  11075. }());
  11076. BABYLON._StencilState = _StencilState;
  11077. })(BABYLON || (BABYLON = {}));
  11078. //# sourceMappingURL=babylon.stencilState.js.map
  11079. var __assign = (this && this.__assign) || Object.assign || function(t) {
  11080. for (var s, i = 1, n = arguments.length; i < n; i++) {
  11081. s = arguments[i];
  11082. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  11083. t[p] = s[p];
  11084. }
  11085. return t;
  11086. };
  11087. var BABYLON;
  11088. (function (BABYLON) {
  11089. var compileShader = function (gl, source, type, defines, shaderVersion) {
  11090. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  11091. };
  11092. var compileRawShader = function (gl, source, type) {
  11093. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  11094. gl.shaderSource(shader, source);
  11095. gl.compileShader(shader);
  11096. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  11097. var log = gl.getShaderInfoLog(shader);
  11098. if (log) {
  11099. throw new Error(log);
  11100. }
  11101. }
  11102. if (!shader) {
  11103. throw new Error("Something went wrong while compile the shader.");
  11104. }
  11105. return shader;
  11106. };
  11107. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  11108. var magFilter = gl.NEAREST;
  11109. var minFilter = gl.NEAREST;
  11110. switch (samplingMode) {
  11111. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  11112. magFilter = gl.LINEAR;
  11113. if (generateMipMaps) {
  11114. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  11115. }
  11116. else {
  11117. minFilter = gl.LINEAR;
  11118. }
  11119. break;
  11120. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  11121. magFilter = gl.LINEAR;
  11122. if (generateMipMaps) {
  11123. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  11124. }
  11125. else {
  11126. minFilter = gl.LINEAR;
  11127. }
  11128. break;
  11129. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  11130. magFilter = gl.NEAREST;
  11131. if (generateMipMaps) {
  11132. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  11133. }
  11134. else {
  11135. minFilter = gl.NEAREST;
  11136. }
  11137. break;
  11138. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  11139. magFilter = gl.NEAREST;
  11140. if (generateMipMaps) {
  11141. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  11142. }
  11143. else {
  11144. minFilter = gl.NEAREST;
  11145. }
  11146. break;
  11147. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  11148. magFilter = gl.NEAREST;
  11149. if (generateMipMaps) {
  11150. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  11151. }
  11152. else {
  11153. minFilter = gl.LINEAR;
  11154. }
  11155. break;
  11156. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  11157. magFilter = gl.NEAREST;
  11158. if (generateMipMaps) {
  11159. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  11160. }
  11161. else {
  11162. minFilter = gl.LINEAR;
  11163. }
  11164. break;
  11165. case BABYLON.Texture.NEAREST_LINEAR:
  11166. magFilter = gl.NEAREST;
  11167. minFilter = gl.LINEAR;
  11168. break;
  11169. case BABYLON.Texture.NEAREST_NEAREST:
  11170. magFilter = gl.NEAREST;
  11171. minFilter = gl.NEAREST;
  11172. break;
  11173. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  11174. magFilter = gl.LINEAR;
  11175. if (generateMipMaps) {
  11176. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  11177. }
  11178. else {
  11179. minFilter = gl.NEAREST;
  11180. }
  11181. break;
  11182. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  11183. magFilter = gl.LINEAR;
  11184. if (generateMipMaps) {
  11185. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  11186. }
  11187. else {
  11188. minFilter = gl.NEAREST;
  11189. }
  11190. break;
  11191. case BABYLON.Texture.LINEAR_LINEAR:
  11192. magFilter = gl.LINEAR;
  11193. minFilter = gl.LINEAR;
  11194. break;
  11195. case BABYLON.Texture.LINEAR_NEAREST:
  11196. magFilter = gl.LINEAR;
  11197. minFilter = gl.NEAREST;
  11198. break;
  11199. }
  11200. return {
  11201. min: minFilter,
  11202. mag: magFilter
  11203. };
  11204. };
  11205. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  11206. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  11207. var img;
  11208. var onload = function () {
  11209. loadedImages[index] = img;
  11210. loadedImages._internalCount++;
  11211. if (scene) {
  11212. scene._removePendingData(img);
  11213. }
  11214. if (loadedImages._internalCount === 6) {
  11215. onfinish(loadedImages);
  11216. }
  11217. };
  11218. var onerror = function (message, exception) {
  11219. if (scene) {
  11220. scene._removePendingData(img);
  11221. }
  11222. if (onErrorCallBack) {
  11223. onErrorCallBack(message, exception);
  11224. }
  11225. };
  11226. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  11227. if (scene) {
  11228. scene._addPendingData(img);
  11229. }
  11230. };
  11231. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  11232. if (onError === void 0) { onError = null; }
  11233. var loadedImages = [];
  11234. loadedImages._internalCount = 0;
  11235. for (var index = 0; index < 6; index++) {
  11236. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  11237. }
  11238. };
  11239. var BufferPointer = /** @class */ (function () {
  11240. function BufferPointer() {
  11241. }
  11242. return BufferPointer;
  11243. }());
  11244. /**
  11245. * Interface for attribute information associated with buffer instanciation
  11246. */
  11247. var InstancingAttributeInfo = /** @class */ (function () {
  11248. function InstancingAttributeInfo() {
  11249. }
  11250. return InstancingAttributeInfo;
  11251. }());
  11252. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  11253. /**
  11254. * Define options used to create a render target texture
  11255. */
  11256. var RenderTargetCreationOptions = /** @class */ (function () {
  11257. function RenderTargetCreationOptions() {
  11258. }
  11259. return RenderTargetCreationOptions;
  11260. }());
  11261. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  11262. /**
  11263. * Define options used to create a depth texture
  11264. */
  11265. var DepthTextureCreationOptions = /** @class */ (function () {
  11266. function DepthTextureCreationOptions() {
  11267. }
  11268. return DepthTextureCreationOptions;
  11269. }());
  11270. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  11271. /**
  11272. * Class used to describe the capabilities of the engine relatively to the current browser
  11273. */
  11274. var EngineCapabilities = /** @class */ (function () {
  11275. function EngineCapabilities() {
  11276. }
  11277. return EngineCapabilities;
  11278. }());
  11279. BABYLON.EngineCapabilities = EngineCapabilities;
  11280. /**
  11281. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  11282. */
  11283. var Engine = /** @class */ (function () {
  11284. /**
  11285. * Creates a new engine
  11286. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  11287. * @param antialias defines enable antialiasing (default: false)
  11288. * @param options defines further options to be sent to the getContext() function
  11289. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  11290. */
  11291. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  11292. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  11293. var _this = this;
  11294. // Public members
  11295. /**
  11296. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  11297. */
  11298. this.forcePOTTextures = false;
  11299. /**
  11300. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  11301. */
  11302. this.isFullscreen = false;
  11303. /**
  11304. * Gets a boolean indicating if the pointer is currently locked
  11305. */
  11306. this.isPointerLock = false;
  11307. /**
  11308. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  11309. */
  11310. this.cullBackFaces = true;
  11311. /**
  11312. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  11313. */
  11314. this.renderEvenInBackground = true;
  11315. /**
  11316. * Gets or sets a boolean indicating that cache can be kept between frames
  11317. */
  11318. this.preventCacheWipeBetweenFrames = false;
  11319. /**
  11320. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  11321. **/
  11322. this.enableOfflineSupport = false;
  11323. /**
  11324. * 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)
  11325. **/
  11326. this.disableManifestCheck = false;
  11327. /**
  11328. * Gets the list of created scenes
  11329. */
  11330. this.scenes = new Array();
  11331. /**
  11332. * Gets the list of created postprocesses
  11333. */
  11334. this.postProcesses = new Array();
  11335. // Observables
  11336. /**
  11337. * Observable event triggered each time the rendering canvas is resized
  11338. */
  11339. this.onResizeObservable = new BABYLON.Observable();
  11340. /**
  11341. * Observable event triggered each time the canvas loses focus
  11342. */
  11343. this.onCanvasBlurObservable = new BABYLON.Observable();
  11344. /**
  11345. * Observable event triggered each time the canvas gains focus
  11346. */
  11347. this.onCanvasFocusObservable = new BABYLON.Observable();
  11348. /**
  11349. * Observable event triggered each time the canvas receives pointerout event
  11350. */
  11351. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  11352. /**
  11353. * Observable event triggered before each texture is initialized
  11354. */
  11355. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  11356. //WebVR
  11357. this._vrDisplay = undefined;
  11358. this._vrSupported = false;
  11359. this._vrExclusivePointerMode = false;
  11360. // Uniform buffers list
  11361. /**
  11362. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  11363. */
  11364. this.disableUniformBuffers = false;
  11365. /** @hidden */
  11366. this._uniformBuffers = new Array();
  11367. // Observables
  11368. /**
  11369. * Observable raised when the engine begins a new frame
  11370. */
  11371. this.onBeginFrameObservable = new BABYLON.Observable();
  11372. /**
  11373. * Observable raised when the engine ends the current frame
  11374. */
  11375. this.onEndFrameObservable = new BABYLON.Observable();
  11376. /**
  11377. * Observable raised when the engine is about to compile a shader
  11378. */
  11379. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  11380. /**
  11381. * Observable raised when the engine has jsut compiled a shader
  11382. */
  11383. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  11384. this._windowIsBackground = false;
  11385. this._webGLVersion = 1.0;
  11386. /** @hidden */
  11387. this._badOS = false;
  11388. /** @hidden */
  11389. this._badDesktopOS = false;
  11390. /**
  11391. * Gets or sets a value indicating if we want to disable texture binding optmization.
  11392. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  11393. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  11394. */
  11395. this.disableTextureBindingOptimization = false;
  11396. /**
  11397. * Observable signaled when VR display mode changes
  11398. */
  11399. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  11400. /**
  11401. * Observable signaled when VR request present is complete
  11402. */
  11403. this.onVRRequestPresentComplete = new BABYLON.Observable();
  11404. /**
  11405. * Observable signaled when VR request present starts
  11406. */
  11407. this.onVRRequestPresentStart = new BABYLON.Observable();
  11408. this._colorWrite = true;
  11409. /** @hidden */
  11410. this._drawCalls = new BABYLON.PerfCounter();
  11411. /** @hidden */
  11412. this._textureCollisions = new BABYLON.PerfCounter();
  11413. this._renderingQueueLaunched = false;
  11414. this._activeRenderLoops = new Array();
  11415. // Deterministic lockstepMaxSteps
  11416. this._deterministicLockstep = false;
  11417. this._lockstepMaxSteps = 4;
  11418. // Lost context
  11419. /**
  11420. * Observable signaled when a context lost event is raised
  11421. */
  11422. this.onContextLostObservable = new BABYLON.Observable();
  11423. /**
  11424. * Observable signaled when a context restored event is raised
  11425. */
  11426. this.onContextRestoredObservable = new BABYLON.Observable();
  11427. this._contextWasLost = false;
  11428. this._doNotHandleContextLost = false;
  11429. // FPS
  11430. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  11431. this._fps = 60;
  11432. this._deltaTime = 0;
  11433. /**
  11434. * Turn this value on if you want to pause FPS computation when in background
  11435. */
  11436. this.disablePerformanceMonitorInBackground = false;
  11437. // States
  11438. /** @hidden */
  11439. this._depthCullingState = new BABYLON._DepthCullingState();
  11440. /** @hidden */
  11441. this._stencilState = new BABYLON._StencilState();
  11442. /** @hidden */
  11443. this._alphaState = new BABYLON._AlphaState();
  11444. /** @hidden */
  11445. this._alphaMode = Engine.ALPHA_DISABLE;
  11446. // Cache
  11447. this._internalTexturesCache = new Array();
  11448. /** @hidden */
  11449. this._activeChannel = 0;
  11450. this._currentTextureChannel = -1;
  11451. /** @hidden */
  11452. this._boundTexturesCache = {};
  11453. this._compiledEffects = {};
  11454. this._vertexAttribArraysEnabled = [];
  11455. this._uintIndicesCurrentlySet = false;
  11456. this._currentBoundBuffer = new Array();
  11457. this._currentBufferPointers = new Array();
  11458. this._currentInstanceLocations = new Array();
  11459. this._currentInstanceBuffers = new Array();
  11460. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11461. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11462. this._vaoRecordInProgress = false;
  11463. this._mustWipeVertexAttributes = false;
  11464. this._nextFreeTextureSlots = new Array();
  11465. this._maxSimultaneousTextures = 0;
  11466. this._activeRequests = new Array();
  11467. // Hardware supported Compressed Textures
  11468. this._texturesSupported = new Array();
  11469. /**
  11470. * Defines whether the engine has been created with the premultipliedAlpha option on or not.
  11471. */
  11472. this.premultipliedAlpha = true;
  11473. this._onVRFullScreenTriggered = function () {
  11474. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  11475. //get the old size before we change
  11476. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  11477. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  11478. //get the width and height, change the render size
  11479. var leftEye = _this._vrDisplay.getEyeParameters('left');
  11480. _this.setHardwareScalingLevel(1);
  11481. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  11482. }
  11483. else {
  11484. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  11485. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  11486. }
  11487. };
  11488. this._boundUniforms = {};
  11489. // Register promises
  11490. BABYLON.PromisePolyfill.Apply();
  11491. var canvas = null;
  11492. Engine.Instances.push(this);
  11493. if (!canvasOrContext) {
  11494. return;
  11495. }
  11496. options = options || {};
  11497. if (canvasOrContext.getContext) {
  11498. canvas = canvasOrContext;
  11499. this._renderingCanvas = canvas;
  11500. if (antialias != null) {
  11501. options.antialias = antialias;
  11502. }
  11503. if (options.deterministicLockstep === undefined) {
  11504. options.deterministicLockstep = false;
  11505. }
  11506. if (options.lockstepMaxSteps === undefined) {
  11507. options.lockstepMaxSteps = 4;
  11508. }
  11509. if (options.preserveDrawingBuffer === undefined) {
  11510. options.preserveDrawingBuffer = false;
  11511. }
  11512. if (options.audioEngine === undefined) {
  11513. options.audioEngine = true;
  11514. }
  11515. if (options.stencil === undefined) {
  11516. options.stencil = true;
  11517. }
  11518. if (options.premultipliedAlpha === false) {
  11519. this.premultipliedAlpha = false;
  11520. }
  11521. this._deterministicLockstep = options.deterministicLockstep;
  11522. this._lockstepMaxSteps = options.lockstepMaxSteps;
  11523. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  11524. // Exceptions
  11525. if (navigator && navigator.userAgent) {
  11526. var ua = navigator.userAgent;
  11527. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  11528. var exception = _a[_i];
  11529. var key = exception.key;
  11530. var targets = exception.targets;
  11531. if (ua.indexOf(key) > -1) {
  11532. if (exception.capture && exception.captureConstraint) {
  11533. var capture = exception.capture;
  11534. var constraint = exception.captureConstraint;
  11535. var regex = new RegExp(capture);
  11536. var matches = regex.exec(ua);
  11537. if (matches && matches.length > 0) {
  11538. var capturedValue = parseInt(matches[matches.length - 1]);
  11539. if (capturedValue >= constraint) {
  11540. continue;
  11541. }
  11542. }
  11543. }
  11544. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  11545. var target = targets_1[_b];
  11546. switch (target) {
  11547. case "uniformBuffer":
  11548. this.disableUniformBuffers = true;
  11549. break;
  11550. case "textureBindingOptimization":
  11551. this.disableTextureBindingOptimization = true;
  11552. break;
  11553. }
  11554. }
  11555. }
  11556. }
  11557. }
  11558. // GL
  11559. if (!options.disableWebGL2Support) {
  11560. try {
  11561. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  11562. if (this._gl) {
  11563. this._webGLVersion = 2.0;
  11564. }
  11565. }
  11566. catch (e) {
  11567. // Do nothing
  11568. }
  11569. }
  11570. if (!this._gl) {
  11571. if (!canvas) {
  11572. throw new Error("The provided canvas is null or undefined.");
  11573. }
  11574. try {
  11575. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  11576. }
  11577. catch (e) {
  11578. throw new Error("WebGL not supported");
  11579. }
  11580. }
  11581. if (!this._gl) {
  11582. throw new Error("WebGL not supported");
  11583. }
  11584. this._onCanvasFocus = function () {
  11585. _this.onCanvasFocusObservable.notifyObservers(_this);
  11586. };
  11587. this._onCanvasBlur = function () {
  11588. _this.onCanvasBlurObservable.notifyObservers(_this);
  11589. };
  11590. canvas.addEventListener("focus", this._onCanvasFocus);
  11591. canvas.addEventListener("blur", this._onCanvasBlur);
  11592. this._onBlur = function () {
  11593. if (_this.disablePerformanceMonitorInBackground) {
  11594. _this._performanceMonitor.disable();
  11595. }
  11596. _this._windowIsBackground = true;
  11597. };
  11598. this._onFocus = function () {
  11599. if (_this.disablePerformanceMonitorInBackground) {
  11600. _this._performanceMonitor.enable();
  11601. }
  11602. _this._windowIsBackground = false;
  11603. };
  11604. this._onCanvasPointerOut = function (ev) {
  11605. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  11606. };
  11607. window.addEventListener("blur", this._onBlur);
  11608. window.addEventListener("focus", this._onFocus);
  11609. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  11610. // Context lost
  11611. if (!this._doNotHandleContextLost) {
  11612. this._onContextLost = function (evt) {
  11613. evt.preventDefault();
  11614. _this._contextWasLost = true;
  11615. BABYLON.Tools.Warn("WebGL context lost.");
  11616. _this.onContextLostObservable.notifyObservers(_this);
  11617. };
  11618. this._onContextRestored = function (evt) {
  11619. // Adding a timeout to avoid race condition at browser level
  11620. setTimeout(function () {
  11621. // Rebuild gl context
  11622. _this._initGLContext();
  11623. // Rebuild effects
  11624. _this._rebuildEffects();
  11625. // Rebuild textures
  11626. _this._rebuildInternalTextures();
  11627. // Rebuild buffers
  11628. _this._rebuildBuffers();
  11629. // Cache
  11630. _this.wipeCaches(true);
  11631. BABYLON.Tools.Warn("WebGL context successfully restored.");
  11632. _this.onContextRestoredObservable.notifyObservers(_this);
  11633. _this._contextWasLost = false;
  11634. }, 0);
  11635. };
  11636. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  11637. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  11638. }
  11639. }
  11640. else {
  11641. this._gl = canvasOrContext;
  11642. this._renderingCanvas = this._gl.canvas;
  11643. if (this._gl.renderbufferStorageMultisample) {
  11644. this._webGLVersion = 2.0;
  11645. }
  11646. options.stencil = this._gl.getContextAttributes().stencil;
  11647. }
  11648. // Viewport
  11649. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  11650. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  11651. this.resize();
  11652. this._isStencilEnable = options.stencil ? true : false;
  11653. this._initGLContext();
  11654. if (canvas) {
  11655. // Fullscreen
  11656. this._onFullscreenChange = function () {
  11657. if (document.fullscreen !== undefined) {
  11658. _this.isFullscreen = document.fullscreen;
  11659. }
  11660. else if (document.mozFullScreen !== undefined) {
  11661. _this.isFullscreen = document.mozFullScreen;
  11662. }
  11663. else if (document.webkitIsFullScreen !== undefined) {
  11664. _this.isFullscreen = document.webkitIsFullScreen;
  11665. }
  11666. else if (document.msIsFullScreen !== undefined) {
  11667. _this.isFullscreen = document.msIsFullScreen;
  11668. }
  11669. // Pointer lock
  11670. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  11671. canvas.requestPointerLock = canvas.requestPointerLock ||
  11672. canvas.msRequestPointerLock ||
  11673. canvas.mozRequestPointerLock ||
  11674. canvas.webkitRequestPointerLock;
  11675. if (canvas.requestPointerLock) {
  11676. canvas.requestPointerLock();
  11677. }
  11678. }
  11679. };
  11680. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  11681. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  11682. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  11683. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  11684. // Pointer lock
  11685. this._onPointerLockChange = function () {
  11686. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  11687. document.webkitPointerLockElement === canvas ||
  11688. document.msPointerLockElement === canvas ||
  11689. document.pointerLockElement === canvas);
  11690. };
  11691. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  11692. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  11693. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  11694. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  11695. this._onVRDisplayPointerRestricted = function () {
  11696. if (canvas) {
  11697. canvas.requestPointerLock();
  11698. }
  11699. };
  11700. this._onVRDisplayPointerUnrestricted = function () {
  11701. document.exitPointerLock();
  11702. };
  11703. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  11704. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  11705. }
  11706. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  11707. Engine.audioEngine = new BABYLON.AudioEngine();
  11708. }
  11709. // Prepare buffer pointers
  11710. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11711. this._currentBufferPointers[i] = new BufferPointer();
  11712. }
  11713. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  11714. // Load WebVR Devices
  11715. if (options.autoEnableWebVR) {
  11716. this.initWebVR();
  11717. }
  11718. // Detect if we are running on a faulty buggy OS.
  11719. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  11720. // Detect if we are running on a faulty buggy desktop OS.
  11721. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  11722. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  11723. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  11724. }
  11725. Object.defineProperty(Engine, "LastCreatedEngine", {
  11726. /**
  11727. * Gets the latest created engine
  11728. */
  11729. get: function () {
  11730. if (Engine.Instances.length === 0) {
  11731. return null;
  11732. }
  11733. return Engine.Instances[Engine.Instances.length - 1];
  11734. },
  11735. enumerable: true,
  11736. configurable: true
  11737. });
  11738. Object.defineProperty(Engine, "LastCreatedScene", {
  11739. /**
  11740. * Gets the latest created scene
  11741. */
  11742. get: function () {
  11743. var lastCreatedEngine = Engine.LastCreatedEngine;
  11744. if (!lastCreatedEngine) {
  11745. return null;
  11746. }
  11747. if (lastCreatedEngine.scenes.length === 0) {
  11748. return null;
  11749. }
  11750. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  11751. },
  11752. enumerable: true,
  11753. configurable: true
  11754. });
  11755. /**
  11756. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  11757. * @param flag defines which part of the materials must be marked as dirty
  11758. * @param predicate defines a predicate used to filter which materials should be affected
  11759. */
  11760. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  11761. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  11762. var engine = Engine.Instances[engineIndex];
  11763. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  11764. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  11765. }
  11766. }
  11767. };
  11768. Object.defineProperty(Engine, "NEVER", {
  11769. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  11770. get: function () {
  11771. return Engine._NEVER;
  11772. },
  11773. enumerable: true,
  11774. configurable: true
  11775. });
  11776. Object.defineProperty(Engine, "ALWAYS", {
  11777. /** 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 */
  11778. get: function () {
  11779. return Engine._ALWAYS;
  11780. },
  11781. enumerable: true,
  11782. configurable: true
  11783. });
  11784. Object.defineProperty(Engine, "LESS", {
  11785. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  11786. get: function () {
  11787. return Engine._LESS;
  11788. },
  11789. enumerable: true,
  11790. configurable: true
  11791. });
  11792. Object.defineProperty(Engine, "EQUAL", {
  11793. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  11794. get: function () {
  11795. return Engine._EQUAL;
  11796. },
  11797. enumerable: true,
  11798. configurable: true
  11799. });
  11800. Object.defineProperty(Engine, "LEQUAL", {
  11801. /** 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 */
  11802. get: function () {
  11803. return Engine._LEQUAL;
  11804. },
  11805. enumerable: true,
  11806. configurable: true
  11807. });
  11808. Object.defineProperty(Engine, "GREATER", {
  11809. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  11810. get: function () {
  11811. return Engine._GREATER;
  11812. },
  11813. enumerable: true,
  11814. configurable: true
  11815. });
  11816. Object.defineProperty(Engine, "GEQUAL", {
  11817. /** 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 */
  11818. get: function () {
  11819. return Engine._GEQUAL;
  11820. },
  11821. enumerable: true,
  11822. configurable: true
  11823. });
  11824. Object.defineProperty(Engine, "NOTEQUAL", {
  11825. /** 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 */
  11826. get: function () {
  11827. return Engine._NOTEQUAL;
  11828. },
  11829. enumerable: true,
  11830. configurable: true
  11831. });
  11832. Object.defineProperty(Engine, "KEEP", {
  11833. /** Passed to stencilOperation to specify that stencil value must be kept */
  11834. get: function () {
  11835. return Engine._KEEP;
  11836. },
  11837. enumerable: true,
  11838. configurable: true
  11839. });
  11840. Object.defineProperty(Engine, "REPLACE", {
  11841. /** Passed to stencilOperation to specify that stencil value must be replaced */
  11842. get: function () {
  11843. return Engine._REPLACE;
  11844. },
  11845. enumerable: true,
  11846. configurable: true
  11847. });
  11848. Object.defineProperty(Engine, "INCR", {
  11849. /** Passed to stencilOperation to specify that stencil value must be incremented */
  11850. get: function () {
  11851. return Engine._INCR;
  11852. },
  11853. enumerable: true,
  11854. configurable: true
  11855. });
  11856. Object.defineProperty(Engine, "DECR", {
  11857. /** Passed to stencilOperation to specify that stencil value must be decremented */
  11858. get: function () {
  11859. return Engine._DECR;
  11860. },
  11861. enumerable: true,
  11862. configurable: true
  11863. });
  11864. Object.defineProperty(Engine, "INVERT", {
  11865. /** Passed to stencilOperation to specify that stencil value must be inverted */
  11866. get: function () {
  11867. return Engine._INVERT;
  11868. },
  11869. enumerable: true,
  11870. configurable: true
  11871. });
  11872. Object.defineProperty(Engine, "INCR_WRAP", {
  11873. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  11874. get: function () {
  11875. return Engine._INCR_WRAP;
  11876. },
  11877. enumerable: true,
  11878. configurable: true
  11879. });
  11880. Object.defineProperty(Engine, "DECR_WRAP", {
  11881. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  11882. get: function () {
  11883. return Engine._DECR_WRAP;
  11884. },
  11885. enumerable: true,
  11886. configurable: true
  11887. });
  11888. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  11889. // Alpha
  11890. /** Defines that alpha blending is disabled */
  11891. get: function () {
  11892. return Engine._ALPHA_DISABLE;
  11893. },
  11894. enumerable: true,
  11895. configurable: true
  11896. });
  11897. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  11898. /** Defines that alpha blending to SRC + DEST */
  11899. get: function () {
  11900. return Engine._ALPHA_ONEONE;
  11901. },
  11902. enumerable: true,
  11903. configurable: true
  11904. });
  11905. Object.defineProperty(Engine, "ALPHA_ADD", {
  11906. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  11907. get: function () {
  11908. return Engine._ALPHA_ADD;
  11909. },
  11910. enumerable: true,
  11911. configurable: true
  11912. });
  11913. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  11914. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  11915. get: function () {
  11916. return Engine._ALPHA_COMBINE;
  11917. },
  11918. enumerable: true,
  11919. configurable: true
  11920. });
  11921. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  11922. /** Defines that alpha blending to DEST - SRC * DEST */
  11923. get: function () {
  11924. return Engine._ALPHA_SUBTRACT;
  11925. },
  11926. enumerable: true,
  11927. configurable: true
  11928. });
  11929. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  11930. /** Defines that alpha blending to SRC * DEST */
  11931. get: function () {
  11932. return Engine._ALPHA_MULTIPLY;
  11933. },
  11934. enumerable: true,
  11935. configurable: true
  11936. });
  11937. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  11938. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  11939. get: function () {
  11940. return Engine._ALPHA_MAXIMIZED;
  11941. },
  11942. enumerable: true,
  11943. configurable: true
  11944. });
  11945. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  11946. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  11947. get: function () {
  11948. return Engine._ALPHA_PREMULTIPLIED;
  11949. },
  11950. enumerable: true,
  11951. configurable: true
  11952. });
  11953. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  11954. /**
  11955. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  11956. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  11957. */
  11958. get: function () {
  11959. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  11960. },
  11961. enumerable: true,
  11962. configurable: true
  11963. });
  11964. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  11965. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  11966. get: function () {
  11967. return Engine._ALPHA_INTERPOLATE;
  11968. },
  11969. enumerable: true,
  11970. configurable: true
  11971. });
  11972. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  11973. /**
  11974. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  11975. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  11976. */
  11977. get: function () {
  11978. return Engine._ALPHA_SCREENMODE;
  11979. },
  11980. enumerable: true,
  11981. configurable: true
  11982. });
  11983. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  11984. // Delays
  11985. /** Defines that the ressource is not delayed*/
  11986. get: function () {
  11987. return Engine._DELAYLOADSTATE_NONE;
  11988. },
  11989. enumerable: true,
  11990. configurable: true
  11991. });
  11992. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  11993. /** Defines that the ressource was successfully delay loaded */
  11994. get: function () {
  11995. return Engine._DELAYLOADSTATE_LOADED;
  11996. },
  11997. enumerable: true,
  11998. configurable: true
  11999. });
  12000. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  12001. /** Defines that the ressource is currently delay loading */
  12002. get: function () {
  12003. return Engine._DELAYLOADSTATE_LOADING;
  12004. },
  12005. enumerable: true,
  12006. configurable: true
  12007. });
  12008. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  12009. /** Defines that the ressource is delayed and has not started loading */
  12010. get: function () {
  12011. return Engine._DELAYLOADSTATE_NOTLOADED;
  12012. },
  12013. enumerable: true,
  12014. configurable: true
  12015. });
  12016. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  12017. /** ALPHA */
  12018. get: function () {
  12019. return Engine._TEXTUREFORMAT_ALPHA;
  12020. },
  12021. enumerable: true,
  12022. configurable: true
  12023. });
  12024. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  12025. /** LUMINANCE */
  12026. get: function () {
  12027. return Engine._TEXTUREFORMAT_LUMINANCE;
  12028. },
  12029. enumerable: true,
  12030. configurable: true
  12031. });
  12032. Object.defineProperty(Engine, "TEXTUREFORMAT_R", {
  12033. /**
  12034. * R
  12035. */
  12036. get: function () {
  12037. return Engine._TEXTUREFORMAT_R;
  12038. },
  12039. enumerable: true,
  12040. configurable: true
  12041. });
  12042. Object.defineProperty(Engine, "TEXTUREFORMAT_RG", {
  12043. /**
  12044. * RG
  12045. */
  12046. get: function () {
  12047. return Engine._TEXTUREFORMAT_RG;
  12048. },
  12049. enumerable: true,
  12050. configurable: true
  12051. });
  12052. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  12053. /** LUMINANCE_ALPHA */
  12054. get: function () {
  12055. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  12056. },
  12057. enumerable: true,
  12058. configurable: true
  12059. });
  12060. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  12061. /** RGB */
  12062. get: function () {
  12063. return Engine._TEXTUREFORMAT_RGB;
  12064. },
  12065. enumerable: true,
  12066. configurable: true
  12067. });
  12068. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  12069. /** RGBA */
  12070. get: function () {
  12071. return Engine._TEXTUREFORMAT_RGBA;
  12072. },
  12073. enumerable: true,
  12074. configurable: true
  12075. });
  12076. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  12077. /** UNSIGNED_INT */
  12078. get: function () {
  12079. return Engine._TEXTURETYPE_UNSIGNED_INT;
  12080. },
  12081. enumerable: true,
  12082. configurable: true
  12083. });
  12084. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  12085. /** FLOAT */
  12086. get: function () {
  12087. return Engine._TEXTURETYPE_FLOAT;
  12088. },
  12089. enumerable: true,
  12090. configurable: true
  12091. });
  12092. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  12093. /** HALF_FLOAT */
  12094. get: function () {
  12095. return Engine._TEXTURETYPE_HALF_FLOAT;
  12096. },
  12097. enumerable: true,
  12098. configurable: true
  12099. });
  12100. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  12101. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  12102. get: function () {
  12103. return Engine._SCALEMODE_FLOOR;
  12104. },
  12105. enumerable: true,
  12106. configurable: true
  12107. });
  12108. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  12109. /** Defines that texture rescaling will look for the nearest power of 2 size */
  12110. get: function () {
  12111. return Engine._SCALEMODE_NEAREST;
  12112. },
  12113. enumerable: true,
  12114. configurable: true
  12115. });
  12116. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  12117. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  12118. get: function () {
  12119. return Engine._SCALEMODE_CEILING;
  12120. },
  12121. enumerable: true,
  12122. configurable: true
  12123. });
  12124. Object.defineProperty(Engine, "Version", {
  12125. /**
  12126. * Returns the current version of the framework
  12127. */
  12128. get: function () {
  12129. return "3.3.0-alpha.6";
  12130. },
  12131. enumerable: true,
  12132. configurable: true
  12133. });
  12134. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  12135. /**
  12136. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  12137. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  12138. */
  12139. get: function () {
  12140. return this._vrExclusivePointerMode;
  12141. },
  12142. enumerable: true,
  12143. configurable: true
  12144. });
  12145. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  12146. /**
  12147. * Gets a boolean indicating that the engine supports uniform buffers
  12148. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12149. */
  12150. get: function () {
  12151. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  12152. },
  12153. enumerable: true,
  12154. configurable: true
  12155. });
  12156. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  12157. /**
  12158. * Gets a boolean indicating that only power of 2 textures are supported
  12159. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  12160. */
  12161. get: function () {
  12162. return this._webGLVersion < 2 || this.forcePOTTextures;
  12163. },
  12164. enumerable: true,
  12165. configurable: true
  12166. });
  12167. Object.defineProperty(Engine.prototype, "doNotHandleContextLost", {
  12168. /**
  12169. * Gets or sets a boolean indicating if resources should be retained to be able to handle context lost events
  12170. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#handling-webgl-context-lost
  12171. */
  12172. get: function () {
  12173. return this._doNotHandleContextLost;
  12174. },
  12175. set: function (value) {
  12176. this._doNotHandleContextLost = value;
  12177. },
  12178. enumerable: true,
  12179. configurable: true
  12180. });
  12181. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  12182. /**
  12183. * Gets the performance monitor attached to this engine
  12184. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  12185. */
  12186. get: function () {
  12187. return this._performanceMonitor;
  12188. },
  12189. enumerable: true,
  12190. configurable: true
  12191. });
  12192. Object.defineProperty(Engine.prototype, "texturesSupported", {
  12193. /**
  12194. * Gets the list of texture formats supported
  12195. */
  12196. get: function () {
  12197. return this._texturesSupported;
  12198. },
  12199. enumerable: true,
  12200. configurable: true
  12201. });
  12202. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  12203. /**
  12204. * Gets the list of texture formats in use
  12205. */
  12206. get: function () {
  12207. return this._textureFormatInUse;
  12208. },
  12209. enumerable: true,
  12210. configurable: true
  12211. });
  12212. Object.defineProperty(Engine.prototype, "currentViewport", {
  12213. /**
  12214. * Gets the current viewport
  12215. */
  12216. get: function () {
  12217. return this._cachedViewport;
  12218. },
  12219. enumerable: true,
  12220. configurable: true
  12221. });
  12222. Object.defineProperty(Engine.prototype, "emptyTexture", {
  12223. /**
  12224. * Gets the default empty texture
  12225. */
  12226. get: function () {
  12227. if (!this._emptyTexture) {
  12228. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12229. }
  12230. return this._emptyTexture;
  12231. },
  12232. enumerable: true,
  12233. configurable: true
  12234. });
  12235. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  12236. /**
  12237. * Gets the default empty 3D texture
  12238. */
  12239. get: function () {
  12240. if (!this._emptyTexture3D) {
  12241. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12242. }
  12243. return this._emptyTexture3D;
  12244. },
  12245. enumerable: true,
  12246. configurable: true
  12247. });
  12248. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  12249. /**
  12250. * Gets the default empty cube texture
  12251. */
  12252. get: function () {
  12253. if (!this._emptyCubeTexture) {
  12254. var faceData = new Uint8Array(4);
  12255. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  12256. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12257. }
  12258. return this._emptyCubeTexture;
  12259. },
  12260. enumerable: true,
  12261. configurable: true
  12262. });
  12263. Engine.prototype._rebuildInternalTextures = function () {
  12264. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  12265. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  12266. var internalTexture = currentState_1[_i];
  12267. internalTexture._rebuild();
  12268. }
  12269. };
  12270. Engine.prototype._rebuildEffects = function () {
  12271. for (var key in this._compiledEffects) {
  12272. var effect = this._compiledEffects[key];
  12273. effect._prepareEffect();
  12274. }
  12275. BABYLON.Effect.ResetCache();
  12276. };
  12277. Engine.prototype._rebuildBuffers = function () {
  12278. // Index / Vertex
  12279. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  12280. var scene = _a[_i];
  12281. scene.resetCachedMaterial();
  12282. scene._rebuildGeometries();
  12283. scene._rebuildTextures();
  12284. }
  12285. // Uniforms
  12286. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  12287. var uniformBuffer = _c[_b];
  12288. uniformBuffer._rebuild();
  12289. }
  12290. };
  12291. Engine.prototype._initGLContext = function () {
  12292. // Caps
  12293. this._caps = new EngineCapabilities();
  12294. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  12295. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  12296. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  12297. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  12298. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  12299. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  12300. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  12301. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  12302. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  12303. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  12304. // Infos
  12305. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  12306. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  12307. if (rendererInfo != null) {
  12308. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  12309. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  12310. }
  12311. if (!this._glVendor) {
  12312. this._glVendor = "Unknown vendor";
  12313. }
  12314. if (!this._glRenderer) {
  12315. this._glRenderer = "Unknown renderer";
  12316. }
  12317. // Constants
  12318. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  12319. if (this._gl.RGBA16F !== 0x881A) {
  12320. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  12321. }
  12322. if (this._gl.RGBA32F !== 0x8814) {
  12323. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  12324. }
  12325. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  12326. this._gl.DEPTH24_STENCIL8 = 35056;
  12327. }
  12328. // Extensions
  12329. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  12330. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  12331. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  12332. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  12333. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  12334. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  12335. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  12336. 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');
  12337. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  12338. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  12339. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  12340. this._caps.highPrecisionShaderSupported = true;
  12341. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  12342. if (this._caps.timerQuery) {
  12343. if (this._webGLVersion === 1) {
  12344. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  12345. }
  12346. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  12347. }
  12348. // Checks if some of the format renders first to allow the use of webgl inspector.
  12349. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  12350. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  12351. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  12352. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  12353. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  12354. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  12355. if (this._webGLVersion > 1) {
  12356. this._gl.HALF_FLOAT_OES = 0x140B;
  12357. }
  12358. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  12359. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  12360. // Draw buffers
  12361. if (this._webGLVersion > 1) {
  12362. this._caps.drawBuffersExtension = true;
  12363. }
  12364. else {
  12365. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  12366. if (drawBuffersExtension !== null) {
  12367. this._caps.drawBuffersExtension = true;
  12368. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  12369. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  12370. for (var i = 0; i < 16; i++) {
  12371. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  12372. }
  12373. }
  12374. else {
  12375. this._caps.drawBuffersExtension = false;
  12376. }
  12377. }
  12378. // Depth Texture
  12379. if (this._webGLVersion > 1) {
  12380. this._caps.depthTextureExtension = true;
  12381. }
  12382. else {
  12383. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  12384. if (depthTextureExtension != null) {
  12385. this._caps.depthTextureExtension = true;
  12386. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  12387. }
  12388. }
  12389. // Vertex array object
  12390. if (this._webGLVersion > 1) {
  12391. this._caps.vertexArrayObject = true;
  12392. }
  12393. else {
  12394. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  12395. if (vertexArrayObjectExtension != null) {
  12396. this._caps.vertexArrayObject = true;
  12397. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  12398. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  12399. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  12400. }
  12401. else {
  12402. this._caps.vertexArrayObject = false;
  12403. }
  12404. }
  12405. // Instances count
  12406. if (this._webGLVersion > 1) {
  12407. this._caps.instancedArrays = true;
  12408. }
  12409. else {
  12410. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  12411. if (instanceExtension != null) {
  12412. this._caps.instancedArrays = true;
  12413. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  12414. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  12415. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  12416. }
  12417. else {
  12418. this._caps.instancedArrays = false;
  12419. }
  12420. }
  12421. // Intelligently add supported compressed formats in order to check for.
  12422. // Check for ASTC support first as it is most powerful and to be very cross platform.
  12423. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  12424. // Likely no hardware which supports both PVR & DXT, so order matters little.
  12425. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  12426. if (this._caps.astc)
  12427. this.texturesSupported.push('-astc.ktx');
  12428. if (this._caps.s3tc)
  12429. this.texturesSupported.push('-dxt.ktx');
  12430. if (this._caps.pvrtc)
  12431. this.texturesSupported.push('-pvrtc.ktx');
  12432. if (this._caps.etc2)
  12433. this.texturesSupported.push('-etc2.ktx');
  12434. if (this._caps.etc1)
  12435. this.texturesSupported.push('-etc1.ktx');
  12436. if (this._gl.getShaderPrecisionFormat) {
  12437. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  12438. if (highp) {
  12439. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  12440. }
  12441. }
  12442. // Depth buffer
  12443. this.setDepthBuffer(true);
  12444. this.setDepthFunctionToLessOrEqual();
  12445. this.setDepthWrite(true);
  12446. // Texture maps
  12447. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  12448. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12449. this._nextFreeTextureSlots.push(slot);
  12450. }
  12451. };
  12452. Object.defineProperty(Engine.prototype, "webGLVersion", {
  12453. /**
  12454. * Gets version of the current webGL context
  12455. */
  12456. get: function () {
  12457. return this._webGLVersion;
  12458. },
  12459. enumerable: true,
  12460. configurable: true
  12461. });
  12462. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  12463. /**
  12464. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  12465. */
  12466. get: function () {
  12467. return this._isStencilEnable;
  12468. },
  12469. enumerable: true,
  12470. configurable: true
  12471. });
  12472. Engine.prototype._prepareWorkingCanvas = function () {
  12473. if (this._workingCanvas) {
  12474. return;
  12475. }
  12476. this._workingCanvas = document.createElement("canvas");
  12477. var context = this._workingCanvas.getContext("2d");
  12478. if (context) {
  12479. this._workingContext = context;
  12480. }
  12481. };
  12482. /**
  12483. * Reset the texture cache to empty state
  12484. */
  12485. Engine.prototype.resetTextureCache = function () {
  12486. for (var key in this._boundTexturesCache) {
  12487. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  12488. continue;
  12489. }
  12490. var boundTexture = this._boundTexturesCache[key];
  12491. if (boundTexture) {
  12492. this._removeDesignatedSlot(boundTexture);
  12493. }
  12494. this._boundTexturesCache[key] = null;
  12495. }
  12496. if (!this.disableTextureBindingOptimization) {
  12497. this._nextFreeTextureSlots = [];
  12498. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12499. this._nextFreeTextureSlots.push(slot);
  12500. }
  12501. }
  12502. this._currentTextureChannel = -1;
  12503. };
  12504. /**
  12505. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  12506. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12507. * @returns true if engine is in deterministic lock step mode
  12508. */
  12509. Engine.prototype.isDeterministicLockStep = function () {
  12510. return this._deterministicLockstep;
  12511. };
  12512. /**
  12513. * Gets the max steps when engine is running in deterministic lock step
  12514. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12515. * @returns the max steps
  12516. */
  12517. Engine.prototype.getLockstepMaxSteps = function () {
  12518. return this._lockstepMaxSteps;
  12519. };
  12520. /**
  12521. * Gets an object containing information about the current webGL context
  12522. * @returns an object containing the vender, the renderer and the version of the current webGL context
  12523. */
  12524. Engine.prototype.getGlInfo = function () {
  12525. return {
  12526. vendor: this._glVendor,
  12527. renderer: this._glRenderer,
  12528. version: this._glVersion
  12529. };
  12530. };
  12531. /**
  12532. * Gets current aspect ratio
  12533. * @param camera defines the camera to use to get the aspect ratio
  12534. * @param useScreen defines if screen size must be used (or the current render target if any)
  12535. * @returns a number defining the aspect ratio
  12536. */
  12537. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  12538. if (useScreen === void 0) { useScreen = false; }
  12539. var viewport = camera.viewport;
  12540. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  12541. };
  12542. /**
  12543. * Gets current screen aspect ratio
  12544. * @returns a number defining the aspect ratio
  12545. */
  12546. Engine.prototype.getScreenAspectRatio = function () {
  12547. return (this.getRenderWidth(true)) / (this.getRenderHeight(true));
  12548. };
  12549. /**
  12550. * Gets the current render width
  12551. * @param useScreen defines if screen size must be used (or the current render target if any)
  12552. * @returns a number defining the current render width
  12553. */
  12554. Engine.prototype.getRenderWidth = function (useScreen) {
  12555. if (useScreen === void 0) { useScreen = false; }
  12556. if (!useScreen && this._currentRenderTarget) {
  12557. return this._currentRenderTarget.width;
  12558. }
  12559. return this._gl.drawingBufferWidth;
  12560. };
  12561. /**
  12562. * Gets the current render height
  12563. * @param useScreen defines if screen size must be used (or the current render target if any)
  12564. * @returns a number defining the current render height
  12565. */
  12566. Engine.prototype.getRenderHeight = function (useScreen) {
  12567. if (useScreen === void 0) { useScreen = false; }
  12568. if (!useScreen && this._currentRenderTarget) {
  12569. return this._currentRenderTarget.height;
  12570. }
  12571. return this._gl.drawingBufferHeight;
  12572. };
  12573. /**
  12574. * Gets the HTML canvas attached with the current webGL context
  12575. * @returns a HTML canvas
  12576. */
  12577. Engine.prototype.getRenderingCanvas = function () {
  12578. return this._renderingCanvas;
  12579. };
  12580. /**
  12581. * Gets the client rect of the HTML canvas attached with the current webGL context
  12582. * @returns a client rectanglee
  12583. */
  12584. Engine.prototype.getRenderingCanvasClientRect = function () {
  12585. if (!this._renderingCanvas) {
  12586. return null;
  12587. }
  12588. return this._renderingCanvas.getBoundingClientRect();
  12589. };
  12590. /**
  12591. * Defines the hardware scaling level.
  12592. * By default the hardware scaling level is computed from the window device ratio.
  12593. * 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.
  12594. * @param level defines the level to use
  12595. */
  12596. Engine.prototype.setHardwareScalingLevel = function (level) {
  12597. this._hardwareScalingLevel = level;
  12598. this.resize();
  12599. };
  12600. /**
  12601. * Gets the current hardware scaling level.
  12602. * By default the hardware scaling level is computed from the window device ratio.
  12603. * 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.
  12604. * @returns a number indicating the current hardware scaling level
  12605. */
  12606. Engine.prototype.getHardwareScalingLevel = function () {
  12607. return this._hardwareScalingLevel;
  12608. };
  12609. /**
  12610. * Gets the list of loaded textures
  12611. * @returns an array containing all loaded textures
  12612. */
  12613. Engine.prototype.getLoadedTexturesCache = function () {
  12614. return this._internalTexturesCache;
  12615. };
  12616. /**
  12617. * Gets the object containing all engine capabilities
  12618. * @returns the EngineCapabilities object
  12619. */
  12620. Engine.prototype.getCaps = function () {
  12621. return this._caps;
  12622. };
  12623. Object.defineProperty(Engine.prototype, "drawCalls", {
  12624. /** @hidden */
  12625. get: function () {
  12626. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  12627. return 0;
  12628. },
  12629. enumerable: true,
  12630. configurable: true
  12631. });
  12632. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  12633. /** @hidden */
  12634. get: function () {
  12635. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  12636. return null;
  12637. },
  12638. enumerable: true,
  12639. configurable: true
  12640. });
  12641. /**
  12642. * Gets the current depth function
  12643. * @returns a number defining the depth function
  12644. */
  12645. Engine.prototype.getDepthFunction = function () {
  12646. return this._depthCullingState.depthFunc;
  12647. };
  12648. /**
  12649. * Sets the current depth function
  12650. * @param depthFunc defines the function to use
  12651. */
  12652. Engine.prototype.setDepthFunction = function (depthFunc) {
  12653. this._depthCullingState.depthFunc = depthFunc;
  12654. };
  12655. /**
  12656. * Sets the current depth function to GREATER
  12657. */
  12658. Engine.prototype.setDepthFunctionToGreater = function () {
  12659. this._depthCullingState.depthFunc = this._gl.GREATER;
  12660. };
  12661. /**
  12662. * Sets the current depth function to GEQUAL
  12663. */
  12664. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  12665. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  12666. };
  12667. /**
  12668. * Sets the current depth function to LESS
  12669. */
  12670. Engine.prototype.setDepthFunctionToLess = function () {
  12671. this._depthCullingState.depthFunc = this._gl.LESS;
  12672. };
  12673. /**
  12674. * Sets the current depth function to LEQUAL
  12675. */
  12676. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  12677. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  12678. };
  12679. /**
  12680. * Gets a boolean indicating if stencil buffer is enabled
  12681. * @returns the current stencil buffer state
  12682. */
  12683. Engine.prototype.getStencilBuffer = function () {
  12684. return this._stencilState.stencilTest;
  12685. };
  12686. /**
  12687. * Enable or disable the stencil buffer
  12688. * @param enable defines if the stencil buffer must be enabled or disabled
  12689. */
  12690. Engine.prototype.setStencilBuffer = function (enable) {
  12691. this._stencilState.stencilTest = enable;
  12692. };
  12693. /**
  12694. * Gets the current stencil mask
  12695. * @returns a number defining the new stencil mask to use
  12696. */
  12697. Engine.prototype.getStencilMask = function () {
  12698. return this._stencilState.stencilMask;
  12699. };
  12700. /**
  12701. * Sets the current stencil mask
  12702. * @param mask defines the new stencil mask to use
  12703. */
  12704. Engine.prototype.setStencilMask = function (mask) {
  12705. this._stencilState.stencilMask = mask;
  12706. };
  12707. /**
  12708. * Gets the current stencil function
  12709. * @returns a number defining the stencil function to use
  12710. */
  12711. Engine.prototype.getStencilFunction = function () {
  12712. return this._stencilState.stencilFunc;
  12713. };
  12714. /**
  12715. * Gets the current stencil reference value
  12716. * @returns a number defining the stencil reference value to use
  12717. */
  12718. Engine.prototype.getStencilFunctionReference = function () {
  12719. return this._stencilState.stencilFuncRef;
  12720. };
  12721. /**
  12722. * Gets the current stencil mask
  12723. * @returns a number defining the stencil mask to use
  12724. */
  12725. Engine.prototype.getStencilFunctionMask = function () {
  12726. return this._stencilState.stencilFuncMask;
  12727. };
  12728. /**
  12729. * Sets the current stencil function
  12730. * @param stencilFunc defines the new stencil function to use
  12731. */
  12732. Engine.prototype.setStencilFunction = function (stencilFunc) {
  12733. this._stencilState.stencilFunc = stencilFunc;
  12734. };
  12735. /**
  12736. * Sets the current stencil reference
  12737. * @param reference defines the new stencil reference to use
  12738. */
  12739. Engine.prototype.setStencilFunctionReference = function (reference) {
  12740. this._stencilState.stencilFuncRef = reference;
  12741. };
  12742. /**
  12743. * Sets the current stencil mask
  12744. * @param mask defines the new stencil mask to use
  12745. */
  12746. Engine.prototype.setStencilFunctionMask = function (mask) {
  12747. this._stencilState.stencilFuncMask = mask;
  12748. };
  12749. /**
  12750. * Gets the current stencil operation when stencil fails
  12751. * @returns a number defining stencil operation to use when stencil fails
  12752. */
  12753. Engine.prototype.getStencilOperationFail = function () {
  12754. return this._stencilState.stencilOpStencilFail;
  12755. };
  12756. /**
  12757. * Gets the current stencil operation when depth fails
  12758. * @returns a number defining stencil operation to use when depth fails
  12759. */
  12760. Engine.prototype.getStencilOperationDepthFail = function () {
  12761. return this._stencilState.stencilOpDepthFail;
  12762. };
  12763. /**
  12764. * Gets the current stencil operation when stencil passes
  12765. * @returns a number defining stencil operation to use when stencil passes
  12766. */
  12767. Engine.prototype.getStencilOperationPass = function () {
  12768. return this._stencilState.stencilOpStencilDepthPass;
  12769. };
  12770. /**
  12771. * Sets the stencil operation to use when stencil fails
  12772. * @param operation defines the stencil operation to use when stencil fails
  12773. */
  12774. Engine.prototype.setStencilOperationFail = function (operation) {
  12775. this._stencilState.stencilOpStencilFail = operation;
  12776. };
  12777. /**
  12778. * Sets the stencil operation to use when depth fails
  12779. * @param operation defines the stencil operation to use when depth fails
  12780. */
  12781. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  12782. this._stencilState.stencilOpDepthFail = operation;
  12783. };
  12784. /**
  12785. * Sets the stencil operation to use when stencil passes
  12786. * @param operation defines the stencil operation to use when stencil passes
  12787. */
  12788. Engine.prototype.setStencilOperationPass = function (operation) {
  12789. this._stencilState.stencilOpStencilDepthPass = operation;
  12790. };
  12791. /**
  12792. * Sets a boolean indicating if the dithering state is enabled or disabled
  12793. * @param value defines the dithering state
  12794. */
  12795. Engine.prototype.setDitheringState = function (value) {
  12796. if (value) {
  12797. this._gl.enable(this._gl.DITHER);
  12798. }
  12799. else {
  12800. this._gl.disable(this._gl.DITHER);
  12801. }
  12802. };
  12803. /**
  12804. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  12805. * @param value defines the rasterizer state
  12806. */
  12807. Engine.prototype.setRasterizerState = function (value) {
  12808. if (value) {
  12809. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  12810. }
  12811. else {
  12812. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  12813. }
  12814. };
  12815. /**
  12816. * stop executing a render loop function and remove it from the execution array
  12817. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  12818. */
  12819. Engine.prototype.stopRenderLoop = function (renderFunction) {
  12820. if (!renderFunction) {
  12821. this._activeRenderLoops = [];
  12822. return;
  12823. }
  12824. var index = this._activeRenderLoops.indexOf(renderFunction);
  12825. if (index >= 0) {
  12826. this._activeRenderLoops.splice(index, 1);
  12827. }
  12828. };
  12829. /** @hidden */
  12830. Engine.prototype._renderLoop = function () {
  12831. if (!this._contextWasLost) {
  12832. var shouldRender = true;
  12833. if (!this.renderEvenInBackground && this._windowIsBackground) {
  12834. shouldRender = false;
  12835. }
  12836. if (shouldRender) {
  12837. // Start new frame
  12838. this.beginFrame();
  12839. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  12840. var renderFunction = this._activeRenderLoops[index];
  12841. renderFunction();
  12842. }
  12843. // Present
  12844. this.endFrame();
  12845. }
  12846. }
  12847. if (this._activeRenderLoops.length > 0) {
  12848. // Register new frame
  12849. var requester = null;
  12850. if (this._vrDisplay && this._vrDisplay.isPresenting)
  12851. requester = this._vrDisplay;
  12852. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  12853. }
  12854. else {
  12855. this._renderingQueueLaunched = false;
  12856. }
  12857. };
  12858. /**
  12859. * Register and execute a render loop. The engine can have more than one render function
  12860. * @param renderFunction defines the function to continuously execute
  12861. */
  12862. Engine.prototype.runRenderLoop = function (renderFunction) {
  12863. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  12864. return;
  12865. }
  12866. this._activeRenderLoops.push(renderFunction);
  12867. if (!this._renderingQueueLaunched) {
  12868. this._renderingQueueLaunched = true;
  12869. this._bindedRenderFunction = this._renderLoop.bind(this);
  12870. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  12871. }
  12872. };
  12873. /**
  12874. * Toggle full screen mode
  12875. * @param requestPointerLock defines if a pointer lock should be requested from the user
  12876. * @param options defines an option object to be sent to the requestFullscreen function
  12877. */
  12878. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  12879. if (this.isFullscreen) {
  12880. BABYLON.Tools.ExitFullscreen();
  12881. }
  12882. else {
  12883. this._pointerLockRequested = requestPointerLock;
  12884. if (this._renderingCanvas) {
  12885. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  12886. }
  12887. }
  12888. };
  12889. /**
  12890. * Clear the current render buffer or the current render target (if any is set up)
  12891. * @param color defines the color to use
  12892. * @param backBuffer defines if the back buffer must be cleared
  12893. * @param depth defines if the depth buffer must be cleared
  12894. * @param stencil defines if the stencil buffer must be cleared
  12895. */
  12896. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  12897. if (stencil === void 0) { stencil = false; }
  12898. this.applyStates();
  12899. var mode = 0;
  12900. if (backBuffer && color) {
  12901. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  12902. mode |= this._gl.COLOR_BUFFER_BIT;
  12903. }
  12904. if (depth) {
  12905. this._gl.clearDepth(1.0);
  12906. mode |= this._gl.DEPTH_BUFFER_BIT;
  12907. }
  12908. if (stencil) {
  12909. this._gl.clearStencil(0);
  12910. mode |= this._gl.STENCIL_BUFFER_BIT;
  12911. }
  12912. this._gl.clear(mode);
  12913. };
  12914. /**
  12915. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  12916. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  12917. * @param y defines the y-coordinate of the corner of the clear rectangle
  12918. * @param width defines the width of the clear rectangle
  12919. * @param height defines the height of the clear rectangle
  12920. * @param clearColor defines the clear color
  12921. */
  12922. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  12923. var gl = this._gl;
  12924. // Save state
  12925. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  12926. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  12927. // Change state
  12928. gl.enable(gl.SCISSOR_TEST);
  12929. gl.scissor(x, y, width, height);
  12930. // Clear
  12931. this.clear(clearColor, true, true, true);
  12932. // Restore state
  12933. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  12934. if (curScissor === true) {
  12935. gl.enable(gl.SCISSOR_TEST);
  12936. }
  12937. else {
  12938. gl.disable(gl.SCISSOR_TEST);
  12939. }
  12940. };
  12941. /**
  12942. * Set the WebGL's viewport
  12943. * @param viewport defines the viewport element to be used
  12944. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  12945. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  12946. */
  12947. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  12948. var width = requiredWidth || this.getRenderWidth();
  12949. var height = requiredHeight || this.getRenderHeight();
  12950. var x = viewport.x || 0;
  12951. var y = viewport.y || 0;
  12952. this._cachedViewport = viewport;
  12953. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  12954. };
  12955. /**
  12956. * Directly set the WebGL Viewport
  12957. * @param x defines the x coordinate of the viewport (in screen space)
  12958. * @param y defines the y coordinate of the viewport (in screen space)
  12959. * @param width defines the width of the viewport (in screen space)
  12960. * @param height defines the height of the viewport (in screen space)
  12961. * @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
  12962. */
  12963. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  12964. var currentViewport = this._cachedViewport;
  12965. this._cachedViewport = null;
  12966. this._gl.viewport(x, y, width, height);
  12967. return currentViewport;
  12968. };
  12969. /**
  12970. * Begin a new frame
  12971. */
  12972. Engine.prototype.beginFrame = function () {
  12973. this.onBeginFrameObservable.notifyObservers(this);
  12974. this._measureFps();
  12975. };
  12976. /**
  12977. * Enf the current frame
  12978. */
  12979. Engine.prototype.endFrame = function () {
  12980. // Force a flush in case we are using a bad OS.
  12981. if (this._badOS) {
  12982. this.flushFramebuffer();
  12983. }
  12984. // Submit frame to the vr device, if enabled
  12985. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12986. // TODO: We should only submit the frame if we read frameData successfully.
  12987. this._vrDisplay.submitFrame();
  12988. }
  12989. this.onEndFrameObservable.notifyObservers(this);
  12990. };
  12991. /**
  12992. * Resize the view according to the canvas' size
  12993. */
  12994. Engine.prototype.resize = function () {
  12995. // We're not resizing the size of the canvas while in VR mode & presenting
  12996. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  12997. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  12998. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  12999. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  13000. }
  13001. };
  13002. /**
  13003. * Force a specific size of the canvas
  13004. * @param width defines the new canvas' width
  13005. * @param height defines the new canvas' height
  13006. */
  13007. Engine.prototype.setSize = function (width, height) {
  13008. if (!this._renderingCanvas) {
  13009. return;
  13010. }
  13011. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  13012. return;
  13013. }
  13014. this._renderingCanvas.width = width;
  13015. this._renderingCanvas.height = height;
  13016. for (var index = 0; index < this.scenes.length; index++) {
  13017. var scene = this.scenes[index];
  13018. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  13019. var cam = scene.cameras[camIndex];
  13020. cam._currentRenderId = 0;
  13021. }
  13022. }
  13023. if (this.onResizeObservable.hasObservers) {
  13024. this.onResizeObservable.notifyObservers(this);
  13025. }
  13026. };
  13027. // WebVR functions
  13028. /**
  13029. * Gets a boolean indicating if a webVR device was detected
  13030. * @returns true if a webVR device was detected
  13031. */
  13032. Engine.prototype.isVRDevicePresent = function () {
  13033. return !!this._vrDisplay;
  13034. };
  13035. /**
  13036. * Gets the current webVR device
  13037. * @returns the current webVR device (or null)
  13038. */
  13039. Engine.prototype.getVRDevice = function () {
  13040. return this._vrDisplay;
  13041. };
  13042. /**
  13043. * Initializes a webVR display and starts listening to display change events
  13044. * The onVRDisplayChangedObservable will be notified upon these changes
  13045. * @returns The onVRDisplayChangedObservable
  13046. */
  13047. Engine.prototype.initWebVR = function () {
  13048. this.initWebVRAsync();
  13049. return this.onVRDisplayChangedObservable;
  13050. };
  13051. /**
  13052. * Initializes a webVR display and starts listening to display change events
  13053. * The onVRDisplayChangedObservable will be notified upon these changes
  13054. * @returns A promise containing a VRDisplay and if vr is supported
  13055. */
  13056. Engine.prototype.initWebVRAsync = function () {
  13057. var _this = this;
  13058. var notifyObservers = function () {
  13059. var eventArgs = {
  13060. vrDisplay: _this._vrDisplay,
  13061. vrSupported: _this._vrSupported
  13062. };
  13063. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  13064. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  13065. };
  13066. if (!this._onVrDisplayConnect) {
  13067. this._onVrDisplayConnect = function (event) {
  13068. _this._vrDisplay = event.display;
  13069. notifyObservers();
  13070. };
  13071. this._onVrDisplayDisconnect = function () {
  13072. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  13073. _this._vrDisplay = undefined;
  13074. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  13075. notifyObservers();
  13076. };
  13077. this._onVrDisplayPresentChange = function () {
  13078. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  13079. };
  13080. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  13081. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  13082. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  13083. }
  13084. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  13085. this._webVRInitPromise.then(notifyObservers);
  13086. return this._webVRInitPromise;
  13087. };
  13088. /**
  13089. * Call this function to switch to webVR mode
  13090. * Will do nothing if webVR is not supported or if there is no webVR device
  13091. * @see http://doc.babylonjs.com/how_to/webvr_camera
  13092. */
  13093. Engine.prototype.enableVR = function () {
  13094. var _this = this;
  13095. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  13096. var onResolved = function () {
  13097. _this.onVRRequestPresentComplete.notifyObservers(true);
  13098. _this._onVRFullScreenTriggered();
  13099. };
  13100. var onRejected = function () {
  13101. _this.onVRRequestPresentComplete.notifyObservers(false);
  13102. };
  13103. this.onVRRequestPresentStart.notifyObservers(this);
  13104. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  13105. }
  13106. };
  13107. /**
  13108. * Call this function to leave webVR mode
  13109. * Will do nothing if webVR is not supported or if there is no webVR device
  13110. * @see http://doc.babylonjs.com/how_to/webvr_camera
  13111. */
  13112. Engine.prototype.disableVR = function () {
  13113. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  13114. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  13115. }
  13116. };
  13117. Engine.prototype._getVRDisplaysAsync = function () {
  13118. var _this = this;
  13119. return new Promise(function (res, rej) {
  13120. if (navigator.getVRDisplays) {
  13121. navigator.getVRDisplays().then(function (devices) {
  13122. _this._vrSupported = true;
  13123. // note that devices may actually be an empty array. This is fine;
  13124. // we expect this._vrDisplay to be undefined in this case.
  13125. _this._vrDisplay = devices[0];
  13126. res({
  13127. vrDisplay: _this._vrDisplay,
  13128. vrSupported: _this._vrSupported
  13129. });
  13130. });
  13131. }
  13132. else {
  13133. _this._vrDisplay = undefined;
  13134. _this._vrSupported = false;
  13135. res({
  13136. vrDisplay: _this._vrDisplay,
  13137. vrSupported: _this._vrSupported
  13138. });
  13139. }
  13140. });
  13141. };
  13142. /**
  13143. * Binds the frame buffer to the specified texture.
  13144. * @param texture The texture to render to or null for the default canvas
  13145. * @param faceIndex The face of the texture to render to in case of cube texture
  13146. * @param requiredWidth The width of the target to render to
  13147. * @param requiredHeight The height of the target to render to
  13148. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  13149. * @param depthStencilTexture The depth stencil texture to use to render
  13150. * @param lodLevel defines le lod level to bind to the frame buffer
  13151. */
  13152. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture, lodLevel) {
  13153. if (lodLevel === void 0) { lodLevel = 0; }
  13154. if (this._currentRenderTarget) {
  13155. this.unBindFramebuffer(this._currentRenderTarget);
  13156. }
  13157. this._currentRenderTarget = texture;
  13158. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  13159. var gl = this._gl;
  13160. if (texture.isCube) {
  13161. if (faceIndex === undefined) {
  13162. faceIndex = 0;
  13163. }
  13164. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, lodLevel);
  13165. if (depthStencilTexture) {
  13166. if (depthStencilTexture._generateStencilBuffer) {
  13167. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  13168. }
  13169. else {
  13170. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  13171. }
  13172. }
  13173. }
  13174. if (this._cachedViewport && !forceFullscreenViewport) {
  13175. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  13176. }
  13177. else {
  13178. if (!requiredWidth) {
  13179. requiredWidth = texture.width;
  13180. if (lodLevel) {
  13181. requiredWidth = requiredWidth / Math.pow(2, lodLevel);
  13182. }
  13183. }
  13184. if (!requiredHeight) {
  13185. requiredHeight = texture.height;
  13186. if (lodLevel) {
  13187. requiredHeight = requiredHeight / Math.pow(2, lodLevel);
  13188. }
  13189. }
  13190. gl.viewport(0, 0, requiredWidth, requiredHeight);
  13191. }
  13192. this.wipeCaches();
  13193. };
  13194. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  13195. if (this._currentFramebuffer !== framebuffer) {
  13196. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  13197. this._currentFramebuffer = framebuffer;
  13198. }
  13199. };
  13200. /**
  13201. * Unbind the current render target texture from the webGL context
  13202. * @param texture defines the render target texture to unbind
  13203. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13204. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13205. */
  13206. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  13207. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13208. this._currentRenderTarget = null;
  13209. // If MSAA, we need to bitblt back to main texture
  13210. var gl = this._gl;
  13211. if (texture._MSAAFramebuffer) {
  13212. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  13213. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  13214. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13215. }
  13216. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13217. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13218. gl.generateMipmap(gl.TEXTURE_2D);
  13219. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13220. }
  13221. if (onBeforeUnbind) {
  13222. if (texture._MSAAFramebuffer) {
  13223. // Bind the correct framebuffer
  13224. this.bindUnboundFramebuffer(texture._framebuffer);
  13225. }
  13226. onBeforeUnbind();
  13227. }
  13228. this.bindUnboundFramebuffer(null);
  13229. };
  13230. /**
  13231. * Unbind a list of render target textures from the webGL context
  13232. * This is used only when drawBuffer extension or webGL2 are active
  13233. * @param textures defines the render target textures to unbind
  13234. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13235. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13236. */
  13237. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  13238. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13239. this._currentRenderTarget = null;
  13240. // If MSAA, we need to bitblt back to main texture
  13241. var gl = this._gl;
  13242. if (textures[0]._MSAAFramebuffer) {
  13243. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  13244. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  13245. var attachments = textures[0]._attachments;
  13246. if (!attachments) {
  13247. attachments = new Array(textures.length);
  13248. textures[0]._attachments = attachments;
  13249. }
  13250. for (var i = 0; i < textures.length; i++) {
  13251. var texture = textures[i];
  13252. for (var j = 0; j < attachments.length; j++) {
  13253. attachments[j] = gl.NONE;
  13254. }
  13255. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13256. gl.readBuffer(attachments[i]);
  13257. gl.drawBuffers(attachments);
  13258. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13259. }
  13260. for (var i = 0; i < attachments.length; i++) {
  13261. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13262. }
  13263. gl.drawBuffers(attachments);
  13264. }
  13265. for (var i = 0; i < textures.length; i++) {
  13266. var texture = textures[i];
  13267. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13268. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  13269. gl.generateMipmap(gl.TEXTURE_2D);
  13270. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13271. }
  13272. }
  13273. if (onBeforeUnbind) {
  13274. if (textures[0]._MSAAFramebuffer) {
  13275. // Bind the correct framebuffer
  13276. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13277. }
  13278. onBeforeUnbind();
  13279. }
  13280. this.bindUnboundFramebuffer(null);
  13281. };
  13282. /**
  13283. * Force the mipmap generation for the given render target texture
  13284. * @param texture defines the render target texture to use
  13285. */
  13286. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  13287. if (texture.generateMipMaps) {
  13288. var gl = this._gl;
  13289. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13290. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13291. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13292. }
  13293. };
  13294. /**
  13295. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  13296. */
  13297. Engine.prototype.flushFramebuffer = function () {
  13298. this._gl.flush();
  13299. };
  13300. /**
  13301. * Unbind the current render target and bind the default framebuffer
  13302. */
  13303. Engine.prototype.restoreDefaultFramebuffer = function () {
  13304. if (this._currentRenderTarget) {
  13305. this.unBindFramebuffer(this._currentRenderTarget);
  13306. }
  13307. else {
  13308. this.bindUnboundFramebuffer(null);
  13309. }
  13310. if (this._cachedViewport) {
  13311. this.setViewport(this._cachedViewport);
  13312. }
  13313. this.wipeCaches();
  13314. };
  13315. // UBOs
  13316. /**
  13317. * Create an uniform buffer
  13318. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13319. * @param elements defines the content of the uniform buffer
  13320. * @returns the webGL uniform buffer
  13321. */
  13322. Engine.prototype.createUniformBuffer = function (elements) {
  13323. var ubo = this._gl.createBuffer();
  13324. if (!ubo) {
  13325. throw new Error("Unable to create uniform buffer");
  13326. }
  13327. this.bindUniformBuffer(ubo);
  13328. if (elements instanceof Float32Array) {
  13329. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  13330. }
  13331. else {
  13332. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  13333. }
  13334. this.bindUniformBuffer(null);
  13335. ubo.references = 1;
  13336. return ubo;
  13337. };
  13338. /**
  13339. * Create a dynamic uniform buffer
  13340. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13341. * @param elements defines the content of the uniform buffer
  13342. * @returns the webGL uniform buffer
  13343. */
  13344. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  13345. var ubo = this._gl.createBuffer();
  13346. if (!ubo) {
  13347. throw new Error("Unable to create dynamic uniform buffer");
  13348. }
  13349. this.bindUniformBuffer(ubo);
  13350. if (elements instanceof Float32Array) {
  13351. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  13352. }
  13353. else {
  13354. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  13355. }
  13356. this.bindUniformBuffer(null);
  13357. ubo.references = 1;
  13358. return ubo;
  13359. };
  13360. /**
  13361. * Update an existing uniform buffer
  13362. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13363. * @param uniformBuffer defines the target uniform buffer
  13364. * @param elements defines the content to update
  13365. * @param offset defines the offset in the uniform buffer where update should start
  13366. * @param count defines the size of the data to update
  13367. */
  13368. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  13369. this.bindUniformBuffer(uniformBuffer);
  13370. if (offset === undefined) {
  13371. offset = 0;
  13372. }
  13373. if (count === undefined) {
  13374. if (elements instanceof Float32Array) {
  13375. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  13376. }
  13377. else {
  13378. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  13379. }
  13380. }
  13381. else {
  13382. if (elements instanceof Float32Array) {
  13383. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  13384. }
  13385. else {
  13386. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  13387. }
  13388. }
  13389. this.bindUniformBuffer(null);
  13390. };
  13391. // VBOs
  13392. Engine.prototype._resetVertexBufferBinding = function () {
  13393. this.bindArrayBuffer(null);
  13394. this._cachedVertexBuffers = null;
  13395. };
  13396. /**
  13397. * Creates a vertex buffer
  13398. * @param data the data for the vertex buffer
  13399. * @returns the new WebGL static buffer
  13400. */
  13401. Engine.prototype.createVertexBuffer = function (data) {
  13402. var vbo = this._gl.createBuffer();
  13403. if (!vbo) {
  13404. throw new Error("Unable to create vertex buffer");
  13405. }
  13406. this.bindArrayBuffer(vbo);
  13407. if (data instanceof Array) {
  13408. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  13409. }
  13410. else {
  13411. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  13412. }
  13413. this._resetVertexBufferBinding();
  13414. vbo.references = 1;
  13415. return vbo;
  13416. };
  13417. /**
  13418. * Creates a dynamic vertex buffer
  13419. * @param data the data for the dynamic vertex buffer
  13420. * @returns the new WebGL dynamic buffer
  13421. */
  13422. Engine.prototype.createDynamicVertexBuffer = function (data) {
  13423. var vbo = this._gl.createBuffer();
  13424. if (!vbo) {
  13425. throw new Error("Unable to create dynamic vertex buffer");
  13426. }
  13427. this.bindArrayBuffer(vbo);
  13428. if (data instanceof Array) {
  13429. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  13430. }
  13431. else {
  13432. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  13433. }
  13434. this._resetVertexBufferBinding();
  13435. vbo.references = 1;
  13436. return vbo;
  13437. };
  13438. /**
  13439. * Update a dynamic index buffer
  13440. * @param indexBuffer defines the target index buffer
  13441. * @param indices defines the data to update
  13442. * @param offset defines the offset in the target index buffer where update should start
  13443. */
  13444. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  13445. if (offset === void 0) { offset = 0; }
  13446. // Force cache update
  13447. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  13448. this.bindIndexBuffer(indexBuffer);
  13449. var arrayBuffer;
  13450. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  13451. arrayBuffer = indices;
  13452. }
  13453. else {
  13454. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13455. }
  13456. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  13457. this._resetIndexBufferBinding();
  13458. };
  13459. /**
  13460. * Updates a dynamic vertex buffer.
  13461. * @param vertexBuffer the vertex buffer to update
  13462. * @param data the data used to update the vertex buffer
  13463. * @param byteOffset the byte offset of the data
  13464. * @param byteLength the byte length of the data
  13465. */
  13466. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  13467. this.bindArrayBuffer(vertexBuffer);
  13468. if (byteOffset === undefined) {
  13469. byteOffset = 0;
  13470. }
  13471. if (byteLength === undefined) {
  13472. if (data instanceof Array) {
  13473. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  13474. }
  13475. else {
  13476. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  13477. }
  13478. }
  13479. else {
  13480. if (data instanceof Array) {
  13481. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  13482. }
  13483. else {
  13484. if (data instanceof ArrayBuffer) {
  13485. data = new Uint8Array(data, byteOffset, byteLength);
  13486. }
  13487. else {
  13488. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  13489. }
  13490. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13491. }
  13492. }
  13493. this._resetVertexBufferBinding();
  13494. };
  13495. Engine.prototype._resetIndexBufferBinding = function () {
  13496. this.bindIndexBuffer(null);
  13497. this._cachedIndexBuffer = null;
  13498. };
  13499. /**
  13500. * Creates a new index buffer
  13501. * @param indices defines the content of the index buffer
  13502. * @param updatable defines if the index buffer must be updatable
  13503. * @returns a new webGL buffer
  13504. */
  13505. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  13506. var vbo = this._gl.createBuffer();
  13507. if (!vbo) {
  13508. throw new Error("Unable to create index buffer");
  13509. }
  13510. this.bindIndexBuffer(vbo);
  13511. // Check for 32 bits indices
  13512. var arrayBuffer;
  13513. var need32Bits = false;
  13514. if (indices instanceof Uint16Array) {
  13515. arrayBuffer = indices;
  13516. }
  13517. else {
  13518. //check 32 bit support
  13519. if (this._caps.uintIndices) {
  13520. if (indices instanceof Uint32Array) {
  13521. arrayBuffer = indices;
  13522. need32Bits = true;
  13523. }
  13524. else {
  13525. //number[] or Int32Array, check if 32 bit is necessary
  13526. for (var index = 0; index < indices.length; index++) {
  13527. if (indices[index] > 65535) {
  13528. need32Bits = true;
  13529. break;
  13530. }
  13531. }
  13532. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13533. }
  13534. }
  13535. else {
  13536. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  13537. arrayBuffer = new Uint16Array(indices);
  13538. }
  13539. }
  13540. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  13541. this._resetIndexBufferBinding();
  13542. vbo.references = 1;
  13543. vbo.is32Bits = need32Bits;
  13544. return vbo;
  13545. };
  13546. /**
  13547. * Bind a webGL buffer to the webGL context
  13548. * @param buffer defines the buffer to bind
  13549. */
  13550. Engine.prototype.bindArrayBuffer = function (buffer) {
  13551. if (!this._vaoRecordInProgress) {
  13552. this._unbindVertexArrayObject();
  13553. }
  13554. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  13555. };
  13556. /**
  13557. * Bind an uniform buffer to the current webGL context
  13558. * @param buffer defines the buffer to bind
  13559. */
  13560. Engine.prototype.bindUniformBuffer = function (buffer) {
  13561. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  13562. };
  13563. /**
  13564. * Bind a buffer to the current webGL context at a given location
  13565. * @param buffer defines the buffer to bind
  13566. * @param location defines the index where to bind the buffer
  13567. */
  13568. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  13569. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  13570. };
  13571. /**
  13572. * Bind a specific block at a given index in a specific shader program
  13573. * @param shaderProgram defines the shader program
  13574. * @param blockName defines the block name
  13575. * @param index defines the index where to bind the block
  13576. */
  13577. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  13578. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  13579. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  13580. };
  13581. ;
  13582. Engine.prototype.bindIndexBuffer = function (buffer) {
  13583. if (!this._vaoRecordInProgress) {
  13584. this._unbindVertexArrayObject();
  13585. }
  13586. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  13587. };
  13588. Engine.prototype.bindBuffer = function (buffer, target) {
  13589. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  13590. this._gl.bindBuffer(target, buffer);
  13591. this._currentBoundBuffer[target] = buffer;
  13592. }
  13593. };
  13594. /**
  13595. * update the bound buffer with the given data
  13596. * @param data defines the data to update
  13597. */
  13598. Engine.prototype.updateArrayBuffer = function (data) {
  13599. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13600. };
  13601. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  13602. var pointer = this._currentBufferPointers[indx];
  13603. var changed = false;
  13604. if (!pointer.active) {
  13605. changed = true;
  13606. pointer.active = true;
  13607. pointer.index = indx;
  13608. pointer.size = size;
  13609. pointer.type = type;
  13610. pointer.normalized = normalized;
  13611. pointer.stride = stride;
  13612. pointer.offset = offset;
  13613. pointer.buffer = buffer;
  13614. }
  13615. else {
  13616. if (pointer.buffer !== buffer) {
  13617. pointer.buffer = buffer;
  13618. changed = true;
  13619. }
  13620. if (pointer.size !== size) {
  13621. pointer.size = size;
  13622. changed = true;
  13623. }
  13624. if (pointer.type !== type) {
  13625. pointer.type = type;
  13626. changed = true;
  13627. }
  13628. if (pointer.normalized !== normalized) {
  13629. pointer.normalized = normalized;
  13630. changed = true;
  13631. }
  13632. if (pointer.stride !== stride) {
  13633. pointer.stride = stride;
  13634. changed = true;
  13635. }
  13636. if (pointer.offset !== offset) {
  13637. pointer.offset = offset;
  13638. changed = true;
  13639. }
  13640. }
  13641. if (changed || this._vaoRecordInProgress) {
  13642. this.bindArrayBuffer(buffer);
  13643. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  13644. }
  13645. };
  13646. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  13647. if (indexBuffer == null) {
  13648. return;
  13649. }
  13650. if (this._cachedIndexBuffer !== indexBuffer) {
  13651. this._cachedIndexBuffer = indexBuffer;
  13652. this.bindIndexBuffer(indexBuffer);
  13653. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  13654. }
  13655. };
  13656. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  13657. var attributes = effect.getAttributesNames();
  13658. if (!this._vaoRecordInProgress) {
  13659. this._unbindVertexArrayObject();
  13660. }
  13661. this.unbindAllAttributes();
  13662. for (var index = 0; index < attributes.length; index++) {
  13663. var order = effect.getAttributeLocation(index);
  13664. if (order >= 0) {
  13665. var vertexBuffer = vertexBuffers[attributes[index]];
  13666. if (!vertexBuffer) {
  13667. continue;
  13668. }
  13669. this._gl.enableVertexAttribArray(order);
  13670. if (!this._vaoRecordInProgress) {
  13671. this._vertexAttribArraysEnabled[order] = true;
  13672. }
  13673. var buffer = vertexBuffer.getBuffer();
  13674. if (buffer) {
  13675. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  13676. if (vertexBuffer.getIsInstanced()) {
  13677. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  13678. if (!this._vaoRecordInProgress) {
  13679. this._currentInstanceLocations.push(order);
  13680. this._currentInstanceBuffers.push(buffer);
  13681. }
  13682. }
  13683. }
  13684. }
  13685. }
  13686. };
  13687. /**
  13688. * Records a vertex array object
  13689. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13690. * @param vertexBuffers defines the list of vertex buffers to store
  13691. * @param indexBuffer defines the index buffer to store
  13692. * @param effect defines the effect to store
  13693. * @returns the new vertex array object
  13694. */
  13695. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  13696. var vao = this._gl.createVertexArray();
  13697. this._vaoRecordInProgress = true;
  13698. this._gl.bindVertexArray(vao);
  13699. this._mustWipeVertexAttributes = true;
  13700. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13701. this.bindIndexBuffer(indexBuffer);
  13702. this._vaoRecordInProgress = false;
  13703. this._gl.bindVertexArray(null);
  13704. return vao;
  13705. };
  13706. /**
  13707. * Bind a specific vertex array object
  13708. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13709. * @param vertexArrayObject defines the vertex array object to bind
  13710. * @param indexBuffer defines the index buffer to bind
  13711. */
  13712. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  13713. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  13714. this._cachedVertexArrayObject = vertexArrayObject;
  13715. this._gl.bindVertexArray(vertexArrayObject);
  13716. this._cachedVertexBuffers = null;
  13717. this._cachedIndexBuffer = null;
  13718. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  13719. this._mustWipeVertexAttributes = true;
  13720. }
  13721. };
  13722. /**
  13723. * Bind webGl buffers directly to the webGL context
  13724. * @param vertexBuffer defines the vertex buffer to bind
  13725. * @param indexBuffer defines the index buffer to bind
  13726. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  13727. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  13728. * @param effect defines the effect associated with the vertex buffer
  13729. */
  13730. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  13731. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  13732. this._cachedVertexBuffers = vertexBuffer;
  13733. this._cachedEffectForVertexBuffers = effect;
  13734. var attributesCount = effect.getAttributesCount();
  13735. this._unbindVertexArrayObject();
  13736. this.unbindAllAttributes();
  13737. var offset = 0;
  13738. for (var index = 0; index < attributesCount; index++) {
  13739. if (index < vertexDeclaration.length) {
  13740. var order = effect.getAttributeLocation(index);
  13741. if (order >= 0) {
  13742. this._gl.enableVertexAttribArray(order);
  13743. this._vertexAttribArraysEnabled[order] = true;
  13744. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  13745. }
  13746. offset += vertexDeclaration[index] * 4;
  13747. }
  13748. }
  13749. }
  13750. this._bindIndexBufferWithCache(indexBuffer);
  13751. };
  13752. Engine.prototype._unbindVertexArrayObject = function () {
  13753. if (!this._cachedVertexArrayObject) {
  13754. return;
  13755. }
  13756. this._cachedVertexArrayObject = null;
  13757. this._gl.bindVertexArray(null);
  13758. };
  13759. /**
  13760. * Bind a list of vertex buffers to the webGL context
  13761. * @param vertexBuffers defines the list of vertex buffers to bind
  13762. * @param indexBuffer defines the index buffer to bind
  13763. * @param effect defines the effect associated with the vertex buffers
  13764. */
  13765. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  13766. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  13767. this._cachedVertexBuffers = vertexBuffers;
  13768. this._cachedEffectForVertexBuffers = effect;
  13769. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13770. }
  13771. this._bindIndexBufferWithCache(indexBuffer);
  13772. };
  13773. /**
  13774. * Unbind all instance attributes
  13775. */
  13776. Engine.prototype.unbindInstanceAttributes = function () {
  13777. var boundBuffer;
  13778. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  13779. var instancesBuffer = this._currentInstanceBuffers[i];
  13780. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  13781. boundBuffer = instancesBuffer;
  13782. this.bindArrayBuffer(instancesBuffer);
  13783. }
  13784. var offsetLocation = this._currentInstanceLocations[i];
  13785. this._gl.vertexAttribDivisor(offsetLocation, 0);
  13786. }
  13787. this._currentInstanceBuffers.length = 0;
  13788. this._currentInstanceLocations.length = 0;
  13789. };
  13790. /**
  13791. * Release and free the memory of a vertex array object
  13792. * @param vao defines the vertex array object to delete
  13793. */
  13794. Engine.prototype.releaseVertexArrayObject = function (vao) {
  13795. this._gl.deleteVertexArray(vao);
  13796. };
  13797. /** @hidden */
  13798. Engine.prototype._releaseBuffer = function (buffer) {
  13799. buffer.references--;
  13800. if (buffer.references === 0) {
  13801. this._gl.deleteBuffer(buffer);
  13802. return true;
  13803. }
  13804. return false;
  13805. };
  13806. /**
  13807. * Creates a webGL buffer to use with instanciation
  13808. * @param capacity defines the size of the buffer
  13809. * @returns the webGL buffer
  13810. */
  13811. Engine.prototype.createInstancesBuffer = function (capacity) {
  13812. var buffer = this._gl.createBuffer();
  13813. if (!buffer) {
  13814. throw new Error("Unable to create instance buffer");
  13815. }
  13816. buffer.capacity = capacity;
  13817. this.bindArrayBuffer(buffer);
  13818. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  13819. return buffer;
  13820. };
  13821. /**
  13822. * Delete a webGL buffer used with instanciation
  13823. * @param buffer defines the webGL buffer to delete
  13824. */
  13825. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  13826. this._gl.deleteBuffer(buffer);
  13827. };
  13828. /**
  13829. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  13830. * @param instancesBuffer defines the webGL buffer to update and bind
  13831. * @param data defines the data to store in the buffer
  13832. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  13833. */
  13834. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  13835. this.bindArrayBuffer(instancesBuffer);
  13836. if (data) {
  13837. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13838. }
  13839. if (offsetLocations[0].index !== undefined) {
  13840. var stride = 0;
  13841. for (var i = 0; i < offsetLocations.length; i++) {
  13842. var ai = offsetLocations[i];
  13843. stride += ai.attributeSize * 4;
  13844. }
  13845. for (var i = 0; i < offsetLocations.length; i++) {
  13846. var ai = offsetLocations[i];
  13847. if (!this._vertexAttribArraysEnabled[ai.index]) {
  13848. this._gl.enableVertexAttribArray(ai.index);
  13849. this._vertexAttribArraysEnabled[ai.index] = true;
  13850. }
  13851. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  13852. this._gl.vertexAttribDivisor(ai.index, 1);
  13853. this._currentInstanceLocations.push(ai.index);
  13854. this._currentInstanceBuffers.push(instancesBuffer);
  13855. }
  13856. }
  13857. else {
  13858. for (var index = 0; index < 4; index++) {
  13859. var offsetLocation = offsetLocations[index];
  13860. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  13861. this._gl.enableVertexAttribArray(offsetLocation);
  13862. this._vertexAttribArraysEnabled[offsetLocation] = true;
  13863. }
  13864. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  13865. this._gl.vertexAttribDivisor(offsetLocation, 1);
  13866. this._currentInstanceLocations.push(offsetLocation);
  13867. this._currentInstanceBuffers.push(instancesBuffer);
  13868. }
  13869. }
  13870. };
  13871. /**
  13872. * Apply all cached states (depth, culling, stencil and alpha)
  13873. */
  13874. Engine.prototype.applyStates = function () {
  13875. this._depthCullingState.apply(this._gl);
  13876. this._stencilState.apply(this._gl);
  13877. this._alphaState.apply(this._gl);
  13878. };
  13879. /**
  13880. * Send a draw order
  13881. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13882. * @param indexStart defines the starting index
  13883. * @param indexCount defines the number of index to draw
  13884. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13885. */
  13886. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  13887. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  13888. };
  13889. /**
  13890. * Draw a list of points
  13891. * @param verticesStart defines the index of first vertex to draw
  13892. * @param verticesCount defines the count of vertices to draw
  13893. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13894. */
  13895. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  13896. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  13897. };
  13898. /**
  13899. * Draw a list of unindexed primitives
  13900. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13901. * @param verticesStart defines the index of first vertex to draw
  13902. * @param verticesCount defines the count of vertices to draw
  13903. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13904. */
  13905. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  13906. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  13907. };
  13908. /**
  13909. * Draw a list of indexed primitives
  13910. * @param fillMode defines the primitive to use
  13911. * @param indexStart defines the starting index
  13912. * @param indexCount defines the number of index to draw
  13913. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13914. */
  13915. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  13916. // Apply states
  13917. this.applyStates();
  13918. this._drawCalls.addCount(1, false);
  13919. // Render
  13920. var drawMode = this._drawMode(fillMode);
  13921. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  13922. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  13923. if (instancesCount) {
  13924. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  13925. }
  13926. else {
  13927. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  13928. }
  13929. };
  13930. /**
  13931. * Draw a list of unindexed primitives
  13932. * @param fillMode defines the primitive to use
  13933. * @param verticesStart defines the index of first vertex to draw
  13934. * @param verticesCount defines the count of vertices to draw
  13935. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13936. */
  13937. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  13938. // Apply states
  13939. this.applyStates();
  13940. this._drawCalls.addCount(1, false);
  13941. var drawMode = this._drawMode(fillMode);
  13942. if (instancesCount) {
  13943. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  13944. }
  13945. else {
  13946. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  13947. }
  13948. };
  13949. Engine.prototype._drawMode = function (fillMode) {
  13950. switch (fillMode) {
  13951. // Triangle views
  13952. case BABYLON.Material.TriangleFillMode:
  13953. return this._gl.TRIANGLES;
  13954. case BABYLON.Material.PointFillMode:
  13955. return this._gl.POINTS;
  13956. case BABYLON.Material.WireFrameFillMode:
  13957. return this._gl.LINES;
  13958. // Draw modes
  13959. case BABYLON.Material.PointListDrawMode:
  13960. return this._gl.POINTS;
  13961. case BABYLON.Material.LineListDrawMode:
  13962. return this._gl.LINES;
  13963. case BABYLON.Material.LineLoopDrawMode:
  13964. return this._gl.LINE_LOOP;
  13965. case BABYLON.Material.LineStripDrawMode:
  13966. return this._gl.LINE_STRIP;
  13967. case BABYLON.Material.TriangleStripDrawMode:
  13968. return this._gl.TRIANGLE_STRIP;
  13969. case BABYLON.Material.TriangleFanDrawMode:
  13970. return this._gl.TRIANGLE_FAN;
  13971. default:
  13972. return this._gl.TRIANGLES;
  13973. }
  13974. };
  13975. // Shaders
  13976. /** @hidden */
  13977. Engine.prototype._releaseEffect = function (effect) {
  13978. if (this._compiledEffects[effect._key]) {
  13979. delete this._compiledEffects[effect._key];
  13980. this._deleteProgram(effect.getProgram());
  13981. }
  13982. };
  13983. /** @hidden */
  13984. Engine.prototype._deleteProgram = function (program) {
  13985. if (program) {
  13986. program.__SPECTOR_rebuildProgram = null;
  13987. if (program.transformFeedback) {
  13988. this.deleteTransformFeedback(program.transformFeedback);
  13989. program.transformFeedback = null;
  13990. }
  13991. this._gl.deleteProgram(program);
  13992. }
  13993. };
  13994. /**
  13995. * Create a new effect (used to store vertex/fragment shaders)
  13996. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  13997. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  13998. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  13999. * @param samplers defines an array of string used to represent textures
  14000. * @param defines defines the string containing the defines to use to compile the shaders
  14001. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  14002. * @param onCompiled defines a function to call when the effect creation is successful
  14003. * @param onError defines a function to call when the effect creation has failed
  14004. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  14005. * @returns the new Effect
  14006. */
  14007. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  14008. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  14009. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  14010. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  14011. if (this._compiledEffects[name]) {
  14012. var compiledEffect = this._compiledEffects[name];
  14013. if (onCompiled && compiledEffect.isReady()) {
  14014. onCompiled(compiledEffect);
  14015. }
  14016. return compiledEffect;
  14017. }
  14018. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  14019. effect._key = name;
  14020. this._compiledEffects[name] = effect;
  14021. return effect;
  14022. };
  14023. /**
  14024. * Create an effect to use with particle systems
  14025. * @param fragmentName defines the base name of the effect (The name of file without .fragment.fx)
  14026. * @param uniformsNames defines a list of attribute names
  14027. * @param samplers defines an array of string used to represent textures
  14028. * @param defines defines the string containing the defines to use to compile the shaders
  14029. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  14030. * @param onCompiled defines a function to call when the effect creation is successful
  14031. * @param onError defines a function to call when the effect creation has failed
  14032. * @returns the new Effect
  14033. */
  14034. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  14035. if (uniformsNames === void 0) { uniformsNames = []; }
  14036. if (samplers === void 0) { samplers = []; }
  14037. if (defines === void 0) { defines = ""; }
  14038. return this.createEffect({
  14039. vertex: "particles",
  14040. fragmentElement: fragmentName
  14041. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  14042. };
  14043. /**
  14044. * Directly creates a webGL program
  14045. * @param vertexCode defines the vertex shader code to use
  14046. * @param fragmentCode defines the fragment shader code to use
  14047. * @param context defines the webGL context to use (if not set, the current one will be used)
  14048. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  14049. * @returns the new webGL program
  14050. */
  14051. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  14052. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14053. context = context || this._gl;
  14054. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  14055. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  14056. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  14057. };
  14058. /**
  14059. * Creates a webGL program
  14060. * @param vertexCode defines the vertex shader code to use
  14061. * @param fragmentCode defines the fragment shader code to use
  14062. * @param defines defines the string containing the defines to use to compile the shaders
  14063. * @param context defines the webGL context to use (if not set, the current one will be used)
  14064. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  14065. * @returns the new webGL program
  14066. */
  14067. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  14068. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14069. context = context || this._gl;
  14070. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  14071. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  14072. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  14073. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  14074. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  14075. this.onAfterShaderCompilationObservable.notifyObservers(this);
  14076. return program;
  14077. };
  14078. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  14079. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14080. var shaderProgram = context.createProgram();
  14081. if (!shaderProgram) {
  14082. throw new Error("Unable to create program");
  14083. }
  14084. context.attachShader(shaderProgram, vertexShader);
  14085. context.attachShader(shaderProgram, fragmentShader);
  14086. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  14087. var transformFeedback = this.createTransformFeedback();
  14088. this.bindTransformFeedback(transformFeedback);
  14089. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  14090. shaderProgram.transformFeedback = transformFeedback;
  14091. }
  14092. context.linkProgram(shaderProgram);
  14093. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  14094. this.bindTransformFeedback(null);
  14095. }
  14096. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  14097. if (!linked) {
  14098. context.validateProgram(shaderProgram);
  14099. var error = context.getProgramInfoLog(shaderProgram);
  14100. if (error) {
  14101. throw new Error(error);
  14102. }
  14103. }
  14104. context.deleteShader(vertexShader);
  14105. context.deleteShader(fragmentShader);
  14106. return shaderProgram;
  14107. };
  14108. /**
  14109. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  14110. * @param shaderProgram defines the webGL program to use
  14111. * @param uniformsNames defines the list of uniform names
  14112. * @returns an array of webGL uniform locations
  14113. */
  14114. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  14115. var results = new Array();
  14116. for (var index = 0; index < uniformsNames.length; index++) {
  14117. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  14118. }
  14119. return results;
  14120. };
  14121. /**
  14122. * Gets the lsit of active attributes for a given webGL program
  14123. * @param shaderProgram defines the webGL program to use
  14124. * @param attributesNames defines the list of attribute names to get
  14125. * @returns an array of indices indicating the offset of each attribute
  14126. */
  14127. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  14128. var results = [];
  14129. for (var index = 0; index < attributesNames.length; index++) {
  14130. try {
  14131. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  14132. }
  14133. catch (e) {
  14134. results.push(-1);
  14135. }
  14136. }
  14137. return results;
  14138. };
  14139. /**
  14140. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  14141. * @param effect defines the effect to activate
  14142. */
  14143. Engine.prototype.enableEffect = function (effect) {
  14144. if (!effect) {
  14145. return;
  14146. }
  14147. // Use program
  14148. this.bindSamplers(effect);
  14149. this._currentEffect = effect;
  14150. if (effect.onBind) {
  14151. effect.onBind(effect);
  14152. }
  14153. effect.onBindObservable.notifyObservers(effect);
  14154. };
  14155. /**
  14156. * Set the value of an uniform to an array of int32
  14157. * @param uniform defines the webGL uniform location where to store the value
  14158. * @param array defines the array of int32 to store
  14159. */
  14160. Engine.prototype.setIntArray = function (uniform, array) {
  14161. if (!uniform)
  14162. return;
  14163. this._gl.uniform1iv(uniform, array);
  14164. };
  14165. /**
  14166. * Set the value of an uniform to an array of int32 (stored as vec2)
  14167. * @param uniform defines the webGL uniform location where to store the value
  14168. * @param array defines the array of int32 to store
  14169. */
  14170. Engine.prototype.setIntArray2 = function (uniform, array) {
  14171. if (!uniform || array.length % 2 !== 0)
  14172. return;
  14173. this._gl.uniform2iv(uniform, array);
  14174. };
  14175. /**
  14176. * Set the value of an uniform to an array of int32 (stored as vec3)
  14177. * @param uniform defines the webGL uniform location where to store the value
  14178. * @param array defines the array of int32 to store
  14179. */
  14180. Engine.prototype.setIntArray3 = function (uniform, array) {
  14181. if (!uniform || array.length % 3 !== 0)
  14182. return;
  14183. this._gl.uniform3iv(uniform, array);
  14184. };
  14185. /**
  14186. * Set the value of an uniform to an array of int32 (stored as vec4)
  14187. * @param uniform defines the webGL uniform location where to store the value
  14188. * @param array defines the array of int32 to store
  14189. */
  14190. Engine.prototype.setIntArray4 = function (uniform, array) {
  14191. if (!uniform || array.length % 4 !== 0)
  14192. return;
  14193. this._gl.uniform4iv(uniform, array);
  14194. };
  14195. /**
  14196. * Set the value of an uniform to an array of float32
  14197. * @param uniform defines the webGL uniform location where to store the value
  14198. * @param array defines the array of float32 to store
  14199. */
  14200. Engine.prototype.setFloatArray = function (uniform, array) {
  14201. if (!uniform)
  14202. return;
  14203. this._gl.uniform1fv(uniform, array);
  14204. };
  14205. /**
  14206. * Set the value of an uniform to an array of float32 (stored as vec2)
  14207. * @param uniform defines the webGL uniform location where to store the value
  14208. * @param array defines the array of float32 to store
  14209. */
  14210. Engine.prototype.setFloatArray2 = function (uniform, array) {
  14211. if (!uniform || array.length % 2 !== 0)
  14212. return;
  14213. this._gl.uniform2fv(uniform, array);
  14214. };
  14215. /**
  14216. * Set the value of an uniform to an array of float32 (stored as vec3)
  14217. * @param uniform defines the webGL uniform location where to store the value
  14218. * @param array defines the array of float32 to store
  14219. */
  14220. Engine.prototype.setFloatArray3 = function (uniform, array) {
  14221. if (!uniform || array.length % 3 !== 0)
  14222. return;
  14223. this._gl.uniform3fv(uniform, array);
  14224. };
  14225. /**
  14226. * Set the value of an uniform to an array of float32 (stored as vec4)
  14227. * @param uniform defines the webGL uniform location where to store the value
  14228. * @param array defines the array of float32 to store
  14229. */
  14230. Engine.prototype.setFloatArray4 = function (uniform, array) {
  14231. if (!uniform || array.length % 4 !== 0)
  14232. return;
  14233. this._gl.uniform4fv(uniform, array);
  14234. };
  14235. /**
  14236. * Set the value of an uniform to an array of number
  14237. * @param uniform defines the webGL uniform location where to store the value
  14238. * @param array defines the array of number to store
  14239. */
  14240. Engine.prototype.setArray = function (uniform, array) {
  14241. if (!uniform)
  14242. return;
  14243. this._gl.uniform1fv(uniform, array);
  14244. };
  14245. /**
  14246. * Set the value of an uniform to an array of number (stored as vec2)
  14247. * @param uniform defines the webGL uniform location where to store the value
  14248. * @param array defines the array of number to store
  14249. */
  14250. Engine.prototype.setArray2 = function (uniform, array) {
  14251. if (!uniform || array.length % 2 !== 0)
  14252. return;
  14253. this._gl.uniform2fv(uniform, array);
  14254. };
  14255. /**
  14256. * Set the value of an uniform to an array of number (stored as vec3)
  14257. * @param uniform defines the webGL uniform location where to store the value
  14258. * @param array defines the array of number to store
  14259. */
  14260. Engine.prototype.setArray3 = function (uniform, array) {
  14261. if (!uniform || array.length % 3 !== 0)
  14262. return;
  14263. this._gl.uniform3fv(uniform, array);
  14264. };
  14265. /**
  14266. * Set the value of an uniform to an array of number (stored as vec4)
  14267. * @param uniform defines the webGL uniform location where to store the value
  14268. * @param array defines the array of number to store
  14269. */
  14270. Engine.prototype.setArray4 = function (uniform, array) {
  14271. if (!uniform || array.length % 4 !== 0)
  14272. return;
  14273. this._gl.uniform4fv(uniform, array);
  14274. };
  14275. /**
  14276. * Set the value of an uniform to an array of float32 (stored as matrices)
  14277. * @param uniform defines the webGL uniform location where to store the value
  14278. * @param matrices defines the array of float32 to store
  14279. */
  14280. Engine.prototype.setMatrices = function (uniform, matrices) {
  14281. if (!uniform)
  14282. return;
  14283. this._gl.uniformMatrix4fv(uniform, false, matrices);
  14284. };
  14285. /**
  14286. * Set the value of an uniform to a matrix
  14287. * @param uniform defines the webGL uniform location where to store the value
  14288. * @param matrix defines the matrix to store
  14289. */
  14290. Engine.prototype.setMatrix = function (uniform, matrix) {
  14291. if (!uniform)
  14292. return;
  14293. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  14294. };
  14295. /**
  14296. * Set the value of an uniform to a matrix (3x3)
  14297. * @param uniform defines the webGL uniform location where to store the value
  14298. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  14299. */
  14300. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  14301. if (!uniform)
  14302. return;
  14303. this._gl.uniformMatrix3fv(uniform, false, matrix);
  14304. };
  14305. /**
  14306. * Set the value of an uniform to a matrix (2x2)
  14307. * @param uniform defines the webGL uniform location where to store the value
  14308. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  14309. */
  14310. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  14311. if (!uniform)
  14312. return;
  14313. this._gl.uniformMatrix2fv(uniform, false, matrix);
  14314. };
  14315. /**
  14316. * Set the value of an uniform to a number (int)
  14317. * @param uniform defines the webGL uniform location where to store the value
  14318. * @param value defines the int number to store
  14319. */
  14320. Engine.prototype.setInt = function (uniform, value) {
  14321. if (!uniform)
  14322. return;
  14323. this._gl.uniform1i(uniform, value);
  14324. };
  14325. /**
  14326. * Set the value of an uniform to a number (float)
  14327. * @param uniform defines the webGL uniform location where to store the value
  14328. * @param value defines the float number to store
  14329. */
  14330. Engine.prototype.setFloat = function (uniform, value) {
  14331. if (!uniform)
  14332. return;
  14333. this._gl.uniform1f(uniform, value);
  14334. };
  14335. /**
  14336. * Set the value of an uniform to a vec2
  14337. * @param uniform defines the webGL uniform location where to store the value
  14338. * @param x defines the 1st component of the value
  14339. * @param y defines the 2nd component of the value
  14340. */
  14341. Engine.prototype.setFloat2 = function (uniform, x, y) {
  14342. if (!uniform)
  14343. return;
  14344. this._gl.uniform2f(uniform, x, y);
  14345. };
  14346. /**
  14347. * Set the value of an uniform to a vec3
  14348. * @param uniform defines the webGL uniform location where to store the value
  14349. * @param x defines the 1st component of the value
  14350. * @param y defines the 2nd component of the value
  14351. * @param z defines the 3rd component of the value
  14352. */
  14353. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  14354. if (!uniform)
  14355. return;
  14356. this._gl.uniform3f(uniform, x, y, z);
  14357. };
  14358. /**
  14359. * Set the value of an uniform to a boolean
  14360. * @param uniform defines the webGL uniform location where to store the value
  14361. * @param bool defines the boolean to store
  14362. */
  14363. Engine.prototype.setBool = function (uniform, bool) {
  14364. if (!uniform)
  14365. return;
  14366. this._gl.uniform1i(uniform, bool);
  14367. };
  14368. /**
  14369. * Set the value of an uniform to a vec4
  14370. * @param uniform defines the webGL uniform location where to store the value
  14371. * @param x defines the 1st component of the value
  14372. * @param y defines the 2nd component of the value
  14373. * @param z defines the 3rd component of the value
  14374. * @param w defines the 4th component of the value
  14375. */
  14376. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  14377. if (!uniform)
  14378. return;
  14379. this._gl.uniform4f(uniform, x, y, z, w);
  14380. };
  14381. /**
  14382. * Set the value of an uniform to a Color3
  14383. * @param uniform defines the webGL uniform location where to store the value
  14384. * @param color3 defines the color to store
  14385. */
  14386. Engine.prototype.setColor3 = function (uniform, color3) {
  14387. if (!uniform)
  14388. return;
  14389. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  14390. };
  14391. /**
  14392. * Set the value of an uniform to a Color3 and an alpha value
  14393. * @param uniform defines the webGL uniform location where to store the value
  14394. * @param color3 defines the color to store
  14395. * @param alpha defines the alpha component to store
  14396. */
  14397. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  14398. if (!uniform)
  14399. return;
  14400. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  14401. };
  14402. /**
  14403. * Sets a Color4 on a uniform variable
  14404. * @param uniform defines the uniform location
  14405. * @param color4 defines the value to be set
  14406. */
  14407. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  14408. if (!uniform)
  14409. return;
  14410. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  14411. };
  14412. // States
  14413. /**
  14414. * Set various states to the webGL context
  14415. * @param culling defines backface culling state
  14416. * @param zOffset defines the value to apply to zOffset (0 by default)
  14417. * @param force defines if states must be applied even if cache is up to date
  14418. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  14419. */
  14420. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  14421. if (zOffset === void 0) { zOffset = 0; }
  14422. if (reverseSide === void 0) { reverseSide = false; }
  14423. // Culling
  14424. if (this._depthCullingState.cull !== culling || force) {
  14425. this._depthCullingState.cull = culling;
  14426. }
  14427. // Cull face
  14428. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  14429. if (this._depthCullingState.cullFace !== cullFace || force) {
  14430. this._depthCullingState.cullFace = cullFace;
  14431. }
  14432. // Z offset
  14433. this.setZOffset(zOffset);
  14434. // Front face
  14435. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  14436. if (this._depthCullingState.frontFace !== frontFace || force) {
  14437. this._depthCullingState.frontFace = frontFace;
  14438. }
  14439. };
  14440. /**
  14441. * Set the z offset to apply to current rendering
  14442. * @param value defines the offset to apply
  14443. */
  14444. Engine.prototype.setZOffset = function (value) {
  14445. this._depthCullingState.zOffset = value;
  14446. };
  14447. /**
  14448. * Gets the current value of the zOffset
  14449. * @returns the current zOffset state
  14450. */
  14451. Engine.prototype.getZOffset = function () {
  14452. return this._depthCullingState.zOffset;
  14453. };
  14454. /**
  14455. * Enable or disable depth buffering
  14456. * @param enable defines the state to set
  14457. */
  14458. Engine.prototype.setDepthBuffer = function (enable) {
  14459. this._depthCullingState.depthTest = enable;
  14460. };
  14461. /**
  14462. * Gets a boolean indicating if depth writing is enabled
  14463. * @returns the current depth writing state
  14464. */
  14465. Engine.prototype.getDepthWrite = function () {
  14466. return this._depthCullingState.depthMask;
  14467. };
  14468. /**
  14469. * Enable or disable depth writing
  14470. * @param enable defines the state to set
  14471. */
  14472. Engine.prototype.setDepthWrite = function (enable) {
  14473. this._depthCullingState.depthMask = enable;
  14474. };
  14475. /**
  14476. * Enable or disable color writing
  14477. * @param enable defines the state to set
  14478. */
  14479. Engine.prototype.setColorWrite = function (enable) {
  14480. this._gl.colorMask(enable, enable, enable, enable);
  14481. this._colorWrite = enable;
  14482. };
  14483. /**
  14484. * Gets a boolean indicating if color writing is enabled
  14485. * @returns the current color writing state
  14486. */
  14487. Engine.prototype.getColorWrite = function () {
  14488. return this._colorWrite;
  14489. };
  14490. /**
  14491. * Sets alpha constants used by some alpha blending modes
  14492. * @param r defines the red component
  14493. * @param g defines the green component
  14494. * @param b defines the blue component
  14495. * @param a defines the alpha component
  14496. */
  14497. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  14498. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  14499. };
  14500. /**
  14501. * Sets the current alpha mode
  14502. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  14503. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  14504. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14505. */
  14506. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  14507. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  14508. if (this._alphaMode === mode) {
  14509. return;
  14510. }
  14511. switch (mode) {
  14512. case Engine.ALPHA_DISABLE:
  14513. this._alphaState.alphaBlend = false;
  14514. break;
  14515. case Engine.ALPHA_PREMULTIPLIED:
  14516. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14517. this._alphaState.alphaBlend = true;
  14518. break;
  14519. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  14520. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14521. this._alphaState.alphaBlend = true;
  14522. break;
  14523. case Engine.ALPHA_COMBINE:
  14524. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14525. this._alphaState.alphaBlend = true;
  14526. break;
  14527. case Engine.ALPHA_ONEONE:
  14528. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14529. this._alphaState.alphaBlend = true;
  14530. break;
  14531. case Engine.ALPHA_ADD:
  14532. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14533. this._alphaState.alphaBlend = true;
  14534. break;
  14535. case Engine.ALPHA_SUBTRACT:
  14536. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14537. this._alphaState.alphaBlend = true;
  14538. break;
  14539. case Engine.ALPHA_MULTIPLY:
  14540. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  14541. this._alphaState.alphaBlend = true;
  14542. break;
  14543. case Engine.ALPHA_MAXIMIZED:
  14544. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14545. this._alphaState.alphaBlend = true;
  14546. break;
  14547. case Engine.ALPHA_INTERPOLATE:
  14548. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  14549. this._alphaState.alphaBlend = true;
  14550. break;
  14551. case Engine.ALPHA_SCREENMODE:
  14552. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14553. this._alphaState.alphaBlend = true;
  14554. break;
  14555. }
  14556. if (!noDepthWriteChange) {
  14557. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  14558. }
  14559. this._alphaMode = mode;
  14560. };
  14561. /**
  14562. * Gets the current alpha mode
  14563. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14564. * @returns the current alpha mode
  14565. */
  14566. Engine.prototype.getAlphaMode = function () {
  14567. return this._alphaMode;
  14568. };
  14569. // Textures
  14570. /**
  14571. * Clears the list of texture accessible through engine.
  14572. * This can help preventing texture load conflict due to name collision.
  14573. */
  14574. Engine.prototype.clearInternalTexturesCache = function () {
  14575. this._internalTexturesCache = [];
  14576. };
  14577. /**
  14578. * Force the entire cache to be cleared
  14579. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  14580. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  14581. */
  14582. Engine.prototype.wipeCaches = function (bruteForce) {
  14583. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  14584. return;
  14585. }
  14586. this._currentEffect = null;
  14587. if (bruteForce) {
  14588. this.resetTextureCache();
  14589. this._currentProgram = null;
  14590. this._stencilState.reset();
  14591. this._depthCullingState.reset();
  14592. this.setDepthFunctionToLessOrEqual();
  14593. this._alphaState.reset();
  14594. }
  14595. this._resetVertexBufferBinding();
  14596. this._cachedIndexBuffer = null;
  14597. this._cachedEffectForVertexBuffers = null;
  14598. this._unbindVertexArrayObject();
  14599. this.bindIndexBuffer(null);
  14600. };
  14601. /**
  14602. * Set the compressed texture format to use, based on the formats you have, and the formats
  14603. * supported by the hardware / browser.
  14604. *
  14605. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  14606. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  14607. * to API arguments needed to compressed textures. This puts the burden on the container
  14608. * generator to house the arcane code for determining these for current & future formats.
  14609. *
  14610. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  14611. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  14612. *
  14613. * Note: The result of this call is not taken into account when a texture is base64.
  14614. *
  14615. * @param formatsAvailable defines the list of those format families you have created
  14616. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  14617. *
  14618. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  14619. * @returns The extension selected.
  14620. */
  14621. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  14622. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  14623. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  14624. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  14625. return this._textureFormatInUse = this._texturesSupported[i];
  14626. }
  14627. }
  14628. }
  14629. // actively set format to nothing, to allow this to be called more than once
  14630. // and possibly fail the 2nd time
  14631. this._textureFormatInUse = null;
  14632. return null;
  14633. };
  14634. /** @hidden */
  14635. Engine.prototype._createTexture = function () {
  14636. var texture = this._gl.createTexture();
  14637. if (!texture) {
  14638. throw new Error("Unable to create texture");
  14639. }
  14640. return texture;
  14641. };
  14642. /**
  14643. * Usually called from BABYLON.Texture.ts.
  14644. * Passed information to create a WebGLTexture
  14645. * @param urlArg defines a value which contains one of the following:
  14646. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  14647. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  14648. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  14649. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  14650. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  14651. * @param scene needed for loading to the correct scene
  14652. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  14653. * @param onLoad optional callback to be called upon successful completion
  14654. * @param onError optional callback to be called upon failure
  14655. * @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
  14656. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  14657. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  14658. * @returns a InternalTexture for assignment back into BABYLON.Texture
  14659. */
  14660. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format) {
  14661. var _this = this;
  14662. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14663. if (onLoad === void 0) { onLoad = null; }
  14664. if (onError === void 0) { onError = null; }
  14665. if (buffer === void 0) { buffer = null; }
  14666. if (fallback === void 0) { fallback = null; }
  14667. if (format === void 0) { format = null; }
  14668. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  14669. var fromData = url.substr(0, 5) === "data:";
  14670. var fromBlob = url.substr(0, 5) === "blob:";
  14671. var isBase64 = fromData && url.indexOf("base64") !== -1;
  14672. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  14673. // establish the file extension, if possible
  14674. var lastDot = url.lastIndexOf('.');
  14675. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  14676. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  14677. var isTGA = (extension.indexOf(".tga") === 0);
  14678. // determine if a ktx file should be substituted
  14679. var isKTX = false;
  14680. if (this._textureFormatInUse && !isBase64 && !fallback) {
  14681. url = url.substring(0, lastDot) + this._textureFormatInUse;
  14682. isKTX = true;
  14683. }
  14684. if (scene) {
  14685. scene._addPendingData(texture);
  14686. }
  14687. texture.url = url;
  14688. texture.generateMipMaps = !noMipmap;
  14689. texture.samplingMode = samplingMode;
  14690. texture.invertY = invertY;
  14691. if (!this._doNotHandleContextLost) {
  14692. // Keep a link to the buffer only if we plan to handle context lost
  14693. texture._buffer = buffer;
  14694. }
  14695. var onLoadObserver = null;
  14696. if (onLoad && !fallback) {
  14697. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  14698. }
  14699. if (!fallback)
  14700. this._internalTexturesCache.push(texture);
  14701. var onerror = function (message, exception) {
  14702. if (scene) {
  14703. scene._removePendingData(texture);
  14704. }
  14705. if (onLoadObserver) {
  14706. texture.onLoadedObservable.remove(onLoadObserver);
  14707. }
  14708. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  14709. if (isKTX) {
  14710. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14711. }
  14712. else if (BABYLON.Tools.UseFallbackTexture) {
  14713. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14714. }
  14715. if (onError) {
  14716. onError(message || "Unknown error", exception);
  14717. }
  14718. };
  14719. var callback = null;
  14720. // processing for non-image formats
  14721. if (isKTX || isTGA || isDDS) {
  14722. if (isKTX) {
  14723. callback = function (data) {
  14724. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  14725. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  14726. ktx.uploadLevels(_this._gl, !noMipmap);
  14727. return false;
  14728. }, samplingMode);
  14729. };
  14730. }
  14731. else if (isTGA) {
  14732. callback = function (arrayBuffer) {
  14733. var data = new Uint8Array(arrayBuffer);
  14734. var header = BABYLON.TGATools.GetTGAHeader(data);
  14735. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  14736. BABYLON.TGATools.UploadContent(_this._gl, data);
  14737. return false;
  14738. }, samplingMode);
  14739. };
  14740. }
  14741. else if (isDDS) {
  14742. callback = function (data) {
  14743. var info = BABYLON.DDSTools.GetDDSInfo(data);
  14744. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  14745. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  14746. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  14747. return false;
  14748. }, samplingMode);
  14749. };
  14750. }
  14751. if (!buffer) {
  14752. this._loadFile(url, function (data) {
  14753. if (callback) {
  14754. callback(data);
  14755. }
  14756. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  14757. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  14758. });
  14759. }
  14760. else {
  14761. if (callback) {
  14762. callback(buffer);
  14763. }
  14764. }
  14765. // image format processing
  14766. }
  14767. else {
  14768. var onload = function (img) {
  14769. if (fromBlob && !_this._doNotHandleContextLost) {
  14770. // We need to store the image if we need to rebuild the texture
  14771. // in case of a webgl context lost
  14772. texture._buffer = img;
  14773. }
  14774. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  14775. var gl = _this._gl;
  14776. var isPot = (img.width === potWidth && img.height === potHeight);
  14777. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  14778. if (isPot) {
  14779. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14780. return false;
  14781. }
  14782. // Using shaders to rescale because canvas.drawImage is lossy
  14783. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14784. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  14785. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14786. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14787. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14788. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14789. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14790. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  14791. _this._releaseTexture(source);
  14792. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14793. continuationCallback();
  14794. });
  14795. return true;
  14796. }, samplingMode);
  14797. };
  14798. if (!fromData || isBase64) {
  14799. if (buffer instanceof HTMLImageElement) {
  14800. onload(buffer);
  14801. }
  14802. else {
  14803. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  14804. }
  14805. }
  14806. else if (typeof buffer === "string" || buffer instanceof ArrayBuffer || buffer instanceof Blob) {
  14807. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  14808. }
  14809. else {
  14810. onload(buffer);
  14811. }
  14812. }
  14813. return texture;
  14814. };
  14815. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  14816. var _this = this;
  14817. var rtt = this.createRenderTargetTexture({
  14818. width: destination.width,
  14819. height: destination.height,
  14820. }, {
  14821. generateMipMaps: false,
  14822. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  14823. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  14824. generateDepthBuffer: false,
  14825. generateStencilBuffer: false
  14826. });
  14827. if (!this._rescalePostProcess) {
  14828. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  14829. }
  14830. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  14831. _this._rescalePostProcess.onApply = function (effect) {
  14832. effect._bindTexture("textureSampler", source);
  14833. };
  14834. var hostingScene = scene;
  14835. if (!hostingScene) {
  14836. hostingScene = _this.scenes[_this.scenes.length - 1];
  14837. }
  14838. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  14839. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  14840. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  14841. _this.unBindFramebuffer(rtt);
  14842. _this._releaseTexture(rtt);
  14843. if (onComplete) {
  14844. onComplete();
  14845. }
  14846. });
  14847. };
  14848. /**
  14849. * Update a raw texture
  14850. * @param texture defines the texture to update
  14851. * @param data defines the data to store in the texture
  14852. * @param format defines the format of the data
  14853. * @param invertY defines if data must be stored with Y axis inverted
  14854. * @param compression defines the compression used (null by default)
  14855. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14856. */
  14857. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  14858. if (compression === void 0) { compression = null; }
  14859. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14860. if (!texture) {
  14861. return;
  14862. }
  14863. // babylon's internalSizedFomat but gl's texImage2D internalFormat
  14864. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  14865. // babylon's internalFormat but gl's texImage2D format
  14866. var internalFormat = this._getInternalFormat(format);
  14867. var textureType = this._getWebGLTextureType(type);
  14868. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14869. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14870. if (!this._doNotHandleContextLost) {
  14871. texture._bufferView = data;
  14872. texture.format = format;
  14873. texture.type = type;
  14874. texture.invertY = invertY;
  14875. texture._compression = compression;
  14876. }
  14877. if (texture.width % 4 !== 0) {
  14878. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14879. }
  14880. if (compression && data) {
  14881. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  14882. }
  14883. else {
  14884. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  14885. }
  14886. if (texture.generateMipMaps) {
  14887. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14888. }
  14889. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14890. // this.resetTextureCache();
  14891. texture.isReady = true;
  14892. };
  14893. /**
  14894. * Creates a raw texture
  14895. * @param data defines the data to store in the texture
  14896. * @param width defines the width of the texture
  14897. * @param height defines the height of the texture
  14898. * @param format defines the format of the data
  14899. * @param generateMipMaps defines if the engine should generate the mip levels
  14900. * @param invertY defines if data must be stored with Y axis inverted
  14901. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14902. * @param compression defines the compression used (null by default)
  14903. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14904. * @returns the raw texture inside an InternalTexture
  14905. */
  14906. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  14907. if (compression === void 0) { compression = null; }
  14908. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14909. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  14910. texture.baseWidth = width;
  14911. texture.baseHeight = height;
  14912. texture.width = width;
  14913. texture.height = height;
  14914. texture.format = format;
  14915. texture.generateMipMaps = generateMipMaps;
  14916. texture.samplingMode = samplingMode;
  14917. texture.invertY = invertY;
  14918. texture._compression = compression;
  14919. texture.type = type;
  14920. if (!this._doNotHandleContextLost) {
  14921. texture._bufferView = data;
  14922. }
  14923. this.updateRawTexture(texture, data, format, invertY, compression, type);
  14924. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14925. // Filters
  14926. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  14927. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14928. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14929. if (generateMipMaps) {
  14930. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14931. }
  14932. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14933. this._internalTexturesCache.push(texture);
  14934. return texture;
  14935. };
  14936. /**
  14937. * Creates a dynamic texture
  14938. * @param width defines the width of the texture
  14939. * @param height defines the height of the texture
  14940. * @param generateMipMaps defines if the engine should generate the mip levels
  14941. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14942. * @returns the dynamic texture inside an InternalTexture
  14943. */
  14944. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  14945. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  14946. texture.baseWidth = width;
  14947. texture.baseHeight = height;
  14948. if (generateMipMaps) {
  14949. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  14950. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  14951. }
  14952. // this.resetTextureCache();
  14953. texture.width = width;
  14954. texture.height = height;
  14955. texture.isReady = false;
  14956. texture.generateMipMaps = generateMipMaps;
  14957. texture.samplingMode = samplingMode;
  14958. this.updateTextureSamplingMode(samplingMode, texture);
  14959. this._internalTexturesCache.push(texture);
  14960. return texture;
  14961. };
  14962. /**
  14963. * Update the sampling mode of a given texture
  14964. * @param samplingMode defines the required sampling mode
  14965. * @param texture defines the texture to update
  14966. */
  14967. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  14968. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  14969. if (texture.isCube) {
  14970. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14971. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14972. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14973. }
  14974. else if (texture.is3D) {
  14975. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14976. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14977. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14978. }
  14979. else {
  14980. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14981. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14982. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14983. }
  14984. texture.samplingMode = samplingMode;
  14985. };
  14986. /**
  14987. * Update the content of a dynamic texture
  14988. * @param texture defines the texture to update
  14989. * @param canvas defines the canvas containing the source
  14990. * @param invertY defines if data must be stored with Y axis inverted
  14991. * @param premulAlpha defines if alpha is stored as premultiplied
  14992. * @param format defines the format of the data
  14993. */
  14994. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  14995. if (premulAlpha === void 0) { premulAlpha = false; }
  14996. if (!texture) {
  14997. return;
  14998. }
  14999. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15000. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  15001. if (premulAlpha) {
  15002. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  15003. }
  15004. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  15005. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  15006. if (texture.generateMipMaps) {
  15007. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15008. }
  15009. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15010. if (premulAlpha) {
  15011. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  15012. }
  15013. texture.isReady = true;
  15014. };
  15015. /**
  15016. * Update a video texture
  15017. * @param texture defines the texture to update
  15018. * @param video defines the video element to use
  15019. * @param invertY defines if data must be stored with Y axis inverted
  15020. */
  15021. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  15022. if (!texture || texture._isDisabled) {
  15023. return;
  15024. }
  15025. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15026. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  15027. try {
  15028. // Testing video texture support
  15029. if (this._videoTextureSupported === undefined) {
  15030. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  15031. if (this._gl.getError() !== 0) {
  15032. this._videoTextureSupported = false;
  15033. }
  15034. else {
  15035. this._videoTextureSupported = true;
  15036. }
  15037. }
  15038. // Copy video through the current working canvas if video texture is not supported
  15039. if (!this._videoTextureSupported) {
  15040. if (!texture._workingCanvas) {
  15041. texture._workingCanvas = document.createElement("canvas");
  15042. var context = texture._workingCanvas.getContext("2d");
  15043. if (!context) {
  15044. throw new Error("Unable to get 2d context");
  15045. }
  15046. texture._workingContext = context;
  15047. texture._workingCanvas.width = texture.width;
  15048. texture._workingCanvas.height = texture.height;
  15049. }
  15050. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  15051. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  15052. }
  15053. else {
  15054. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  15055. }
  15056. if (texture.generateMipMaps) {
  15057. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15058. }
  15059. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15060. // this.resetTextureCache();
  15061. texture.isReady = true;
  15062. }
  15063. catch (ex) {
  15064. // Something unexpected
  15065. // Let's disable the texture
  15066. texture._isDisabled = true;
  15067. }
  15068. };
  15069. /**
  15070. * Updates a depth texture Comparison Mode and Function.
  15071. * If the comparison Function is equal to 0, the mode will be set to none.
  15072. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  15073. * @param texture The texture to set the comparison function for
  15074. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  15075. */
  15076. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  15077. if (this.webGLVersion === 1) {
  15078. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  15079. return;
  15080. }
  15081. var gl = this._gl;
  15082. if (texture.isCube) {
  15083. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15084. if (comparisonFunction === 0) {
  15085. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15086. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15087. }
  15088. else {
  15089. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15090. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15091. }
  15092. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15093. }
  15094. else {
  15095. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15096. if (comparisonFunction === 0) {
  15097. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15098. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15099. }
  15100. else {
  15101. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15102. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15103. }
  15104. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15105. }
  15106. texture._comparisonFunction = comparisonFunction;
  15107. };
  15108. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  15109. var width = size.width || size;
  15110. var height = size.height || size;
  15111. internalTexture.baseWidth = width;
  15112. internalTexture.baseHeight = height;
  15113. internalTexture.width = width;
  15114. internalTexture.height = height;
  15115. internalTexture.isReady = true;
  15116. internalTexture.samples = 1;
  15117. internalTexture.generateMipMaps = false;
  15118. internalTexture._generateDepthBuffer = true;
  15119. internalTexture._generateStencilBuffer = generateStencil;
  15120. internalTexture.samplingMode = bilinearFiltering ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15121. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15122. internalTexture._comparisonFunction = comparisonFunction;
  15123. var gl = this._gl;
  15124. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15125. var samplingParameters = getSamplingParameters(internalTexture.samplingMode, false, gl);
  15126. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  15127. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  15128. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15129. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15130. if (comparisonFunction === 0) {
  15131. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15132. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15133. }
  15134. else {
  15135. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15136. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15137. }
  15138. };
  15139. /**
  15140. * Creates a depth stencil texture.
  15141. * This is only available in WebGL 2 or with the depth texture extension available.
  15142. * @param size The size of face edge in the texture.
  15143. * @param options The options defining the texture.
  15144. * @returns The texture
  15145. */
  15146. Engine.prototype.createDepthStencilTexture = function (size, options) {
  15147. if (options.isCube) {
  15148. var width = size.width || size;
  15149. return this._createDepthStencilCubeTexture(width, options);
  15150. }
  15151. else {
  15152. return this._createDepthStencilTexture(size, options);
  15153. }
  15154. };
  15155. /**
  15156. * Creates a depth stencil texture.
  15157. * This is only available in WebGL 2 or with the depth texture extension available.
  15158. * @param size The size of face edge in the texture.
  15159. * @param options The options defining the texture.
  15160. * @returns The texture
  15161. */
  15162. Engine.prototype._createDepthStencilTexture = function (size, options) {
  15163. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  15164. if (!this._caps.depthTextureExtension) {
  15165. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  15166. return internalTexture;
  15167. }
  15168. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15169. var gl = this._gl;
  15170. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  15171. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15172. if (this.webGLVersion > 1) {
  15173. if (internalOptions.generateStencil) {
  15174. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15175. }
  15176. else {
  15177. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15178. }
  15179. }
  15180. else {
  15181. if (internalOptions.generateStencil) {
  15182. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15183. }
  15184. else {
  15185. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15186. }
  15187. }
  15188. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15189. return internalTexture;
  15190. };
  15191. /**
  15192. * Creates a depth stencil cube texture.
  15193. * This is only available in WebGL 2.
  15194. * @param size The size of face edge in the cube texture.
  15195. * @param options The options defining the cube texture.
  15196. * @returns The cube texture
  15197. */
  15198. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  15199. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  15200. internalTexture.isCube = true;
  15201. if (this.webGLVersion === 1) {
  15202. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  15203. return internalTexture;
  15204. }
  15205. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15206. var gl = this._gl;
  15207. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  15208. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15209. // Create the depth/stencil buffer
  15210. for (var face = 0; face < 6; face++) {
  15211. if (internalOptions.generateStencil) {
  15212. 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);
  15213. }
  15214. else {
  15215. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15216. }
  15217. }
  15218. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15219. return internalTexture;
  15220. };
  15221. /**
  15222. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  15223. * @param renderTarget The render target to set the frame buffer for
  15224. */
  15225. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  15226. // Create the framebuffer
  15227. var internalTexture = renderTarget.getInternalTexture();
  15228. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  15229. return;
  15230. }
  15231. var gl = this._gl;
  15232. var depthStencilTexture = renderTarget.depthStencilTexture;
  15233. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  15234. if (depthStencilTexture.isCube) {
  15235. if (depthStencilTexture._generateStencilBuffer) {
  15236. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15237. }
  15238. else {
  15239. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15240. }
  15241. }
  15242. else {
  15243. if (depthStencilTexture._generateStencilBuffer) {
  15244. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15245. }
  15246. else {
  15247. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15248. }
  15249. }
  15250. this.bindUnboundFramebuffer(null);
  15251. };
  15252. /**
  15253. * Creates a new render target texture
  15254. * @param size defines the size of the texture
  15255. * @param options defines the options used to create the texture
  15256. * @returns a new render target texture stored in an InternalTexture
  15257. */
  15258. Engine.prototype.createRenderTargetTexture = function (size, options) {
  15259. var fullOptions = new RenderTargetCreationOptions();
  15260. if (options !== undefined && typeof options === "object") {
  15261. fullOptions.generateMipMaps = options.generateMipMaps;
  15262. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15263. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  15264. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  15265. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  15266. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  15267. }
  15268. else {
  15269. fullOptions.generateMipMaps = options;
  15270. fullOptions.generateDepthBuffer = true;
  15271. fullOptions.generateStencilBuffer = false;
  15272. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15273. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  15274. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  15275. }
  15276. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15277. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15278. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15279. }
  15280. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15281. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15282. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15283. }
  15284. var gl = this._gl;
  15285. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15286. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15287. var width = size.width || size;
  15288. var height = size.height || size;
  15289. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  15290. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15291. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15292. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15293. }
  15294. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15295. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15296. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15297. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15298. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  15299. // Create the framebuffer
  15300. var currentFrameBuffer = this._currentFramebuffer;
  15301. var framebuffer = gl.createFramebuffer();
  15302. this.bindUnboundFramebuffer(framebuffer);
  15303. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15304. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  15305. if (fullOptions.generateMipMaps) {
  15306. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15307. }
  15308. // Unbind
  15309. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15310. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15311. this.bindUnboundFramebuffer(currentFrameBuffer);
  15312. texture._framebuffer = framebuffer;
  15313. texture.baseWidth = width;
  15314. texture.baseHeight = height;
  15315. texture.width = width;
  15316. texture.height = height;
  15317. texture.isReady = true;
  15318. texture.samples = 1;
  15319. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  15320. texture.samplingMode = fullOptions.samplingMode;
  15321. texture.type = fullOptions.type;
  15322. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15323. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  15324. // this.resetTextureCache();
  15325. this._internalTexturesCache.push(texture);
  15326. return texture;
  15327. };
  15328. /**
  15329. * Create a multi render target texture
  15330. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  15331. * @param size defines the size of the texture
  15332. * @param options defines the creation options
  15333. * @returns the cube texture as an InternalTexture
  15334. */
  15335. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  15336. var generateMipMaps = false;
  15337. var generateDepthBuffer = true;
  15338. var generateStencilBuffer = false;
  15339. var generateDepthTexture = false;
  15340. var textureCount = 1;
  15341. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  15342. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  15343. var types = new Array();
  15344. var samplingModes = new Array();
  15345. if (options !== undefined) {
  15346. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  15347. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15348. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  15349. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  15350. textureCount = options.textureCount || 1;
  15351. if (options.types) {
  15352. types = options.types;
  15353. }
  15354. if (options.samplingModes) {
  15355. samplingModes = options.samplingModes;
  15356. }
  15357. }
  15358. var gl = this._gl;
  15359. // Create the framebuffer
  15360. var framebuffer = gl.createFramebuffer();
  15361. this.bindUnboundFramebuffer(framebuffer);
  15362. var width = size.width || size;
  15363. var height = size.height || size;
  15364. var textures = [];
  15365. var attachments = [];
  15366. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  15367. for (var i = 0; i < textureCount; i++) {
  15368. var samplingMode = samplingModes[i] || defaultSamplingMode;
  15369. var type = types[i] || defaultType;
  15370. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15371. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15372. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15373. }
  15374. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15375. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15376. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15377. }
  15378. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  15379. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15380. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15381. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15382. }
  15383. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15384. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15385. textures.push(texture);
  15386. attachments.push(attachment);
  15387. gl.activeTexture(gl["TEXTURE" + i]);
  15388. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  15389. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15390. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15391. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15392. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15393. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15394. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15395. if (generateMipMaps) {
  15396. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15397. }
  15398. // Unbind
  15399. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15400. texture._framebuffer = framebuffer;
  15401. texture._depthStencilBuffer = depthStencilBuffer;
  15402. texture.baseWidth = width;
  15403. texture.baseHeight = height;
  15404. texture.width = width;
  15405. texture.height = height;
  15406. texture.isReady = true;
  15407. texture.samples = 1;
  15408. texture.generateMipMaps = generateMipMaps;
  15409. texture.samplingMode = samplingMode;
  15410. texture.type = type;
  15411. texture._generateDepthBuffer = generateDepthBuffer;
  15412. texture._generateStencilBuffer = generateStencilBuffer;
  15413. texture._attachments = attachments;
  15414. this._internalTexturesCache.push(texture);
  15415. }
  15416. if (generateDepthTexture && this._caps.depthTextureExtension) {
  15417. // Depth texture
  15418. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15419. gl.activeTexture(gl.TEXTURE0);
  15420. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  15421. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15422. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15423. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15424. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15425. 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);
  15426. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  15427. depthTexture._framebuffer = framebuffer;
  15428. depthTexture.baseWidth = width;
  15429. depthTexture.baseHeight = height;
  15430. depthTexture.width = width;
  15431. depthTexture.height = height;
  15432. depthTexture.isReady = true;
  15433. depthTexture.samples = 1;
  15434. depthTexture.generateMipMaps = generateMipMaps;
  15435. depthTexture.samplingMode = gl.NEAREST;
  15436. depthTexture._generateDepthBuffer = generateDepthBuffer;
  15437. depthTexture._generateStencilBuffer = generateStencilBuffer;
  15438. textures.push(depthTexture);
  15439. this._internalTexturesCache.push(depthTexture);
  15440. }
  15441. gl.drawBuffers(attachments);
  15442. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15443. this.bindUnboundFramebuffer(null);
  15444. this.resetTextureCache();
  15445. return textures;
  15446. };
  15447. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  15448. if (samples === void 0) { samples = 1; }
  15449. var depthStencilBuffer = null;
  15450. var gl = this._gl;
  15451. // Create the depth/stencil buffer
  15452. if (generateStencilBuffer) {
  15453. depthStencilBuffer = gl.createRenderbuffer();
  15454. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15455. if (samples > 1) {
  15456. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  15457. }
  15458. else {
  15459. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  15460. }
  15461. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15462. }
  15463. else if (generateDepthBuffer) {
  15464. depthStencilBuffer = gl.createRenderbuffer();
  15465. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15466. if (samples > 1) {
  15467. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  15468. }
  15469. else {
  15470. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  15471. }
  15472. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15473. }
  15474. return depthStencilBuffer;
  15475. };
  15476. /**
  15477. * Updates the sample count of a render target texture
  15478. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15479. * @param texture defines the texture to update
  15480. * @param samples defines the sample count to set
  15481. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15482. */
  15483. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  15484. if (this.webGLVersion < 2 || !texture) {
  15485. return 1;
  15486. }
  15487. if (texture.samples === samples) {
  15488. return samples;
  15489. }
  15490. var gl = this._gl;
  15491. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15492. // Dispose previous render buffers
  15493. if (texture._depthStencilBuffer) {
  15494. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  15495. texture._depthStencilBuffer = null;
  15496. }
  15497. if (texture._MSAAFramebuffer) {
  15498. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  15499. texture._MSAAFramebuffer = null;
  15500. }
  15501. if (texture._MSAARenderBuffer) {
  15502. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  15503. texture._MSAARenderBuffer = null;
  15504. }
  15505. if (samples > 1) {
  15506. var framebuffer = gl.createFramebuffer();
  15507. if (!framebuffer) {
  15508. throw new Error("Unable to create multi sampled framebuffer");
  15509. }
  15510. texture._MSAAFramebuffer = framebuffer;
  15511. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  15512. var colorRenderbuffer = gl.createRenderbuffer();
  15513. if (!colorRenderbuffer) {
  15514. throw new Error("Unable to create multi sampled framebuffer");
  15515. }
  15516. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15517. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15518. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  15519. texture._MSAARenderBuffer = colorRenderbuffer;
  15520. }
  15521. else {
  15522. this.bindUnboundFramebuffer(texture._framebuffer);
  15523. }
  15524. texture.samples = samples;
  15525. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  15526. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15527. this.bindUnboundFramebuffer(null);
  15528. return samples;
  15529. };
  15530. /**
  15531. * Update the sample count for a given multiple render target texture
  15532. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15533. * @param textures defines the textures to update
  15534. * @param samples defines the sample count to set
  15535. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15536. */
  15537. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  15538. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  15539. return 1;
  15540. }
  15541. if (textures[0].samples === samples) {
  15542. return samples;
  15543. }
  15544. var gl = this._gl;
  15545. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15546. // Dispose previous render buffers
  15547. if (textures[0]._depthStencilBuffer) {
  15548. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  15549. textures[0]._depthStencilBuffer = null;
  15550. }
  15551. if (textures[0]._MSAAFramebuffer) {
  15552. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  15553. textures[0]._MSAAFramebuffer = null;
  15554. }
  15555. for (var i = 0; i < textures.length; i++) {
  15556. if (textures[i]._MSAARenderBuffer) {
  15557. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  15558. textures[i]._MSAARenderBuffer = null;
  15559. }
  15560. }
  15561. if (samples > 1) {
  15562. var framebuffer = gl.createFramebuffer();
  15563. if (!framebuffer) {
  15564. throw new Error("Unable to create multi sampled framebuffer");
  15565. }
  15566. this.bindUnboundFramebuffer(framebuffer);
  15567. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  15568. var attachments = [];
  15569. for (var i = 0; i < textures.length; i++) {
  15570. var texture = textures[i];
  15571. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15572. var colorRenderbuffer = gl.createRenderbuffer();
  15573. if (!colorRenderbuffer) {
  15574. throw new Error("Unable to create multi sampled framebuffer");
  15575. }
  15576. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15577. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15578. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  15579. texture._MSAAFramebuffer = framebuffer;
  15580. texture._MSAARenderBuffer = colorRenderbuffer;
  15581. texture.samples = samples;
  15582. texture._depthStencilBuffer = depthStencilBuffer;
  15583. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15584. attachments.push(attachment);
  15585. }
  15586. gl.drawBuffers(attachments);
  15587. }
  15588. else {
  15589. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  15590. }
  15591. this.bindUnboundFramebuffer(null);
  15592. return samples;
  15593. };
  15594. /** @hidden */
  15595. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  15596. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  15597. };
  15598. /** @hidden */
  15599. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  15600. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  15601. };
  15602. /** @hidden */
  15603. Engine.prototype._uploadImageToTexture = function (texture, faceIndex, lod, image) {
  15604. var gl = this._gl;
  15605. var textureType = this._getWebGLTextureType(texture.type);
  15606. var format = this._getInternalFormat(texture.format);
  15607. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  15608. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15609. this._bindTextureDirectly(bindTarget, texture, true);
  15610. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, texture.invertY ? 1 : 0);
  15611. var target = gl.TEXTURE_2D;
  15612. if (texture.isCube) {
  15613. var target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15614. }
  15615. gl.texImage2D(target, lod, internalFormat, format, textureType, image);
  15616. this._bindTextureDirectly(bindTarget, null, true);
  15617. };
  15618. /**
  15619. * Creates a new render target cube texture
  15620. * @param size defines the size of the texture
  15621. * @param options defines the options used to create the texture
  15622. * @returns a new render target cube texture stored in an InternalTexture
  15623. */
  15624. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  15625. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  15626. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  15627. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15628. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15629. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15630. }
  15631. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15632. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15633. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15634. }
  15635. var gl = this._gl;
  15636. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15637. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15638. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  15639. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15640. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15641. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  15642. }
  15643. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15644. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15645. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15646. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15647. for (var face = 0; face < 6; face++) {
  15648. 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);
  15649. }
  15650. // Create the framebuffer
  15651. var framebuffer = gl.createFramebuffer();
  15652. this.bindUnboundFramebuffer(framebuffer);
  15653. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  15654. // MipMaps
  15655. if (fullOptions.generateMipMaps) {
  15656. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15657. }
  15658. // Unbind
  15659. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15660. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15661. this.bindUnboundFramebuffer(null);
  15662. texture._framebuffer = framebuffer;
  15663. texture.width = size;
  15664. texture.height = size;
  15665. texture.isReady = true;
  15666. texture.isCube = true;
  15667. texture.samples = 1;
  15668. texture.generateMipMaps = fullOptions.generateMipMaps;
  15669. texture.samplingMode = fullOptions.samplingMode;
  15670. texture.type = fullOptions.type;
  15671. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15672. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  15673. this._internalTexturesCache.push(texture);
  15674. return texture;
  15675. };
  15676. /**
  15677. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  15678. * @param rootUrl defines the url where the file to load is located
  15679. * @param scene defines the current scene
  15680. * @param lodScale defines scale to apply to the mip map selection
  15681. * @param lodOffset defines offset to apply to the mip map selection
  15682. * @param onLoad defines an optional callback raised when the texture is loaded
  15683. * @param onError defines an optional callback raised if there is an issue to load the texture
  15684. * @param format defines the format of the data
  15685. * @param forcedExtension defines the extension to use to pick the right loader
  15686. * @param createPolynomials defines wheter or not to create polynomails harmonics for the texture
  15687. * @returns the cube texture as an InternalTexture
  15688. */
  15689. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, createPolynomials) {
  15690. var _this = this;
  15691. if (onLoad === void 0) { onLoad = null; }
  15692. if (onError === void 0) { onError = null; }
  15693. if (forcedExtension === void 0) { forcedExtension = null; }
  15694. if (createPolynomials === void 0) { createPolynomials = true; }
  15695. var callback = function (loadData) {
  15696. if (!loadData) {
  15697. if (onLoad) {
  15698. onLoad(null);
  15699. }
  15700. return;
  15701. }
  15702. var texture = loadData.texture;
  15703. if (!createPolynomials) {
  15704. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15705. }
  15706. else if (loadData.info.sphericalPolynomial) {
  15707. texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
  15708. }
  15709. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  15710. if (_this._caps.textureLOD) {
  15711. // Do not add extra process if texture lod is supported.
  15712. if (onLoad) {
  15713. onLoad(texture);
  15714. }
  15715. return;
  15716. }
  15717. var mipSlices = 3;
  15718. var gl = _this._gl;
  15719. var width = loadData.width;
  15720. if (!width) {
  15721. return;
  15722. }
  15723. var textures = [];
  15724. for (var i = 0; i < mipSlices; i++) {
  15725. //compute LOD from even spacing in smoothness (matching shader calculation)
  15726. var smoothness = i / (mipSlices - 1);
  15727. var roughness = 1 - smoothness;
  15728. var minLODIndex = lodOffset; // roughness = 0
  15729. var maxLODIndex = BABYLON.Scalar.Log2(width) * lodScale + lodOffset; // roughness = 1
  15730. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  15731. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  15732. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15733. glTextureFromLod.isCube = true;
  15734. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  15735. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15736. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15737. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15738. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15739. if (loadData.isDDS) {
  15740. var info = loadData.info;
  15741. var data = loadData.data;
  15742. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15743. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  15744. }
  15745. else {
  15746. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  15747. }
  15748. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15749. // Wrap in a base texture for easy binding.
  15750. var lodTexture = new BABYLON.BaseTexture(scene);
  15751. lodTexture.isCube = true;
  15752. lodTexture._texture = glTextureFromLod;
  15753. glTextureFromLod.isReady = true;
  15754. textures.push(lodTexture);
  15755. }
  15756. texture._lodTextureHigh = textures[2];
  15757. texture._lodTextureMid = textures[1];
  15758. texture._lodTextureLow = textures[0];
  15759. if (onLoad) {
  15760. onLoad(texture);
  15761. }
  15762. };
  15763. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset);
  15764. };
  15765. /**
  15766. * Creates a cube texture
  15767. * @param rootUrl defines the url where the files to load is located
  15768. * @param scene defines the current scene
  15769. * @param files defines the list of files to load (1 per face)
  15770. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  15771. * @param onLoad defines an optional callback raised when the texture is loaded
  15772. * @param onError defines an optional callback raised if there is an issue to load the texture
  15773. * @param format defines the format of the data
  15774. * @param forcedExtension defines the extension to use to pick the right loader
  15775. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  15776. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  15777. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  15778. * @returns the cube texture as an InternalTexture
  15779. */
  15780. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset) {
  15781. var _this = this;
  15782. if (onLoad === void 0) { onLoad = null; }
  15783. if (onError === void 0) { onError = null; }
  15784. if (forcedExtension === void 0) { forcedExtension = null; }
  15785. if (createPolynomials === void 0) { createPolynomials = false; }
  15786. if (lodScale === void 0) { lodScale = 0; }
  15787. if (lodOffset === void 0) { lodOffset = 0; }
  15788. var gl = this._gl;
  15789. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  15790. texture.isCube = true;
  15791. texture.url = rootUrl;
  15792. texture.generateMipMaps = !noMipmap;
  15793. texture._lodGenerationScale = lodScale;
  15794. texture._lodGenerationOffset = lodOffset;
  15795. if (!this._doNotHandleContextLost) {
  15796. texture._extension = forcedExtension;
  15797. texture._files = files;
  15798. }
  15799. var isKTX = false;
  15800. var isDDS = false;
  15801. var isEnv = false;
  15802. var lastDot = rootUrl.lastIndexOf('.');
  15803. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  15804. if (this._textureFormatInUse) {
  15805. extension = this._textureFormatInUse;
  15806. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  15807. isKTX = true;
  15808. }
  15809. else {
  15810. isDDS = (extension === ".dds");
  15811. isEnv = (extension === ".env");
  15812. }
  15813. var onerror = function (request, exception) {
  15814. if (onError && request) {
  15815. onError(request.status + " " + request.statusText, exception);
  15816. }
  15817. };
  15818. if (isKTX) {
  15819. this._loadFile(rootUrl, function (data) {
  15820. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  15821. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  15822. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15823. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  15824. ktx.uploadLevels(_this._gl, !noMipmap);
  15825. _this.setCubeMapTextureParams(gl, loadMipmap);
  15826. texture.width = ktx.pixelWidth;
  15827. texture.height = ktx.pixelHeight;
  15828. texture.isReady = true;
  15829. }, undefined, undefined, true, onerror);
  15830. }
  15831. else if (isEnv) {
  15832. this._loadFile(rootUrl, function (data) {
  15833. data = data;
  15834. var info = BABYLON.EnvironmentTextureTools.GetEnvInfo(data);
  15835. if (info) {
  15836. texture.width = info.width;
  15837. texture.height = info.width;
  15838. BABYLON.EnvironmentTextureTools.UploadPolynomials(texture, data, info);
  15839. BABYLON.EnvironmentTextureTools.UploadLevelsAsync(texture, data, info).then(function () {
  15840. texture.isReady = true;
  15841. if (onLoad) {
  15842. onLoad();
  15843. }
  15844. });
  15845. }
  15846. else if (onError) {
  15847. onError("Can not parse the environment file", null);
  15848. }
  15849. }, undefined, undefined, true, onerror);
  15850. }
  15851. else if (isDDS) {
  15852. if (files && files.length === 6) {
  15853. this._cascadeLoadFiles(scene, function (imgs) {
  15854. var info;
  15855. var loadMipmap = false;
  15856. var width = 0;
  15857. for (var index = 0; index < imgs.length; index++) {
  15858. var data = imgs[index];
  15859. info = BABYLON.DDSTools.GetDDSInfo(data);
  15860. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15861. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15862. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15863. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  15864. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15865. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15866. }
  15867. texture.width = info.width;
  15868. texture.height = info.height;
  15869. texture.type = info.textureType;
  15870. width = info.width;
  15871. }
  15872. _this.setCubeMapTextureParams(gl, loadMipmap);
  15873. texture.isReady = true;
  15874. if (onLoad) {
  15875. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  15876. }
  15877. }, files, onError);
  15878. }
  15879. else {
  15880. this._loadFile(rootUrl, function (data) {
  15881. var info = BABYLON.DDSTools.GetDDSInfo(data);
  15882. if (createPolynomials) {
  15883. info.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15884. }
  15885. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15886. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15887. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15888. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  15889. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15890. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15891. }
  15892. _this.setCubeMapTextureParams(gl, loadMipmap);
  15893. texture.width = info.width;
  15894. texture.height = info.height;
  15895. texture.isReady = true;
  15896. texture.type = info.textureType;
  15897. if (onLoad) {
  15898. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  15899. }
  15900. }, undefined, undefined, true, onerror);
  15901. }
  15902. }
  15903. else {
  15904. if (!files) {
  15905. throw new Error("Cannot load cubemap because files were not defined");
  15906. }
  15907. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  15908. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  15909. var height = width;
  15910. _this._prepareWorkingCanvas();
  15911. if (!_this._workingCanvas || !_this._workingContext) {
  15912. return;
  15913. }
  15914. _this._workingCanvas.width = width;
  15915. _this._workingCanvas.height = height;
  15916. var faces = [
  15917. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  15918. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  15919. ];
  15920. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15921. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  15922. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  15923. for (var index = 0; index < faces.length; index++) {
  15924. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  15925. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  15926. }
  15927. if (!noMipmap) {
  15928. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15929. }
  15930. _this.setCubeMapTextureParams(gl, !noMipmap);
  15931. texture.width = width;
  15932. texture.height = height;
  15933. texture.isReady = true;
  15934. if (format) {
  15935. texture.format = format;
  15936. }
  15937. texture.onLoadedObservable.notifyObservers(texture);
  15938. texture.onLoadedObservable.clear();
  15939. if (onLoad) {
  15940. onLoad();
  15941. }
  15942. }, files, onError);
  15943. }
  15944. this._internalTexturesCache.push(texture);
  15945. return texture;
  15946. };
  15947. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  15948. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15949. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  15950. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15951. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15952. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15953. // this.resetTextureCache();
  15954. };
  15955. /**
  15956. * Update a raw cube texture
  15957. * @param texture defines the texture to udpdate
  15958. * @param data defines the data to store
  15959. * @param format defines the data format
  15960. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15961. * @param invertY defines if data must be stored with Y axis inverted
  15962. * @param compression defines the compression used (null by default)
  15963. * @param level defines which level of the texture to update
  15964. */
  15965. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  15966. if (compression === void 0) { compression = null; }
  15967. if (level === void 0) { level = 0; }
  15968. texture._bufferViewArray = data;
  15969. texture.format = format;
  15970. texture.type = type;
  15971. texture.invertY = invertY;
  15972. texture._compression = compression;
  15973. var gl = this._gl;
  15974. var textureType = this._getWebGLTextureType(type);
  15975. var internalFormat = this._getInternalFormat(format);
  15976. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  15977. var needConversion = false;
  15978. if (internalFormat === gl.RGB) {
  15979. internalFormat = gl.RGBA;
  15980. needConversion = true;
  15981. }
  15982. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15983. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  15984. if (texture.width % 4 !== 0) {
  15985. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  15986. }
  15987. // Data are known to be in +X +Y +Z -X -Y -Z
  15988. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15989. var faceData = data[faceIndex];
  15990. if (compression) {
  15991. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  15992. }
  15993. else {
  15994. if (needConversion) {
  15995. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  15996. }
  15997. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  15998. }
  15999. }
  16000. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  16001. if (isPot && texture.generateMipMaps && level === 0) {
  16002. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  16003. }
  16004. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16005. // this.resetTextureCache();
  16006. texture.isReady = true;
  16007. };
  16008. /**
  16009. * Creates a new raw cube texture
  16010. * @param data defines the array of data to use to create each face
  16011. * @param size defines the size of the textures
  16012. * @param format defines the format of the data
  16013. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  16014. * @param generateMipMaps defines if the engine should generate the mip levels
  16015. * @param invertY defines if data must be stored with Y axis inverted
  16016. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16017. * @param compression defines the compression used (null by default)
  16018. * @returns the cube texture as an InternalTexture
  16019. */
  16020. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  16021. if (compression === void 0) { compression = null; }
  16022. var gl = this._gl;
  16023. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  16024. texture.isCube = true;
  16025. texture.generateMipMaps = generateMipMaps;
  16026. texture.format = format;
  16027. texture.type = type;
  16028. if (!this._doNotHandleContextLost) {
  16029. texture._bufferViewArray = data;
  16030. }
  16031. var textureType = this._getWebGLTextureType(type);
  16032. var internalFormat = this._getInternalFormat(format);
  16033. if (internalFormat === gl.RGB) {
  16034. internalFormat = gl.RGBA;
  16035. }
  16036. var width = size;
  16037. var height = width;
  16038. texture.width = width;
  16039. texture.height = height;
  16040. // Double check on POT to generate Mips.
  16041. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  16042. if (!isPot) {
  16043. generateMipMaps = false;
  16044. }
  16045. // Upload data if needed. The texture won't be ready until then.
  16046. if (data) {
  16047. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  16048. }
  16049. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  16050. // Filters
  16051. if (data && generateMipMaps) {
  16052. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  16053. }
  16054. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  16055. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  16056. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  16057. }
  16058. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  16059. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  16060. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  16061. }
  16062. else {
  16063. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  16064. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  16065. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  16066. }
  16067. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16068. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16069. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16070. return texture;
  16071. };
  16072. /**
  16073. * Creates a new raw cube texture from a specified url
  16074. * @param url defines the url where the data is located
  16075. * @param scene defines the current scene
  16076. * @param size defines the size of the textures
  16077. * @param format defines the format of the data
  16078. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  16079. * @param noMipmap defines if the engine should avoid generating the mip levels
  16080. * @param callback defines a callback used to extract texture data from loaded data
  16081. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  16082. * @param onLoad defines a callback called when texture is loaded
  16083. * @param onError defines a callback called if there is an error
  16084. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16085. * @param invertY defines if data must be stored with Y axis inverted
  16086. * @returns the cube texture as an InternalTexture
  16087. */
  16088. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  16089. var _this = this;
  16090. if (onLoad === void 0) { onLoad = null; }
  16091. if (onError === void 0) { onError = null; }
  16092. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  16093. if (invertY === void 0) { invertY = false; }
  16094. var gl = this._gl;
  16095. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  16096. scene._addPendingData(texture);
  16097. texture.url = url;
  16098. this._internalTexturesCache.push(texture);
  16099. var onerror = function (request, exception) {
  16100. scene._removePendingData(texture);
  16101. if (onError && request) {
  16102. onError(request.status + " " + request.statusText, exception);
  16103. }
  16104. };
  16105. var internalCallback = function (data) {
  16106. var width = texture.width;
  16107. var faceDataArrays = callback(data);
  16108. if (!faceDataArrays) {
  16109. return;
  16110. }
  16111. if (mipmapGenerator) {
  16112. var textureType = _this._getWebGLTextureType(type);
  16113. var internalFormat = _this._getInternalFormat(format);
  16114. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  16115. var needConversion = false;
  16116. if (internalFormat === gl.RGB) {
  16117. internalFormat = gl.RGBA;
  16118. needConversion = true;
  16119. }
  16120. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16121. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  16122. var mipData = mipmapGenerator(faceDataArrays);
  16123. for (var level = 0; level < mipData.length; level++) {
  16124. var mipSize = width >> level;
  16125. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  16126. var mipFaceData = mipData[level][faceIndex];
  16127. if (needConversion) {
  16128. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  16129. }
  16130. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  16131. }
  16132. }
  16133. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16134. }
  16135. else {
  16136. texture.generateMipMaps = !noMipmap;
  16137. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  16138. }
  16139. texture.isReady = true;
  16140. // this.resetTextureCache();
  16141. scene._removePendingData(texture);
  16142. if (onLoad) {
  16143. onLoad();
  16144. }
  16145. };
  16146. this._loadFile(url, function (data) {
  16147. internalCallback(data);
  16148. }, undefined, scene.database, true, onerror);
  16149. return texture;
  16150. };
  16151. ;
  16152. /**
  16153. * Update a raw 3D texture
  16154. * @param texture defines the texture to update
  16155. * @param data defines the data to store
  16156. * @param format defines the data format
  16157. * @param invertY defines if data must be stored with Y axis inverted
  16158. * @param compression defines the used compression (can be null)
  16159. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  16160. */
  16161. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression, textureType) {
  16162. if (compression === void 0) { compression = null; }
  16163. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16164. var internalType = this._getWebGLTextureType(textureType);
  16165. var internalFormat = this._getInternalFormat(format);
  16166. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(textureType, format);
  16167. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16168. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  16169. if (!this._doNotHandleContextLost) {
  16170. texture._bufferView = data;
  16171. texture.format = format;
  16172. texture.invertY = invertY;
  16173. texture._compression = compression;
  16174. }
  16175. if (texture.width % 4 !== 0) {
  16176. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  16177. }
  16178. if (compression && data) {
  16179. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  16180. }
  16181. else {
  16182. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalSizedFomat, texture.width, texture.height, texture.depth, 0, internalFormat, internalType, data);
  16183. }
  16184. if (texture.generateMipMaps) {
  16185. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16186. }
  16187. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16188. // this.resetTextureCache();
  16189. texture.isReady = true;
  16190. };
  16191. /**
  16192. * Creates a new raw 3D texture
  16193. * @param data defines the data used to create the texture
  16194. * @param width defines the width of the texture
  16195. * @param height defines the height of the texture
  16196. * @param depth defines the depth of the texture
  16197. * @param format defines the format of the texture
  16198. * @param generateMipMaps defines if the engine must generate mip levels
  16199. * @param invertY defines if data must be stored with Y axis inverted
  16200. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16201. * @param compression defines the compressed used (can be null)
  16202. * @param textureType defines the compressed used (can be null)
  16203. * @returns a new raw 3D texture (stored in an InternalTexture)
  16204. */
  16205. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression, textureType) {
  16206. if (compression === void 0) { compression = null; }
  16207. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16208. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  16209. texture.baseWidth = width;
  16210. texture.baseHeight = height;
  16211. texture.baseDepth = depth;
  16212. texture.width = width;
  16213. texture.height = height;
  16214. texture.depth = depth;
  16215. texture.format = format;
  16216. texture.type = textureType;
  16217. texture.generateMipMaps = generateMipMaps;
  16218. texture.samplingMode = samplingMode;
  16219. texture.is3D = true;
  16220. if (!this._doNotHandleContextLost) {
  16221. texture._bufferView = data;
  16222. }
  16223. this.updateRawTexture3D(texture, data, format, invertY, compression, textureType);
  16224. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16225. // Filters
  16226. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  16227. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  16228. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  16229. if (generateMipMaps) {
  16230. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16231. }
  16232. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16233. this._internalTexturesCache.push(texture);
  16234. return texture;
  16235. };
  16236. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  16237. var gl = this._gl;
  16238. if (!gl) {
  16239. return;
  16240. }
  16241. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  16242. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  16243. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  16244. if (!noMipmap && !isCompressed) {
  16245. gl.generateMipmap(gl.TEXTURE_2D);
  16246. }
  16247. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  16248. // this.resetTextureCache();
  16249. if (scene) {
  16250. scene._removePendingData(texture);
  16251. }
  16252. texture.onLoadedObservable.notifyObservers(texture);
  16253. texture.onLoadedObservable.clear();
  16254. };
  16255. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  16256. var _this = this;
  16257. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  16258. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  16259. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  16260. var gl = this._gl;
  16261. if (!gl) {
  16262. return;
  16263. }
  16264. if (!texture._webGLTexture) {
  16265. // this.resetTextureCache();
  16266. if (scene) {
  16267. scene._removePendingData(texture);
  16268. }
  16269. return;
  16270. }
  16271. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  16272. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  16273. texture.baseWidth = width;
  16274. texture.baseHeight = height;
  16275. texture.width = potWidth;
  16276. texture.height = potHeight;
  16277. texture.isReady = true;
  16278. if (processFunction(potWidth, potHeight, function () {
  16279. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16280. })) {
  16281. // Returning as texture needs extra async steps
  16282. return;
  16283. }
  16284. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16285. };
  16286. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  16287. // Create new RGBA data container.
  16288. var rgbaData;
  16289. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  16290. rgbaData = new Float32Array(width * height * 4);
  16291. }
  16292. else {
  16293. rgbaData = new Uint32Array(width * height * 4);
  16294. }
  16295. // Convert each pixel.
  16296. for (var x = 0; x < width; x++) {
  16297. for (var y = 0; y < height; y++) {
  16298. var index = (y * width + x) * 3;
  16299. var newIndex = (y * width + x) * 4;
  16300. // Map Old Value to new value.
  16301. rgbaData[newIndex + 0] = rgbData[index + 0];
  16302. rgbaData[newIndex + 1] = rgbData[index + 1];
  16303. rgbaData[newIndex + 2] = rgbData[index + 2];
  16304. // Add fully opaque alpha channel.
  16305. rgbaData[newIndex + 3] = 1;
  16306. }
  16307. }
  16308. return rgbaData;
  16309. };
  16310. /** @hidden */
  16311. Engine.prototype._releaseFramebufferObjects = function (texture) {
  16312. var gl = this._gl;
  16313. if (texture._framebuffer) {
  16314. gl.deleteFramebuffer(texture._framebuffer);
  16315. texture._framebuffer = null;
  16316. }
  16317. if (texture._depthStencilBuffer) {
  16318. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  16319. texture._depthStencilBuffer = null;
  16320. }
  16321. if (texture._MSAAFramebuffer) {
  16322. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  16323. texture._MSAAFramebuffer = null;
  16324. }
  16325. if (texture._MSAARenderBuffer) {
  16326. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  16327. texture._MSAARenderBuffer = null;
  16328. }
  16329. };
  16330. /** @hidden */
  16331. Engine.prototype._releaseTexture = function (texture) {
  16332. var gl = this._gl;
  16333. this._releaseFramebufferObjects(texture);
  16334. gl.deleteTexture(texture._webGLTexture);
  16335. // Unbind channels
  16336. this.unbindAllTextures();
  16337. var index = this._internalTexturesCache.indexOf(texture);
  16338. if (index !== -1) {
  16339. this._internalTexturesCache.splice(index, 1);
  16340. }
  16341. // Integrated fixed lod samplers.
  16342. if (texture._lodTextureHigh) {
  16343. texture._lodTextureHigh.dispose();
  16344. }
  16345. if (texture._lodTextureMid) {
  16346. texture._lodTextureMid.dispose();
  16347. }
  16348. if (texture._lodTextureLow) {
  16349. texture._lodTextureLow.dispose();
  16350. }
  16351. // Set output texture of post process to null if the texture has been released/disposed
  16352. this.scenes.forEach(function (scene) {
  16353. scene.postProcesses.forEach(function (postProcess) {
  16354. if (postProcess._outputTexture == texture) {
  16355. postProcess._outputTexture = null;
  16356. }
  16357. });
  16358. scene.cameras.forEach(function (camera) {
  16359. camera._postProcesses.forEach(function (postProcess) {
  16360. if (postProcess) {
  16361. if (postProcess._outputTexture == texture) {
  16362. postProcess._outputTexture = null;
  16363. }
  16364. }
  16365. });
  16366. });
  16367. });
  16368. };
  16369. Engine.prototype.setProgram = function (program) {
  16370. if (this._currentProgram !== program) {
  16371. this._gl.useProgram(program);
  16372. this._currentProgram = program;
  16373. }
  16374. };
  16375. /**
  16376. * Binds an effect to the webGL context
  16377. * @param effect defines the effect to bind
  16378. */
  16379. Engine.prototype.bindSamplers = function (effect) {
  16380. this.setProgram(effect.getProgram());
  16381. var samplers = effect.getSamplers();
  16382. for (var index = 0; index < samplers.length; index++) {
  16383. var uniform = effect.getUniform(samplers[index]);
  16384. if (uniform) {
  16385. this._boundUniforms[index] = uniform;
  16386. }
  16387. }
  16388. this._currentEffect = null;
  16389. };
  16390. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  16391. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  16392. return;
  16393. }
  16394. // Remove
  16395. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16396. // Bind last to it
  16397. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  16398. // Bind to dummy
  16399. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  16400. };
  16401. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  16402. if (!internalTexture) {
  16403. return -1;
  16404. }
  16405. internalTexture._initialSlot = channel;
  16406. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  16407. if (channel !== internalTexture._designatedSlot) {
  16408. this._textureCollisions.addCount(1, false);
  16409. }
  16410. }
  16411. else {
  16412. if (channel !== internalTexture._designatedSlot) {
  16413. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  16414. return internalTexture._designatedSlot;
  16415. }
  16416. else {
  16417. // No slot for this texture, let's pick a new one (if we find a free slot)
  16418. if (this._nextFreeTextureSlots.length) {
  16419. return this._nextFreeTextureSlots[0];
  16420. }
  16421. // We need to recycle the oldest bound texture, sorry.
  16422. this._textureCollisions.addCount(1, false);
  16423. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  16424. }
  16425. }
  16426. }
  16427. return channel;
  16428. };
  16429. Engine.prototype._linkTrackers = function (previous, next) {
  16430. previous.next = next;
  16431. next.previous = previous;
  16432. };
  16433. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  16434. var currentSlot = internalTexture._designatedSlot;
  16435. if (currentSlot === -1) {
  16436. return -1;
  16437. }
  16438. internalTexture._designatedSlot = -1;
  16439. if (this.disableTextureBindingOptimization) {
  16440. return -1;
  16441. }
  16442. // Remove from bound list
  16443. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16444. // Free the slot
  16445. this._boundTexturesCache[currentSlot] = null;
  16446. this._nextFreeTextureSlots.push(currentSlot);
  16447. return currentSlot;
  16448. };
  16449. Engine.prototype._activateCurrentTexture = function () {
  16450. if (this._currentTextureChannel !== this._activeChannel) {
  16451. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  16452. this._currentTextureChannel = this._activeChannel;
  16453. }
  16454. };
  16455. /** @hidden */
  16456. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
  16457. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  16458. if (force === void 0) { force = false; }
  16459. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  16460. this._activeChannel = texture._designatedSlot;
  16461. }
  16462. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  16463. var isTextureForRendering = texture && texture._initialSlot > -1;
  16464. if (currentTextureBound !== texture || force) {
  16465. if (currentTextureBound) {
  16466. this._removeDesignatedSlot(currentTextureBound);
  16467. }
  16468. this._activateCurrentTexture();
  16469. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  16470. this._boundTexturesCache[this._activeChannel] = texture;
  16471. if (texture) {
  16472. if (!this.disableTextureBindingOptimization) {
  16473. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  16474. if (slotIndex > -1) {
  16475. this._nextFreeTextureSlots.splice(slotIndex, 1);
  16476. }
  16477. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  16478. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  16479. }
  16480. texture._designatedSlot = this._activeChannel;
  16481. }
  16482. }
  16483. else if (forTextureDataUpdate) {
  16484. this._activateCurrentTexture();
  16485. }
  16486. if (isTextureForRendering && !forTextureDataUpdate) {
  16487. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  16488. }
  16489. };
  16490. /** @hidden */
  16491. Engine.prototype._bindTexture = function (channel, texture) {
  16492. if (channel < 0) {
  16493. return;
  16494. }
  16495. if (texture) {
  16496. channel = this._getCorrectTextureChannel(channel, texture);
  16497. }
  16498. this._activeChannel = channel;
  16499. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  16500. };
  16501. /**
  16502. * Sets a texture to the webGL context from a postprocess
  16503. * @param channel defines the channel to use
  16504. * @param postProcess defines the source postprocess
  16505. */
  16506. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  16507. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  16508. };
  16509. /**
  16510. * Binds the output of the passed in post process to the texture channel specified
  16511. * @param channel The channel the texture should be bound to
  16512. * @param postProcess The post process which's output should be bound
  16513. */
  16514. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  16515. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  16516. };
  16517. /**
  16518. * Unbind all textures from the webGL context
  16519. */
  16520. Engine.prototype.unbindAllTextures = function () {
  16521. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  16522. this._activeChannel = channel;
  16523. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16524. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16525. if (this.webGLVersion > 1) {
  16526. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16527. }
  16528. }
  16529. };
  16530. /**
  16531. * Sets a texture to the according uniform.
  16532. * @param channel The texture channel
  16533. * @param uniform The uniform to set
  16534. * @param texture The texture to apply
  16535. */
  16536. Engine.prototype.setTexture = function (channel, uniform, texture) {
  16537. if (channel < 0) {
  16538. return;
  16539. }
  16540. if (uniform) {
  16541. this._boundUniforms[channel] = uniform;
  16542. }
  16543. this._setTexture(channel, texture);
  16544. };
  16545. /**
  16546. * Sets a depth stencil texture from a render target to the according uniform.
  16547. * @param channel The texture channel
  16548. * @param uniform The uniform to set
  16549. * @param texture The render target texture containing the depth stencil texture to apply
  16550. */
  16551. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  16552. if (channel < 0) {
  16553. return;
  16554. }
  16555. if (uniform) {
  16556. this._boundUniforms[channel] = uniform;
  16557. }
  16558. if (!texture || !texture.depthStencilTexture) {
  16559. this._setTexture(channel, null);
  16560. }
  16561. else {
  16562. this._setTexture(channel, texture, false, true);
  16563. }
  16564. };
  16565. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  16566. var uniform = this._boundUniforms[sourceSlot];
  16567. if (uniform._currentState === destination) {
  16568. return;
  16569. }
  16570. this._gl.uniform1i(uniform, destination);
  16571. uniform._currentState = destination;
  16572. };
  16573. Engine.prototype._getTextureWrapMode = function (mode) {
  16574. switch (mode) {
  16575. case BABYLON.Texture.WRAP_ADDRESSMODE:
  16576. return this._gl.REPEAT;
  16577. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  16578. return this._gl.CLAMP_TO_EDGE;
  16579. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  16580. return this._gl.MIRRORED_REPEAT;
  16581. }
  16582. return this._gl.REPEAT;
  16583. };
  16584. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  16585. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  16586. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  16587. // Not ready?
  16588. if (!texture) {
  16589. if (this._boundTexturesCache[channel] != null) {
  16590. this._activeChannel = channel;
  16591. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16592. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16593. if (this.webGLVersion > 1) {
  16594. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16595. }
  16596. }
  16597. return false;
  16598. }
  16599. // Video
  16600. if (texture.video) {
  16601. this._activeChannel = channel;
  16602. texture.update();
  16603. }
  16604. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  16605. texture.delayLoad();
  16606. return false;
  16607. }
  16608. var internalTexture;
  16609. if (depthStencilTexture) {
  16610. internalTexture = texture.depthStencilTexture;
  16611. }
  16612. else if (texture.isReady()) {
  16613. internalTexture = texture.getInternalTexture();
  16614. }
  16615. else if (texture.isCube) {
  16616. internalTexture = this.emptyCubeTexture;
  16617. }
  16618. else if (texture.is3D) {
  16619. internalTexture = this.emptyTexture3D;
  16620. }
  16621. else {
  16622. internalTexture = this.emptyTexture;
  16623. }
  16624. if (!isPartOfTextureArray) {
  16625. channel = this._getCorrectTextureChannel(channel, internalTexture);
  16626. }
  16627. var needToBind = true;
  16628. if (this._boundTexturesCache[channel] === internalTexture) {
  16629. this._moveBoundTextureOnTop(internalTexture);
  16630. if (!isPartOfTextureArray) {
  16631. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  16632. }
  16633. needToBind = false;
  16634. }
  16635. this._activeChannel = channel;
  16636. if (internalTexture && internalTexture.is3D) {
  16637. if (needToBind) {
  16638. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  16639. }
  16640. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16641. internalTexture._cachedWrapU = texture.wrapU;
  16642. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16643. }
  16644. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16645. internalTexture._cachedWrapV = texture.wrapV;
  16646. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16647. }
  16648. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  16649. internalTexture._cachedWrapR = texture.wrapR;
  16650. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  16651. }
  16652. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  16653. }
  16654. else if (internalTexture && internalTexture.isCube) {
  16655. if (needToBind) {
  16656. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  16657. }
  16658. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  16659. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  16660. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  16661. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  16662. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  16663. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  16664. }
  16665. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  16666. }
  16667. else {
  16668. if (needToBind) {
  16669. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  16670. }
  16671. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16672. internalTexture._cachedWrapU = texture.wrapU;
  16673. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16674. }
  16675. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16676. internalTexture._cachedWrapV = texture.wrapV;
  16677. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16678. }
  16679. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  16680. }
  16681. return true;
  16682. };
  16683. /**
  16684. * Sets an array of texture to the webGL context
  16685. * @param channel defines the channel where the texture array must be set
  16686. * @param uniform defines the associated uniform location
  16687. * @param textures defines the array of textures to bind
  16688. */
  16689. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  16690. if (channel < 0 || !uniform) {
  16691. return;
  16692. }
  16693. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  16694. this._textureUnits = new Int32Array(textures.length);
  16695. }
  16696. for (var i = 0; i < textures.length; i++) {
  16697. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  16698. }
  16699. this._gl.uniform1iv(uniform, this._textureUnits);
  16700. for (var index = 0; index < textures.length; index++) {
  16701. this._setTexture(this._textureUnits[index], textures[index], true);
  16702. }
  16703. };
  16704. /** @hidden */
  16705. Engine.prototype._setAnisotropicLevel = function (target, texture) {
  16706. var internalTexture = texture.getInternalTexture();
  16707. if (!internalTexture) {
  16708. return;
  16709. }
  16710. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  16711. var value = texture.anisotropicFilteringLevel;
  16712. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  16713. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  16714. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  16715. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  16716. }
  16717. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  16718. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  16719. internalTexture._cachedAnisotropicFilteringLevel = value;
  16720. }
  16721. };
  16722. Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
  16723. this._bindTextureDirectly(target, texture, true, true);
  16724. this._gl.texParameterf(target, parameter, value);
  16725. };
  16726. Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
  16727. if (texture) {
  16728. this._bindTextureDirectly(target, texture, true, true);
  16729. }
  16730. this._gl.texParameteri(target, parameter, value);
  16731. };
  16732. /**
  16733. * Reads pixels from the current frame buffer. Please note that this function can be slow
  16734. * @param x defines the x coordinate of the rectangle where pixels must be read
  16735. * @param y defines the y coordinate of the rectangle where pixels must be read
  16736. * @param width defines the width of the rectangle where pixels must be read
  16737. * @param height defines the height of the rectangle where pixels must be read
  16738. * @returns a Uint8Array containing RGBA colors
  16739. */
  16740. Engine.prototype.readPixels = function (x, y, width, height) {
  16741. var data = new Uint8Array(height * width * 4);
  16742. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  16743. return data;
  16744. };
  16745. /**
  16746. * Add an externaly attached data from its key.
  16747. * This method call will fail and return false, if such key already exists.
  16748. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  16749. * @param key the unique key that identifies the data
  16750. * @param data the data object to associate to the key for this Engine instance
  16751. * @return true if no such key were already present and the data was added successfully, false otherwise
  16752. */
  16753. Engine.prototype.addExternalData = function (key, data) {
  16754. if (!this._externalData) {
  16755. this._externalData = new BABYLON.StringDictionary();
  16756. }
  16757. return this._externalData.add(key, data);
  16758. };
  16759. /**
  16760. * Get an externaly attached data from its key
  16761. * @param key the unique key that identifies the data
  16762. * @return the associated data, if present (can be null), or undefined if not present
  16763. */
  16764. Engine.prototype.getExternalData = function (key) {
  16765. if (!this._externalData) {
  16766. this._externalData = new BABYLON.StringDictionary();
  16767. }
  16768. return this._externalData.get(key);
  16769. };
  16770. /**
  16771. * Get an externaly attached data from its key, create it using a factory if it's not already present
  16772. * @param key the unique key that identifies the data
  16773. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  16774. * @return the associated data, can be null if the factory returned null.
  16775. */
  16776. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  16777. if (!this._externalData) {
  16778. this._externalData = new BABYLON.StringDictionary();
  16779. }
  16780. return this._externalData.getOrAddWithFactory(key, factory);
  16781. };
  16782. /**
  16783. * Remove an externaly attached data from the Engine instance
  16784. * @param key the unique key that identifies the data
  16785. * @return true if the data was successfully removed, false if it doesn't exist
  16786. */
  16787. Engine.prototype.removeExternalData = function (key) {
  16788. if (!this._externalData) {
  16789. this._externalData = new BABYLON.StringDictionary();
  16790. }
  16791. return this._externalData.remove(key);
  16792. };
  16793. /**
  16794. * Unbind all vertex attributes from the webGL context
  16795. */
  16796. Engine.prototype.unbindAllAttributes = function () {
  16797. if (this._mustWipeVertexAttributes) {
  16798. this._mustWipeVertexAttributes = false;
  16799. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  16800. this._gl.disableVertexAttribArray(i);
  16801. this._vertexAttribArraysEnabled[i] = false;
  16802. this._currentBufferPointers[i].active = false;
  16803. }
  16804. return;
  16805. }
  16806. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  16807. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  16808. continue;
  16809. }
  16810. this._gl.disableVertexAttribArray(i);
  16811. this._vertexAttribArraysEnabled[i] = false;
  16812. this._currentBufferPointers[i].active = false;
  16813. }
  16814. };
  16815. /**
  16816. * 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
  16817. */
  16818. Engine.prototype.releaseEffects = function () {
  16819. for (var name in this._compiledEffects) {
  16820. this._deleteProgram(this._compiledEffects[name]._program);
  16821. }
  16822. this._compiledEffects = {};
  16823. };
  16824. /**
  16825. * Dispose and release all associated resources
  16826. */
  16827. Engine.prototype.dispose = function () {
  16828. this.hideLoadingUI();
  16829. this.stopRenderLoop();
  16830. // Release postProcesses
  16831. while (this.postProcesses.length) {
  16832. this.postProcesses[0].dispose();
  16833. }
  16834. // Empty texture
  16835. if (this._emptyTexture) {
  16836. this._releaseTexture(this._emptyTexture);
  16837. this._emptyTexture = null;
  16838. }
  16839. if (this._emptyCubeTexture) {
  16840. this._releaseTexture(this._emptyCubeTexture);
  16841. this._emptyCubeTexture = null;
  16842. }
  16843. // Rescale PP
  16844. if (this._rescalePostProcess) {
  16845. this._rescalePostProcess.dispose();
  16846. }
  16847. // Release scenes
  16848. while (this.scenes.length) {
  16849. this.scenes[0].dispose();
  16850. }
  16851. // Release audio engine
  16852. if (Engine.audioEngine) {
  16853. Engine.audioEngine.dispose();
  16854. }
  16855. // Release effects
  16856. this.releaseEffects();
  16857. // Unbind
  16858. this.unbindAllAttributes();
  16859. this._boundUniforms = [];
  16860. if (this._dummyFramebuffer) {
  16861. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  16862. }
  16863. //WebVR
  16864. this.disableVR();
  16865. // Events
  16866. if (BABYLON.Tools.IsWindowObjectExist()) {
  16867. window.removeEventListener("blur", this._onBlur);
  16868. window.removeEventListener("focus", this._onFocus);
  16869. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  16870. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  16871. if (this._renderingCanvas) {
  16872. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  16873. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  16874. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  16875. if (!this._doNotHandleContextLost) {
  16876. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  16877. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  16878. }
  16879. }
  16880. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  16881. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  16882. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  16883. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  16884. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  16885. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  16886. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  16887. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  16888. if (this._onVrDisplayConnect) {
  16889. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  16890. if (this._onVrDisplayDisconnect) {
  16891. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  16892. }
  16893. if (this._onVrDisplayPresentChange) {
  16894. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  16895. }
  16896. this._onVrDisplayConnect = null;
  16897. this._onVrDisplayDisconnect = null;
  16898. }
  16899. }
  16900. // Remove from Instances
  16901. var index = Engine.Instances.indexOf(this);
  16902. if (index >= 0) {
  16903. Engine.Instances.splice(index, 1);
  16904. }
  16905. this._workingCanvas = null;
  16906. this._workingContext = null;
  16907. this._currentBufferPointers = [];
  16908. this._renderingCanvas = null;
  16909. this._currentProgram = null;
  16910. this._bindedRenderFunction = null;
  16911. this.onResizeObservable.clear();
  16912. this.onCanvasBlurObservable.clear();
  16913. this.onCanvasFocusObservable.clear();
  16914. this.onCanvasPointerOutObservable.clear();
  16915. this.onBeginFrameObservable.clear();
  16916. this.onEndFrameObservable.clear();
  16917. BABYLON.Effect.ResetCache();
  16918. // Abort active requests
  16919. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  16920. var request = _a[_i];
  16921. request.abort();
  16922. }
  16923. };
  16924. // Loading screen
  16925. /**
  16926. * Display the loading screen
  16927. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16928. */
  16929. Engine.prototype.displayLoadingUI = function () {
  16930. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16931. return;
  16932. }
  16933. var loadingScreen = this.loadingScreen;
  16934. if (loadingScreen) {
  16935. loadingScreen.displayLoadingUI();
  16936. }
  16937. };
  16938. /**
  16939. * Hide the loading screen
  16940. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16941. */
  16942. Engine.prototype.hideLoadingUI = function () {
  16943. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16944. return;
  16945. }
  16946. var loadingScreen = this.loadingScreen;
  16947. if (loadingScreen) {
  16948. loadingScreen.hideLoadingUI();
  16949. }
  16950. };
  16951. Object.defineProperty(Engine.prototype, "loadingScreen", {
  16952. /**
  16953. * Gets the current loading screen object
  16954. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16955. */
  16956. get: function () {
  16957. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  16958. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  16959. return this._loadingScreen;
  16960. },
  16961. /**
  16962. * Sets the current loading screen object
  16963. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16964. */
  16965. set: function (loadingScreen) {
  16966. this._loadingScreen = loadingScreen;
  16967. },
  16968. enumerable: true,
  16969. configurable: true
  16970. });
  16971. Object.defineProperty(Engine.prototype, "loadingUIText", {
  16972. /**
  16973. * Sets the current loading screen text
  16974. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16975. */
  16976. set: function (text) {
  16977. this.loadingScreen.loadingUIText = text;
  16978. },
  16979. enumerable: true,
  16980. configurable: true
  16981. });
  16982. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  16983. /**
  16984. * Sets the current loading screen background color
  16985. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16986. */
  16987. set: function (color) {
  16988. this.loadingScreen.loadingUIBackgroundColor = color;
  16989. },
  16990. enumerable: true,
  16991. configurable: true
  16992. });
  16993. /**
  16994. * Attach a new callback raised when context lost event is fired
  16995. * @param callback defines the callback to call
  16996. */
  16997. Engine.prototype.attachContextLostEvent = function (callback) {
  16998. if (this._renderingCanvas) {
  16999. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  17000. }
  17001. };
  17002. /**
  17003. * Attach a new callback raised when context restored event is fired
  17004. * @param callback defines the callback to call
  17005. */
  17006. Engine.prototype.attachContextRestoredEvent = function (callback) {
  17007. if (this._renderingCanvas) {
  17008. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  17009. }
  17010. };
  17011. /**
  17012. * Gets the source code of the vertex shader associated with a specific webGL program
  17013. * @param program defines the program to use
  17014. * @returns a string containing the source code of the vertex shader associated with the program
  17015. */
  17016. Engine.prototype.getVertexShaderSource = function (program) {
  17017. var shaders = this._gl.getAttachedShaders(program);
  17018. if (!shaders) {
  17019. return null;
  17020. }
  17021. return this._gl.getShaderSource(shaders[0]);
  17022. };
  17023. /**
  17024. * Gets the source code of the fragment shader associated with a specific webGL program
  17025. * @param program defines the program to use
  17026. * @returns a string containing the source code of the fragment shader associated with the program
  17027. */
  17028. Engine.prototype.getFragmentShaderSource = function (program) {
  17029. var shaders = this._gl.getAttachedShaders(program);
  17030. if (!shaders) {
  17031. return null;
  17032. }
  17033. return this._gl.getShaderSource(shaders[1]);
  17034. };
  17035. /**
  17036. * Get the current error code of the webGL context
  17037. * @returns the error code
  17038. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  17039. */
  17040. Engine.prototype.getError = function () {
  17041. return this._gl.getError();
  17042. };
  17043. // FPS
  17044. /**
  17045. * Gets the current framerate
  17046. * @returns a number representing the framerate
  17047. */
  17048. Engine.prototype.getFps = function () {
  17049. return this._fps;
  17050. };
  17051. /**
  17052. * Gets the time spent between current and previous frame
  17053. * @returns a number representing the delta time in ms
  17054. */
  17055. Engine.prototype.getDeltaTime = function () {
  17056. return this._deltaTime;
  17057. };
  17058. Engine.prototype._measureFps = function () {
  17059. this._performanceMonitor.sampleFrame();
  17060. this._fps = this._performanceMonitor.averageFPS;
  17061. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  17062. };
  17063. /** @hidden */
  17064. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex, level) {
  17065. if (faceIndex === void 0) { faceIndex = -1; }
  17066. if (level === void 0) { level = 0; }
  17067. var gl = this._gl;
  17068. if (!this._dummyFramebuffer) {
  17069. var dummy = gl.createFramebuffer();
  17070. if (!dummy) {
  17071. throw new Error("Unable to create dummy framebuffer");
  17072. }
  17073. this._dummyFramebuffer = dummy;
  17074. }
  17075. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  17076. if (faceIndex > -1) {
  17077. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, level);
  17078. }
  17079. else {
  17080. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, level);
  17081. }
  17082. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  17083. var buffer;
  17084. switch (readType) {
  17085. case gl.UNSIGNED_BYTE:
  17086. buffer = new Uint8Array(4 * width * height);
  17087. readType = gl.UNSIGNED_BYTE;
  17088. break;
  17089. default:
  17090. buffer = new Float32Array(4 * width * height);
  17091. readType = gl.FLOAT;
  17092. break;
  17093. }
  17094. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  17095. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  17096. return buffer;
  17097. };
  17098. Engine.prototype._canRenderToFloatFramebuffer = function () {
  17099. if (this._webGLVersion > 1) {
  17100. return this._caps.colorBufferFloat;
  17101. }
  17102. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  17103. };
  17104. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  17105. if (this._webGLVersion > 1) {
  17106. return this._caps.colorBufferFloat;
  17107. }
  17108. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  17109. };
  17110. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  17111. Engine.prototype._canRenderToFramebuffer = function (type) {
  17112. var gl = this._gl;
  17113. //clear existing errors
  17114. while (gl.getError() !== gl.NO_ERROR) { }
  17115. var successful = true;
  17116. var texture = gl.createTexture();
  17117. gl.bindTexture(gl.TEXTURE_2D, texture);
  17118. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  17119. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  17120. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  17121. var fb = gl.createFramebuffer();
  17122. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  17123. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  17124. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  17125. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  17126. successful = successful && (gl.getError() === gl.NO_ERROR);
  17127. //try render by clearing frame buffer's color buffer
  17128. if (successful) {
  17129. gl.clear(gl.COLOR_BUFFER_BIT);
  17130. successful = successful && (gl.getError() === gl.NO_ERROR);
  17131. }
  17132. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  17133. if (successful) {
  17134. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  17135. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17136. var readFormat = gl.RGBA;
  17137. var readType = gl.UNSIGNED_BYTE;
  17138. var buffer = new Uint8Array(4);
  17139. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  17140. successful = successful && (gl.getError() === gl.NO_ERROR);
  17141. }
  17142. //clean up
  17143. gl.deleteTexture(texture);
  17144. gl.deleteFramebuffer(fb);
  17145. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17146. //clear accumulated errors
  17147. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  17148. return successful;
  17149. };
  17150. /** @hidden */
  17151. Engine.prototype._getWebGLTextureType = function (type) {
  17152. if (type === Engine.TEXTURETYPE_FLOAT) {
  17153. return this._gl.FLOAT;
  17154. }
  17155. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17156. // Add Half Float Constant.
  17157. return this._gl.HALF_FLOAT_OES;
  17158. }
  17159. return this._gl.UNSIGNED_BYTE;
  17160. };
  17161. ;
  17162. Engine.prototype._getInternalFormat = function (format) {
  17163. var internalFormat = this._gl.RGBA;
  17164. switch (format) {
  17165. case Engine.TEXTUREFORMAT_ALPHA:
  17166. internalFormat = this._gl.ALPHA;
  17167. break;
  17168. case Engine.TEXTUREFORMAT_LUMINANCE:
  17169. internalFormat = this._gl.LUMINANCE;
  17170. break;
  17171. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  17172. internalFormat = this._gl.LUMINANCE_ALPHA;
  17173. break;
  17174. case Engine.TEXTUREFORMAT_RGB:
  17175. internalFormat = this._gl.RGB;
  17176. break;
  17177. case Engine.TEXTUREFORMAT_RGBA:
  17178. internalFormat = this._gl.RGBA;
  17179. break;
  17180. case Engine.TEXTUREFORMAT_R:
  17181. internalFormat = this._gl.RED;
  17182. break;
  17183. case Engine.TEXTUREFORMAT_RG:
  17184. internalFormat = this._gl.RG;
  17185. break;
  17186. }
  17187. return internalFormat;
  17188. };
  17189. /** @hidden */
  17190. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  17191. if (this._webGLVersion === 1) {
  17192. if (format !== undefined) {
  17193. switch (format) {
  17194. case Engine.TEXTUREFORMAT_LUMINANCE:
  17195. return this._gl.LUMINANCE;
  17196. case Engine.TEXTUREFORMAT_ALPHA:
  17197. return this._gl.ALPHA;
  17198. }
  17199. }
  17200. return this._gl.RGBA;
  17201. }
  17202. if (type === Engine.TEXTURETYPE_FLOAT) {
  17203. if (format !== undefined) {
  17204. switch (format) {
  17205. case Engine.TEXTUREFORMAT_R:
  17206. return this._gl.R32F;
  17207. case Engine.TEXTUREFORMAT_RG:
  17208. return this._gl.RG32F;
  17209. case Engine.TEXTUREFORMAT_RGB:
  17210. return this._gl.RGB32F;
  17211. }
  17212. }
  17213. return this._gl.RGBA32F;
  17214. }
  17215. if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17216. if (format) {
  17217. switch (format) {
  17218. case Engine.TEXTUREFORMAT_R:
  17219. return this._gl.R16F;
  17220. case Engine.TEXTUREFORMAT_RG:
  17221. return this._gl.RG16F;
  17222. case Engine.TEXTUREFORMAT_RGB:
  17223. return this._gl.RGB16F;
  17224. }
  17225. }
  17226. return this._gl.RGBA16F;
  17227. }
  17228. if (format !== undefined) {
  17229. switch (format) {
  17230. case Engine.TEXTUREFORMAT_LUMINANCE:
  17231. return this._gl.LUMINANCE;
  17232. case Engine.TEXTUREFORMAT_RGB:
  17233. return this._gl.RGB;
  17234. case Engine.TEXTUREFORMAT_R:
  17235. return this._gl.R8;
  17236. case Engine.TEXTUREFORMAT_RG:
  17237. return this._gl.RG8;
  17238. case Engine.TEXTUREFORMAT_ALPHA:
  17239. return this._gl.ALPHA;
  17240. }
  17241. }
  17242. return this._gl.RGBA;
  17243. };
  17244. ;
  17245. /** @hidden */
  17246. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  17247. if (type === Engine.TEXTURETYPE_FLOAT) {
  17248. return this._gl.RGBA32F;
  17249. }
  17250. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17251. return this._gl.RGBA16F;
  17252. }
  17253. return this._gl.RGBA8;
  17254. };
  17255. ;
  17256. /**
  17257. * Create a new webGL query (you must be sure that queries are supported by checking getCaps() function)
  17258. * @return the new query
  17259. */
  17260. Engine.prototype.createQuery = function () {
  17261. return this._gl.createQuery();
  17262. };
  17263. /**
  17264. * Delete and release a webGL query
  17265. * @param query defines the query to delete
  17266. * @return the current engine
  17267. */
  17268. Engine.prototype.deleteQuery = function (query) {
  17269. this._gl.deleteQuery(query);
  17270. return this;
  17271. };
  17272. /**
  17273. * Check if a given query has resolved and got its value
  17274. * @param query defines the query to check
  17275. * @returns true if the query got its value
  17276. */
  17277. Engine.prototype.isQueryResultAvailable = function (query) {
  17278. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  17279. };
  17280. /**
  17281. * Gets the value of a given query
  17282. * @param query defines the query to check
  17283. * @returns the value of the query
  17284. */
  17285. Engine.prototype.getQueryResult = function (query) {
  17286. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  17287. };
  17288. /**
  17289. * Initiates an occlusion query
  17290. * @param algorithmType defines the algorithm to use
  17291. * @param query defines the query to use
  17292. * @returns the current engine
  17293. * @see http://doc.babylonjs.com/features/occlusionquery
  17294. */
  17295. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  17296. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  17297. this._gl.beginQuery(glAlgorithm, query);
  17298. return this;
  17299. };
  17300. /**
  17301. * Ends an occlusion query
  17302. * @see http://doc.babylonjs.com/features/occlusionquery
  17303. * @param algorithmType defines the algorithm to use
  17304. * @returns the current engine
  17305. */
  17306. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  17307. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  17308. this._gl.endQuery(glAlgorithm);
  17309. return this;
  17310. };
  17311. /* Time queries */
  17312. Engine.prototype._createTimeQuery = function () {
  17313. var timerQuery = this._caps.timerQuery;
  17314. if (timerQuery.createQueryEXT) {
  17315. return timerQuery.createQueryEXT();
  17316. }
  17317. return this.createQuery();
  17318. };
  17319. Engine.prototype._deleteTimeQuery = function (query) {
  17320. var timerQuery = this._caps.timerQuery;
  17321. if (timerQuery.deleteQueryEXT) {
  17322. timerQuery.deleteQueryEXT(query);
  17323. return;
  17324. }
  17325. this.deleteQuery(query);
  17326. };
  17327. Engine.prototype._getTimeQueryResult = function (query) {
  17328. var timerQuery = this._caps.timerQuery;
  17329. if (timerQuery.getQueryObjectEXT) {
  17330. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  17331. }
  17332. return this.getQueryResult(query);
  17333. };
  17334. Engine.prototype._getTimeQueryAvailability = function (query) {
  17335. var timerQuery = this._caps.timerQuery;
  17336. if (timerQuery.getQueryObjectEXT) {
  17337. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  17338. }
  17339. return this.isQueryResultAvailable(query);
  17340. };
  17341. /**
  17342. * Starts a time query (used to measure time spent by the GPU on a specific frame)
  17343. * Please note that only one query can be issued at a time
  17344. * @returns a time token used to track the time span
  17345. */
  17346. Engine.prototype.startTimeQuery = function () {
  17347. var timerQuery = this._caps.timerQuery;
  17348. if (!timerQuery) {
  17349. return null;
  17350. }
  17351. var token = new BABYLON._TimeToken();
  17352. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  17353. if (this._caps.canUseTimestampForTimerQuery) {
  17354. token._startTimeQuery = this._createTimeQuery();
  17355. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  17356. }
  17357. else {
  17358. if (this._currentNonTimestampToken) {
  17359. return this._currentNonTimestampToken;
  17360. }
  17361. token._timeElapsedQuery = this._createTimeQuery();
  17362. if (timerQuery.beginQueryEXT) {
  17363. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  17364. }
  17365. else {
  17366. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  17367. }
  17368. this._currentNonTimestampToken = token;
  17369. }
  17370. return token;
  17371. };
  17372. /**
  17373. * Ends a time query
  17374. * @param token defines the token used to measure the time span
  17375. * @returns the time spent (in ns)
  17376. */
  17377. Engine.prototype.endTimeQuery = function (token) {
  17378. var timerQuery = this._caps.timerQuery;
  17379. if (!timerQuery || !token) {
  17380. return -1;
  17381. }
  17382. if (this._caps.canUseTimestampForTimerQuery) {
  17383. if (!token._startTimeQuery) {
  17384. return -1;
  17385. }
  17386. if (!token._endTimeQuery) {
  17387. token._endTimeQuery = this._createTimeQuery();
  17388. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  17389. }
  17390. }
  17391. else if (!token._timeElapsedQueryEnded) {
  17392. if (!token._timeElapsedQuery) {
  17393. return -1;
  17394. }
  17395. if (timerQuery.endQueryEXT) {
  17396. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  17397. }
  17398. else {
  17399. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  17400. }
  17401. token._timeElapsedQueryEnded = true;
  17402. }
  17403. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  17404. var available = false;
  17405. if (token._endTimeQuery) {
  17406. available = this._getTimeQueryAvailability(token._endTimeQuery);
  17407. }
  17408. else if (token._timeElapsedQuery) {
  17409. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  17410. }
  17411. if (available && !disjoint) {
  17412. var result = 0;
  17413. if (this._caps.canUseTimestampForTimerQuery) {
  17414. if (!token._startTimeQuery || !token._endTimeQuery) {
  17415. return -1;
  17416. }
  17417. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  17418. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  17419. result = timeEnd - timeStart;
  17420. this._deleteTimeQuery(token._startTimeQuery);
  17421. this._deleteTimeQuery(token._endTimeQuery);
  17422. token._startTimeQuery = null;
  17423. token._endTimeQuery = null;
  17424. }
  17425. else {
  17426. if (!token._timeElapsedQuery) {
  17427. return -1;
  17428. }
  17429. result = this._getTimeQueryResult(token._timeElapsedQuery);
  17430. this._deleteTimeQuery(token._timeElapsedQuery);
  17431. token._timeElapsedQuery = null;
  17432. token._timeElapsedQueryEnded = false;
  17433. this._currentNonTimestampToken = null;
  17434. }
  17435. return result;
  17436. }
  17437. return -1;
  17438. };
  17439. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  17440. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  17441. };
  17442. // Transform feedback
  17443. /**
  17444. * Creates a webGL transform feedback object
  17445. * Please makes sure to check webGLVersion property to check if you are running webGL 2+
  17446. * @returns the webGL transform feedback object
  17447. */
  17448. Engine.prototype.createTransformFeedback = function () {
  17449. return this._gl.createTransformFeedback();
  17450. };
  17451. /**
  17452. * Delete a webGL transform feedback object
  17453. * @param value defines the webGL transform feedback object to delete
  17454. */
  17455. Engine.prototype.deleteTransformFeedback = function (value) {
  17456. this._gl.deleteTransformFeedback(value);
  17457. };
  17458. /**
  17459. * Bind a webGL transform feedback object to the webgl context
  17460. * @param value defines the webGL transform feedback object to bind
  17461. */
  17462. Engine.prototype.bindTransformFeedback = function (value) {
  17463. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  17464. };
  17465. /**
  17466. * Begins a transform feedback operation
  17467. * @param usePoints defines if points or triangles must be used
  17468. */
  17469. Engine.prototype.beginTransformFeedback = function (usePoints) {
  17470. if (usePoints === void 0) { usePoints = true; }
  17471. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  17472. };
  17473. /**
  17474. * Ends a transform feedback operation
  17475. */
  17476. Engine.prototype.endTransformFeedback = function () {
  17477. this._gl.endTransformFeedback();
  17478. };
  17479. /**
  17480. * Specify the varyings to use with transform feedback
  17481. * @param program defines the associated webGL program
  17482. * @param value defines the list of strings representing the varying names
  17483. */
  17484. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  17485. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  17486. };
  17487. /**
  17488. * Bind a webGL buffer for a transform feedback operation
  17489. * @param value defines the webGL buffer to bind
  17490. */
  17491. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  17492. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  17493. };
  17494. /** @hidden */
  17495. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  17496. var _this = this;
  17497. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  17498. this._activeRequests.push(request);
  17499. request.onCompleteObservable.add(function (request) {
  17500. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  17501. });
  17502. return request;
  17503. };
  17504. /** @hidden */
  17505. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  17506. var _this = this;
  17507. return new Promise(function (resolve, reject) {
  17508. _this._loadFile(url, function (data) {
  17509. resolve(data);
  17510. }, undefined, database, useArrayBuffer, function (request, exception) {
  17511. reject(exception);
  17512. });
  17513. });
  17514. };
  17515. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  17516. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  17517. var onload = function (data) {
  17518. loadedFiles[index] = data;
  17519. loadedFiles._internalCount++;
  17520. if (loadedFiles._internalCount === 6) {
  17521. onfinish(loadedFiles);
  17522. }
  17523. };
  17524. var onerror = function (request, exception) {
  17525. if (onErrorCallBack && request) {
  17526. onErrorCallBack(request.status + " " + request.statusText, exception);
  17527. }
  17528. };
  17529. this._loadFile(url, onload, undefined, undefined, true, onerror);
  17530. };
  17531. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  17532. if (onError === void 0) { onError = null; }
  17533. var loadedFiles = [];
  17534. loadedFiles._internalCount = 0;
  17535. for (var index = 0; index < 6; index++) {
  17536. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  17537. }
  17538. };
  17539. // Statics
  17540. /**
  17541. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  17542. * @returns true if the engine can be created
  17543. * @ignorenaming
  17544. */
  17545. Engine.isSupported = function () {
  17546. try {
  17547. var tempcanvas = document.createElement("canvas");
  17548. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  17549. return gl != null && !!window.WebGLRenderingContext;
  17550. }
  17551. catch (e) {
  17552. return false;
  17553. }
  17554. };
  17555. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  17556. Engine.ExceptionList = [
  17557. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  17558. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17559. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17560. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17561. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17562. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  17563. ];
  17564. /** Gets the list of created engines */
  17565. Engine.Instances = new Array();
  17566. // Const statics
  17567. Engine._ALPHA_DISABLE = 0;
  17568. Engine._ALPHA_ADD = 1;
  17569. Engine._ALPHA_COMBINE = 2;
  17570. Engine._ALPHA_SUBTRACT = 3;
  17571. Engine._ALPHA_MULTIPLY = 4;
  17572. Engine._ALPHA_MAXIMIZED = 5;
  17573. Engine._ALPHA_ONEONE = 6;
  17574. Engine._ALPHA_PREMULTIPLIED = 7;
  17575. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  17576. Engine._ALPHA_INTERPOLATE = 9;
  17577. Engine._ALPHA_SCREENMODE = 10;
  17578. Engine._DELAYLOADSTATE_NONE = 0;
  17579. Engine._DELAYLOADSTATE_LOADED = 1;
  17580. Engine._DELAYLOADSTATE_LOADING = 2;
  17581. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  17582. Engine._TEXTUREFORMAT_ALPHA = 0;
  17583. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  17584. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  17585. Engine._TEXTUREFORMAT_RGB = 4;
  17586. Engine._TEXTUREFORMAT_RGBA = 5;
  17587. Engine._TEXTUREFORMAT_R = 6;
  17588. Engine._TEXTUREFORMAT_RG = 7;
  17589. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  17590. Engine._TEXTURETYPE_FLOAT = 1;
  17591. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  17592. // Depht or Stencil test Constants.
  17593. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  17594. 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.
  17595. 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.
  17596. 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.
  17597. 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.
  17598. 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.
  17599. 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.
  17600. 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.
  17601. // Stencil Actions Constants.
  17602. Engine._KEEP = 0x1E00;
  17603. Engine._REPLACE = 0x1E01;
  17604. Engine._INCR = 0x1E02;
  17605. Engine._DECR = 0x1E03;
  17606. Engine._INVERT = 0x150A;
  17607. Engine._INCR_WRAP = 0x8507;
  17608. Engine._DECR_WRAP = 0x8508;
  17609. // Texture rescaling mode
  17610. Engine._SCALEMODE_FLOOR = 1;
  17611. Engine._SCALEMODE_NEAREST = 2;
  17612. Engine._SCALEMODE_CEILING = 3;
  17613. // Updatable statics so stick with vars here
  17614. /**
  17615. * Gets or sets the epsilon value used by collision engine
  17616. */
  17617. Engine.CollisionsEpsilon = 0.001;
  17618. /**
  17619. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  17620. */
  17621. Engine.CodeRepository = "src/";
  17622. /**
  17623. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  17624. */
  17625. Engine.ShadersRepository = "src/Shaders/";
  17626. return Engine;
  17627. }());
  17628. BABYLON.Engine = Engine;
  17629. })(BABYLON || (BABYLON = {}));
  17630. //# sourceMappingURL=babylon.engine.js.map
  17631. var BABYLON;
  17632. (function (BABYLON) {
  17633. /**
  17634. * Node is the basic class for all scene objects (Mesh, Light Camera).
  17635. */
  17636. var Node = /** @class */ (function () {
  17637. /**
  17638. * Creates a new Node
  17639. * @param {string} name - the name and id to be given to this node
  17640. * @param {BABYLON.Scene} the scene this node will be added to
  17641. */
  17642. function Node(name, scene) {
  17643. if (scene === void 0) { scene = null; }
  17644. /**
  17645. * Gets or sets a string used to store user defined state for the node
  17646. */
  17647. this.state = "";
  17648. /**
  17649. * Gets or sets an object used to store user defined information for the node
  17650. */
  17651. this.metadata = null;
  17652. /**
  17653. * Gets or sets a boolean used to define if the node must be serialized
  17654. */
  17655. this.doNotSerialize = false;
  17656. /** @hidden */
  17657. this._isDisposed = false;
  17658. /**
  17659. * Gets a list of Animations associated with the node
  17660. */
  17661. this.animations = new Array();
  17662. this._ranges = {};
  17663. this._isEnabled = true;
  17664. this._isReady = true;
  17665. /** @hidden */
  17666. this._currentRenderId = -1;
  17667. this._parentRenderId = -1;
  17668. this._childRenderId = -1;
  17669. this._animationPropertiesOverride = null;
  17670. /**
  17671. * An event triggered when the mesh is disposed
  17672. */
  17673. this.onDisposeObservable = new BABYLON.Observable();
  17674. // Behaviors
  17675. this._behaviors = new Array();
  17676. this.name = name;
  17677. this.id = name;
  17678. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  17679. this.uniqueId = this._scene.getUniqueId();
  17680. this._initCache();
  17681. }
  17682. /**
  17683. * Gets a boolean indicating if the node has been disposed
  17684. * @returns true if the node was disposed
  17685. */
  17686. Node.prototype.isDisposed = function () {
  17687. return this._isDisposed;
  17688. };
  17689. Object.defineProperty(Node.prototype, "parent", {
  17690. get: function () {
  17691. return this._parentNode;
  17692. },
  17693. /**
  17694. * Gets or sets the parent of the node
  17695. */
  17696. set: function (parent) {
  17697. if (this._parentNode === parent) {
  17698. return;
  17699. }
  17700. // Remove self from list of children of parent
  17701. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  17702. var index = this._parentNode._children.indexOf(this);
  17703. if (index !== -1) {
  17704. this._parentNode._children.splice(index, 1);
  17705. }
  17706. }
  17707. // Store new parent
  17708. this._parentNode = parent;
  17709. // Add as child to new parent
  17710. if (this._parentNode) {
  17711. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  17712. this._parentNode._children = new Array();
  17713. }
  17714. this._parentNode._children.push(this);
  17715. }
  17716. },
  17717. enumerable: true,
  17718. configurable: true
  17719. });
  17720. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  17721. /**
  17722. * Gets or sets the animation properties override
  17723. */
  17724. get: function () {
  17725. if (!this._animationPropertiesOverride) {
  17726. return this._scene.animationPropertiesOverride;
  17727. }
  17728. return this._animationPropertiesOverride;
  17729. },
  17730. set: function (value) {
  17731. this._animationPropertiesOverride = value;
  17732. },
  17733. enumerable: true,
  17734. configurable: true
  17735. });
  17736. /**
  17737. * Gets a string idenfifying the name of the class
  17738. * @returns "Node" string
  17739. */
  17740. Node.prototype.getClassName = function () {
  17741. return "Node";
  17742. };
  17743. Object.defineProperty(Node.prototype, "onDispose", {
  17744. /**
  17745. * Sets a callback that will be raised when the node will be disposed
  17746. */
  17747. set: function (callback) {
  17748. if (this._onDisposeObserver) {
  17749. this.onDisposeObservable.remove(this._onDisposeObserver);
  17750. }
  17751. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17752. },
  17753. enumerable: true,
  17754. configurable: true
  17755. });
  17756. /**
  17757. * Gets the scene of the node
  17758. * @returns a {BABYLON.Scene}
  17759. */
  17760. Node.prototype.getScene = function () {
  17761. return this._scene;
  17762. };
  17763. /**
  17764. * Gets the engine of the node
  17765. * @returns a {BABYLON.Engine}
  17766. */
  17767. Node.prototype.getEngine = function () {
  17768. return this._scene.getEngine();
  17769. };
  17770. /**
  17771. * Attach a behavior to the node
  17772. * @see http://doc.babylonjs.com/features/behaviour
  17773. * @param behavior defines the behavior to attach
  17774. * @returns the current Node
  17775. */
  17776. Node.prototype.addBehavior = function (behavior) {
  17777. var _this = this;
  17778. var index = this._behaviors.indexOf(behavior);
  17779. if (index !== -1) {
  17780. return this;
  17781. }
  17782. behavior.init();
  17783. if (this._scene.isLoading) {
  17784. // We defer the attach when the scene will be loaded
  17785. this._scene.onDataLoadedObservable.addOnce(function () {
  17786. behavior.attach(_this);
  17787. });
  17788. }
  17789. else {
  17790. behavior.attach(this);
  17791. }
  17792. this._behaviors.push(behavior);
  17793. return this;
  17794. };
  17795. /**
  17796. * Remove an attached behavior
  17797. * @see http://doc.babylonjs.com/features/behaviour
  17798. * @param behavior defines the behavior to attach
  17799. * @returns the current Node
  17800. */
  17801. Node.prototype.removeBehavior = function (behavior) {
  17802. var index = this._behaviors.indexOf(behavior);
  17803. if (index === -1) {
  17804. return this;
  17805. }
  17806. this._behaviors[index].detach();
  17807. this._behaviors.splice(index, 1);
  17808. return this;
  17809. };
  17810. Object.defineProperty(Node.prototype, "behaviors", {
  17811. /**
  17812. * Gets the list of attached behaviors
  17813. * @see http://doc.babylonjs.com/features/behaviour
  17814. */
  17815. get: function () {
  17816. return this._behaviors;
  17817. },
  17818. enumerable: true,
  17819. configurable: true
  17820. });
  17821. /**
  17822. * Gets an attached behavior by name
  17823. * @param name defines the name of the behavior to look for
  17824. * @see http://doc.babylonjs.com/features/behaviour
  17825. * @returns null if behavior was not found else the requested behavior
  17826. */
  17827. Node.prototype.getBehaviorByName = function (name) {
  17828. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  17829. var behavior = _a[_i];
  17830. if (behavior.name === name) {
  17831. return behavior;
  17832. }
  17833. }
  17834. return null;
  17835. };
  17836. /**
  17837. * Returns the world matrix of the node
  17838. * @returns a matrix containing the node's world matrix
  17839. */
  17840. Node.prototype.getWorldMatrix = function () {
  17841. return BABYLON.Matrix.Identity();
  17842. };
  17843. /** @hidden */
  17844. Node.prototype._getWorldMatrixDeterminant = function () {
  17845. return 1;
  17846. };
  17847. // override it in derived class if you add new variables to the cache
  17848. // and call the parent class method
  17849. /** @hidden */
  17850. Node.prototype._initCache = function () {
  17851. this._cache = {};
  17852. this._cache.parent = undefined;
  17853. };
  17854. /** @hidden */
  17855. Node.prototype.updateCache = function (force) {
  17856. if (!force && this.isSynchronized())
  17857. return;
  17858. this._cache.parent = this.parent;
  17859. this._updateCache();
  17860. };
  17861. // override it in derived class if you add new variables to the cache
  17862. // and call the parent class method if !ignoreParentClass
  17863. /** @hidden */
  17864. Node.prototype._updateCache = function (ignoreParentClass) {
  17865. };
  17866. // override it in derived class if you add new variables to the cache
  17867. /** @hidden */
  17868. Node.prototype._isSynchronized = function () {
  17869. return true;
  17870. };
  17871. /** @hidden */
  17872. Node.prototype._markSyncedWithParent = function () {
  17873. if (this.parent) {
  17874. this._parentRenderId = this.parent._childRenderId;
  17875. }
  17876. };
  17877. /** @hidden */
  17878. Node.prototype.isSynchronizedWithParent = function () {
  17879. if (!this.parent) {
  17880. return true;
  17881. }
  17882. if (this._parentRenderId !== this.parent._childRenderId) {
  17883. return false;
  17884. }
  17885. return this.parent.isSynchronized();
  17886. };
  17887. /** @hidden */
  17888. Node.prototype.isSynchronized = function (updateCache) {
  17889. var check = this.hasNewParent();
  17890. check = check || !this.isSynchronizedWithParent();
  17891. check = check || !this._isSynchronized();
  17892. if (updateCache)
  17893. this.updateCache(true);
  17894. return !check;
  17895. };
  17896. /** @hidden */
  17897. Node.prototype.hasNewParent = function (update) {
  17898. if (this._cache.parent === this.parent)
  17899. return false;
  17900. if (update)
  17901. this._cache.parent = this.parent;
  17902. return true;
  17903. };
  17904. /**
  17905. * Is this node ready to be used/rendered
  17906. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  17907. * @return true if the node is ready
  17908. */
  17909. Node.prototype.isReady = function (completeCheck) {
  17910. if (completeCheck === void 0) { completeCheck = false; }
  17911. return this._isReady;
  17912. };
  17913. /**
  17914. * Is this node enabled?
  17915. * 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
  17916. * @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
  17917. * @return whether this node (and its parent) is enabled
  17918. */
  17919. Node.prototype.isEnabled = function (checkAncestors) {
  17920. if (checkAncestors === void 0) { checkAncestors = true; }
  17921. if (checkAncestors === false) {
  17922. return this._isEnabled;
  17923. }
  17924. if (this._isEnabled === false) {
  17925. return false;
  17926. }
  17927. if (this.parent !== undefined && this.parent !== null) {
  17928. return this.parent.isEnabled(checkAncestors);
  17929. }
  17930. return true;
  17931. };
  17932. /**
  17933. * Set the enabled state of this node
  17934. * @param value defines the new enabled state
  17935. */
  17936. Node.prototype.setEnabled = function (value) {
  17937. this._isEnabled = value;
  17938. };
  17939. /**
  17940. * Is this node a descendant of the given node?
  17941. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  17942. * @param ancestor defines the parent node to inspect
  17943. * @returns a boolean indicating if this node is a descendant of the given node
  17944. */
  17945. Node.prototype.isDescendantOf = function (ancestor) {
  17946. if (this.parent) {
  17947. if (this.parent === ancestor) {
  17948. return true;
  17949. }
  17950. return this.parent.isDescendantOf(ancestor);
  17951. }
  17952. return false;
  17953. };
  17954. /** @hidden */
  17955. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  17956. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  17957. if (!this._children) {
  17958. return;
  17959. }
  17960. for (var index = 0; index < this._children.length; index++) {
  17961. var item = this._children[index];
  17962. if (!predicate || predicate(item)) {
  17963. results.push(item);
  17964. }
  17965. if (!directDescendantsOnly) {
  17966. item._getDescendants(results, false, predicate);
  17967. }
  17968. }
  17969. };
  17970. /**
  17971. * Will return all nodes that have this node as ascendant
  17972. * @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
  17973. * @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
  17974. * @return all children nodes of all types
  17975. */
  17976. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  17977. var results = new Array();
  17978. this._getDescendants(results, directDescendantsOnly, predicate);
  17979. return results;
  17980. };
  17981. /**
  17982. * Get all child-meshes of this node
  17983. * @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
  17984. * @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
  17985. * @returns an array of {BABYLON.AbstractMesh}
  17986. */
  17987. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  17988. var results = [];
  17989. this._getDescendants(results, directDescendantsOnly, function (node) {
  17990. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  17991. });
  17992. return results;
  17993. };
  17994. /**
  17995. * Get all child-transformNodes of this node
  17996. * @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
  17997. * @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
  17998. * @returns an array of {BABYLON.TransformNode}
  17999. */
  18000. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  18001. var results = [];
  18002. this._getDescendants(results, directDescendantsOnly, function (node) {
  18003. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  18004. });
  18005. return results;
  18006. };
  18007. /**
  18008. * Get all direct children of this node
  18009. * @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
  18010. * @returns an array of {BABYLON.Node}
  18011. */
  18012. Node.prototype.getChildren = function (predicate) {
  18013. return this.getDescendants(true, predicate);
  18014. };
  18015. /** @hidden */
  18016. Node.prototype._setReady = function (state) {
  18017. if (state === this._isReady) {
  18018. return;
  18019. }
  18020. if (!state) {
  18021. this._isReady = false;
  18022. return;
  18023. }
  18024. if (this.onReady) {
  18025. this.onReady(this);
  18026. }
  18027. this._isReady = true;
  18028. };
  18029. /**
  18030. * Get an animation by name
  18031. * @param name defines the name of the animation to look for
  18032. * @returns null if not found else the requested animation
  18033. */
  18034. Node.prototype.getAnimationByName = function (name) {
  18035. for (var i = 0; i < this.animations.length; i++) {
  18036. var animation = this.animations[i];
  18037. if (animation.name === name) {
  18038. return animation;
  18039. }
  18040. }
  18041. return null;
  18042. };
  18043. /**
  18044. * Creates an animation range for this node
  18045. * @param name defines the name of the range
  18046. * @param from defines the starting key
  18047. * @param to defines the end key
  18048. */
  18049. Node.prototype.createAnimationRange = function (name, from, to) {
  18050. // check name not already in use
  18051. if (!this._ranges[name]) {
  18052. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  18053. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  18054. if (this.animations[i]) {
  18055. this.animations[i].createRange(name, from, to);
  18056. }
  18057. }
  18058. }
  18059. };
  18060. /**
  18061. * Delete a specific animation range
  18062. * @param name defines the name of the range to delete
  18063. * @param deleteFrames defines if animation frames from the range must be deleted as well
  18064. */
  18065. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  18066. if (deleteFrames === void 0) { deleteFrames = true; }
  18067. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  18068. if (this.animations[i]) {
  18069. this.animations[i].deleteRange(name, deleteFrames);
  18070. }
  18071. }
  18072. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  18073. };
  18074. /**
  18075. * Get an animation range by name
  18076. * @param name defines the name of the animation range to look for
  18077. * @returns null if not found else the requested animation range
  18078. */
  18079. Node.prototype.getAnimationRange = function (name) {
  18080. return this._ranges[name];
  18081. };
  18082. /**
  18083. * Will start the animation sequence
  18084. * @param name defines the range frames for animation sequence
  18085. * @param loop defines if the animation should loop (false by default)
  18086. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  18087. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  18088. * @returns the object created for this animation. If range does not exist, it will return null
  18089. */
  18090. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  18091. var range = this.getAnimationRange(name);
  18092. if (!range) {
  18093. return null;
  18094. }
  18095. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  18096. };
  18097. /**
  18098. * Serialize animation ranges into a JSON compatible object
  18099. * @returns serialization object
  18100. */
  18101. Node.prototype.serializeAnimationRanges = function () {
  18102. var serializationRanges = [];
  18103. for (var name in this._ranges) {
  18104. var localRange = this._ranges[name];
  18105. if (!localRange) {
  18106. continue;
  18107. }
  18108. var range = {};
  18109. range.name = name;
  18110. range.from = localRange.from;
  18111. range.to = localRange.to;
  18112. serializationRanges.push(range);
  18113. }
  18114. return serializationRanges;
  18115. };
  18116. /**
  18117. * Computes the world matrix of the node
  18118. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  18119. * @returns the world matrix
  18120. */
  18121. Node.prototype.computeWorldMatrix = function (force) {
  18122. return BABYLON.Matrix.Identity();
  18123. };
  18124. /**
  18125. * Releases resources associated with this node.
  18126. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  18127. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  18128. */
  18129. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18130. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18131. if (!doNotRecurse) {
  18132. var nodes = this.getDescendants(true);
  18133. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  18134. var node = nodes_1[_i];
  18135. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  18136. }
  18137. }
  18138. else {
  18139. var transformNodes = this.getChildTransformNodes(true);
  18140. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  18141. var transformNode = transformNodes_1[_a];
  18142. transformNode.parent = null;
  18143. transformNode.computeWorldMatrix(true);
  18144. }
  18145. }
  18146. this.parent = null;
  18147. // Callback
  18148. this.onDisposeObservable.notifyObservers(this);
  18149. this.onDisposeObservable.clear();
  18150. // Behaviors
  18151. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  18152. var behavior = _c[_b];
  18153. behavior.detach();
  18154. }
  18155. this._behaviors = [];
  18156. this._isDisposed = true;
  18157. };
  18158. /**
  18159. * Parse animation range data from a serialization object and store them into a given node
  18160. * @param node defines where to store the animation ranges
  18161. * @param parsedNode defines the serialization object to read data from
  18162. * @param scene defines the hosting scene
  18163. */
  18164. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  18165. if (parsedNode.ranges) {
  18166. for (var index = 0; index < parsedNode.ranges.length; index++) {
  18167. var data = parsedNode.ranges[index];
  18168. node.createAnimationRange(data.name, data.from, data.to);
  18169. }
  18170. }
  18171. };
  18172. __decorate([
  18173. BABYLON.serialize()
  18174. ], Node.prototype, "name", void 0);
  18175. __decorate([
  18176. BABYLON.serialize()
  18177. ], Node.prototype, "id", void 0);
  18178. __decorate([
  18179. BABYLON.serialize()
  18180. ], Node.prototype, "uniqueId", void 0);
  18181. __decorate([
  18182. BABYLON.serialize()
  18183. ], Node.prototype, "state", void 0);
  18184. __decorate([
  18185. BABYLON.serialize()
  18186. ], Node.prototype, "metadata", void 0);
  18187. return Node;
  18188. }());
  18189. BABYLON.Node = Node;
  18190. })(BABYLON || (BABYLON = {}));
  18191. //# sourceMappingURL=babylon.node.js.map
  18192. var BABYLON;
  18193. (function (BABYLON) {
  18194. var BoundingSphere = /** @class */ (function () {
  18195. /**
  18196. * Creates a new bounding sphere
  18197. * @param min defines the minimum vector (in local space)
  18198. * @param max defines the maximum vector (in local space)
  18199. */
  18200. function BoundingSphere(min, max) {
  18201. this._tempRadiusVector = BABYLON.Vector3.Zero();
  18202. this.reConstruct(min, max);
  18203. }
  18204. /**
  18205. * Recreates the entire bounding sphere from scratch
  18206. * @param min defines the new minimum vector (in local space)
  18207. * @param max defines the new maximum vector (in local space)
  18208. */
  18209. BoundingSphere.prototype.reConstruct = function (min, max) {
  18210. this.minimum = min.clone();
  18211. this.maximum = max.clone();
  18212. var distance = BABYLON.Vector3.Distance(min, max);
  18213. this.center = BABYLON.Vector3.Lerp(min, max, 0.5);
  18214. this.radius = distance * 0.5;
  18215. this.centerWorld = BABYLON.Vector3.Zero();
  18216. this._update(BABYLON.Matrix.Identity());
  18217. };
  18218. // Methods
  18219. BoundingSphere.prototype._update = function (world) {
  18220. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  18221. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  18222. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  18223. };
  18224. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  18225. for (var i = 0; i < 6; i++) {
  18226. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  18227. return false;
  18228. }
  18229. return true;
  18230. };
  18231. BoundingSphere.prototype.intersectsPoint = function (point) {
  18232. var x = this.centerWorld.x - point.x;
  18233. var y = this.centerWorld.y - point.y;
  18234. var z = this.centerWorld.z - point.z;
  18235. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18236. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  18237. return false;
  18238. return true;
  18239. };
  18240. // Statics
  18241. BoundingSphere.Intersects = function (sphere0, sphere1) {
  18242. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  18243. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  18244. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  18245. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18246. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  18247. return false;
  18248. return true;
  18249. };
  18250. return BoundingSphere;
  18251. }());
  18252. BABYLON.BoundingSphere = BoundingSphere;
  18253. })(BABYLON || (BABYLON = {}));
  18254. //# sourceMappingURL=babylon.boundingSphere.js.map
  18255. var BABYLON;
  18256. (function (BABYLON) {
  18257. var BoundingBox = /** @class */ (function () {
  18258. /**
  18259. * Creates a new bounding box
  18260. * @param min defines the minimum vector (in local space)
  18261. * @param max defines the maximum vector (in local space)
  18262. */
  18263. function BoundingBox(min, max) {
  18264. this.vectorsWorld = new Array();
  18265. this.reConstruct(min, max);
  18266. }
  18267. // Methods
  18268. /**
  18269. * Recreates the entire bounding box from scratch
  18270. * @param min defines the new minimum vector (in local space)
  18271. * @param max defines the new maximum vector (in local space)
  18272. */
  18273. BoundingBox.prototype.reConstruct = function (min, max) {
  18274. this.minimum = min.clone();
  18275. this.maximum = max.clone();
  18276. // Bounding vectors
  18277. this.vectors = new Array();
  18278. this.vectors.push(this.minimum.clone());
  18279. this.vectors.push(this.maximum.clone());
  18280. this.vectors.push(this.minimum.clone());
  18281. this.vectors[2].x = this.maximum.x;
  18282. this.vectors.push(this.minimum.clone());
  18283. this.vectors[3].y = this.maximum.y;
  18284. this.vectors.push(this.minimum.clone());
  18285. this.vectors[4].z = this.maximum.z;
  18286. this.vectors.push(this.maximum.clone());
  18287. this.vectors[5].z = this.minimum.z;
  18288. this.vectors.push(this.maximum.clone());
  18289. this.vectors[6].x = this.minimum.x;
  18290. this.vectors.push(this.maximum.clone());
  18291. this.vectors[7].y = this.minimum.y;
  18292. // OBB
  18293. this.center = this.maximum.add(this.minimum).scale(0.5);
  18294. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  18295. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  18296. // World
  18297. for (var index = 0; index < this.vectors.length; index++) {
  18298. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  18299. }
  18300. this.minimumWorld = BABYLON.Vector3.Zero();
  18301. this.maximumWorld = BABYLON.Vector3.Zero();
  18302. this.centerWorld = BABYLON.Vector3.Zero();
  18303. this.extendSizeWorld = BABYLON.Vector3.Zero();
  18304. this._update(this._worldMatrix || BABYLON.Matrix.Identity());
  18305. };
  18306. BoundingBox.prototype.getWorldMatrix = function () {
  18307. return this._worldMatrix;
  18308. };
  18309. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  18310. this._worldMatrix.copyFrom(matrix);
  18311. return this;
  18312. };
  18313. BoundingBox.prototype._update = function (world) {
  18314. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  18315. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  18316. for (var index = 0; index < this.vectors.length; index++) {
  18317. var v = this.vectorsWorld[index];
  18318. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  18319. if (v.x < this.minimumWorld.x)
  18320. this.minimumWorld.x = v.x;
  18321. if (v.y < this.minimumWorld.y)
  18322. this.minimumWorld.y = v.y;
  18323. if (v.z < this.minimumWorld.z)
  18324. this.minimumWorld.z = v.z;
  18325. if (v.x > this.maximumWorld.x)
  18326. this.maximumWorld.x = v.x;
  18327. if (v.y > this.maximumWorld.y)
  18328. this.maximumWorld.y = v.y;
  18329. if (v.z > this.maximumWorld.z)
  18330. this.maximumWorld.z = v.z;
  18331. }
  18332. // Extend
  18333. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  18334. this.extendSizeWorld.scaleInPlace(0.5);
  18335. // OBB
  18336. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  18337. this.centerWorld.scaleInPlace(0.5);
  18338. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  18339. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  18340. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  18341. this._worldMatrix = world;
  18342. };
  18343. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  18344. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  18345. };
  18346. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18347. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  18348. };
  18349. BoundingBox.prototype.intersectsPoint = function (point) {
  18350. var delta = -BABYLON.Epsilon;
  18351. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  18352. return false;
  18353. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  18354. return false;
  18355. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  18356. return false;
  18357. return true;
  18358. };
  18359. BoundingBox.prototype.intersectsSphere = function (sphere) {
  18360. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  18361. };
  18362. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  18363. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  18364. return false;
  18365. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  18366. return false;
  18367. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  18368. return false;
  18369. return true;
  18370. };
  18371. // Statics
  18372. BoundingBox.Intersects = function (box0, box1) {
  18373. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  18374. return false;
  18375. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  18376. return false;
  18377. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  18378. return false;
  18379. return true;
  18380. };
  18381. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  18382. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  18383. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  18384. return (num <= (sphereRadius * sphereRadius));
  18385. };
  18386. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  18387. for (var p = 0; p < 6; p++) {
  18388. for (var i = 0; i < 8; i++) {
  18389. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18390. return false;
  18391. }
  18392. }
  18393. }
  18394. return true;
  18395. };
  18396. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  18397. for (var p = 0; p < 6; p++) {
  18398. var inCount = 8;
  18399. for (var i = 0; i < 8; i++) {
  18400. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18401. --inCount;
  18402. }
  18403. else {
  18404. break;
  18405. }
  18406. }
  18407. if (inCount === 0)
  18408. return false;
  18409. }
  18410. return true;
  18411. };
  18412. return BoundingBox;
  18413. }());
  18414. BABYLON.BoundingBox = BoundingBox;
  18415. })(BABYLON || (BABYLON = {}));
  18416. //# sourceMappingURL=babylon.boundingBox.js.map
  18417. var BABYLON;
  18418. (function (BABYLON) {
  18419. var computeBoxExtents = function (axis, box) {
  18420. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  18421. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  18422. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  18423. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  18424. var r = r0 + r1 + r2;
  18425. return {
  18426. min: p - r,
  18427. max: p + r
  18428. };
  18429. };
  18430. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  18431. var axisOverlap = function (axis, box0, box1) {
  18432. var result0 = computeBoxExtents(axis, box0);
  18433. var result1 = computeBoxExtents(axis, box1);
  18434. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  18435. };
  18436. var BoundingInfo = /** @class */ (function () {
  18437. function BoundingInfo(minimum, maximum) {
  18438. this.minimum = minimum;
  18439. this.maximum = maximum;
  18440. this._isLocked = false;
  18441. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  18442. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  18443. }
  18444. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  18445. get: function () {
  18446. return this._isLocked;
  18447. },
  18448. set: function (value) {
  18449. this._isLocked = value;
  18450. },
  18451. enumerable: true,
  18452. configurable: true
  18453. });
  18454. // Methods
  18455. BoundingInfo.prototype.update = function (world) {
  18456. if (this._isLocked) {
  18457. return;
  18458. }
  18459. this.boundingBox._update(world);
  18460. this.boundingSphere._update(world);
  18461. };
  18462. /**
  18463. * Recreate the bounding info to be centered around a specific point given a specific extend.
  18464. * @param center New center of the bounding info
  18465. * @param extend New extend of the bounding info
  18466. */
  18467. BoundingInfo.prototype.centerOn = function (center, extend) {
  18468. this.minimum = center.subtract(extend);
  18469. this.maximum = center.add(extend);
  18470. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  18471. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  18472. return this;
  18473. };
  18474. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  18475. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  18476. return false;
  18477. return this.boundingBox.isInFrustum(frustumPlanes);
  18478. };
  18479. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  18480. /**
  18481. * Gets the world distance between the min and max points of the bounding box
  18482. */
  18483. get: function () {
  18484. var boundingBox = this.boundingBox;
  18485. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  18486. return size.length();
  18487. },
  18488. enumerable: true,
  18489. configurable: true
  18490. });
  18491. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18492. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  18493. };
  18494. BoundingInfo.prototype._checkCollision = function (collider) {
  18495. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  18496. };
  18497. BoundingInfo.prototype.intersectsPoint = function (point) {
  18498. if (!this.boundingSphere.centerWorld) {
  18499. return false;
  18500. }
  18501. if (!this.boundingSphere.intersectsPoint(point)) {
  18502. return false;
  18503. }
  18504. if (!this.boundingBox.intersectsPoint(point)) {
  18505. return false;
  18506. }
  18507. return true;
  18508. };
  18509. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  18510. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  18511. return false;
  18512. }
  18513. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  18514. return false;
  18515. }
  18516. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  18517. return false;
  18518. }
  18519. if (!precise) {
  18520. return true;
  18521. }
  18522. var box0 = this.boundingBox;
  18523. var box1 = boundingInfo.boundingBox;
  18524. if (!axisOverlap(box0.directions[0], box0, box1))
  18525. return false;
  18526. if (!axisOverlap(box0.directions[1], box0, box1))
  18527. return false;
  18528. if (!axisOverlap(box0.directions[2], box0, box1))
  18529. return false;
  18530. if (!axisOverlap(box1.directions[0], box0, box1))
  18531. return false;
  18532. if (!axisOverlap(box1.directions[1], box0, box1))
  18533. return false;
  18534. if (!axisOverlap(box1.directions[2], box0, box1))
  18535. return false;
  18536. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  18537. return false;
  18538. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  18539. return false;
  18540. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  18541. return false;
  18542. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  18543. return false;
  18544. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  18545. return false;
  18546. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  18547. return false;
  18548. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  18549. return false;
  18550. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  18551. return false;
  18552. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  18553. return false;
  18554. return true;
  18555. };
  18556. return BoundingInfo;
  18557. }());
  18558. BABYLON.BoundingInfo = BoundingInfo;
  18559. })(BABYLON || (BABYLON = {}));
  18560. //# sourceMappingURL=babylon.boundingInfo.js.map
  18561. var BABYLON;
  18562. (function (BABYLON) {
  18563. var TransformNode = /** @class */ (function (_super) {
  18564. __extends(TransformNode, _super);
  18565. function TransformNode(name, scene, isPure) {
  18566. if (scene === void 0) { scene = null; }
  18567. if (isPure === void 0) { isPure = true; }
  18568. var _this = _super.call(this, name, scene) || this;
  18569. _this._forward = new BABYLON.Vector3(0, 0, 1);
  18570. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  18571. _this._up = new BABYLON.Vector3(0, 1, 0);
  18572. _this._right = new BABYLON.Vector3(1, 0, 0);
  18573. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  18574. // Properties
  18575. _this._rotation = BABYLON.Vector3.Zero();
  18576. _this._scaling = BABYLON.Vector3.One();
  18577. _this._isDirty = false;
  18578. /**
  18579. * Set the billboard mode. Default is 0.
  18580. *
  18581. * | Value | Type | Description |
  18582. * | --- | --- | --- |
  18583. * | 0 | BILLBOARDMODE_NONE | |
  18584. * | 1 | BILLBOARDMODE_X | |
  18585. * | 2 | BILLBOARDMODE_Y | |
  18586. * | 4 | BILLBOARDMODE_Z | |
  18587. * | 7 | BILLBOARDMODE_ALL | |
  18588. *
  18589. */
  18590. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  18591. _this.scalingDeterminant = 1;
  18592. _this.infiniteDistance = false;
  18593. /**
  18594. * Gets or sets a boolean indicating that non uniform scaling (when at least one component is different from others) should be ignored.
  18595. * By default the system will update normals to compensate
  18596. */
  18597. _this.ignoreNonUniformScaling = false;
  18598. _this.position = BABYLON.Vector3.Zero();
  18599. _this._localWorld = BABYLON.Matrix.Zero();
  18600. _this._worldMatrix = BABYLON.Matrix.Zero();
  18601. _this._worldMatrixDeterminant = 0;
  18602. _this._absolutePosition = BABYLON.Vector3.Zero();
  18603. _this._pivotMatrix = BABYLON.Matrix.Identity();
  18604. _this._postMultiplyPivotMatrix = false;
  18605. _this._isWorldMatrixFrozen = false;
  18606. /**
  18607. * An event triggered after the world matrix is updated
  18608. */
  18609. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  18610. _this._nonUniformScaling = false;
  18611. if (isPure) {
  18612. _this.getScene().addTransformNode(_this);
  18613. }
  18614. return _this;
  18615. }
  18616. /**
  18617. * Gets a string idenfifying the name of the class
  18618. * @returns "TransformNode" string
  18619. */
  18620. TransformNode.prototype.getClassName = function () {
  18621. return "TransformNode";
  18622. };
  18623. Object.defineProperty(TransformNode.prototype, "rotation", {
  18624. /**
  18625. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  18626. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  18627. * Default : (0.0, 0.0, 0.0)
  18628. */
  18629. get: function () {
  18630. return this._rotation;
  18631. },
  18632. set: function (newRotation) {
  18633. this._rotation = newRotation;
  18634. },
  18635. enumerable: true,
  18636. configurable: true
  18637. });
  18638. Object.defineProperty(TransformNode.prototype, "scaling", {
  18639. /**
  18640. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18641. * Default : (1.0, 1.0, 1.0)
  18642. */
  18643. get: function () {
  18644. return this._scaling;
  18645. },
  18646. /**
  18647. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18648. * Default : (1.0, 1.0, 1.0)
  18649. */
  18650. set: function (newScaling) {
  18651. this._scaling = newScaling;
  18652. },
  18653. enumerable: true,
  18654. configurable: true
  18655. });
  18656. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  18657. /**
  18658. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  18659. * It's null by default.
  18660. * 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)
  18661. */
  18662. get: function () {
  18663. return this._rotationQuaternion;
  18664. },
  18665. set: function (quaternion) {
  18666. this._rotationQuaternion = quaternion;
  18667. //reset the rotation vector.
  18668. if (quaternion && this.rotation.length()) {
  18669. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  18670. }
  18671. },
  18672. enumerable: true,
  18673. configurable: true
  18674. });
  18675. Object.defineProperty(TransformNode.prototype, "forward", {
  18676. /**
  18677. * The forward direction of that transform in world space.
  18678. */
  18679. get: function () {
  18680. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  18681. },
  18682. enumerable: true,
  18683. configurable: true
  18684. });
  18685. Object.defineProperty(TransformNode.prototype, "up", {
  18686. /**
  18687. * The up direction of that transform in world space.
  18688. */
  18689. get: function () {
  18690. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  18691. },
  18692. enumerable: true,
  18693. configurable: true
  18694. });
  18695. Object.defineProperty(TransformNode.prototype, "right", {
  18696. /**
  18697. * The right direction of that transform in world space.
  18698. */
  18699. get: function () {
  18700. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  18701. },
  18702. enumerable: true,
  18703. configurable: true
  18704. });
  18705. /**
  18706. * Returns the latest update of the World matrix
  18707. * Returns a Matrix.
  18708. */
  18709. TransformNode.prototype.getWorldMatrix = function () {
  18710. if (this._currentRenderId !== this.getScene().getRenderId()) {
  18711. this.computeWorldMatrix();
  18712. }
  18713. return this._worldMatrix;
  18714. };
  18715. /** @hidden */
  18716. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  18717. return this._worldMatrixDeterminant;
  18718. };
  18719. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  18720. /**
  18721. * Returns directly the latest state of the mesh World matrix.
  18722. * A Matrix is returned.
  18723. */
  18724. get: function () {
  18725. return this._worldMatrix;
  18726. },
  18727. enumerable: true,
  18728. configurable: true
  18729. });
  18730. /**
  18731. * Copies the paramater passed Matrix into the mesh Pose matrix.
  18732. * Returns the TransformNode.
  18733. */
  18734. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  18735. this._poseMatrix.copyFrom(matrix);
  18736. return this;
  18737. };
  18738. /**
  18739. * Returns the mesh Pose matrix.
  18740. * Returned object : Matrix
  18741. */
  18742. TransformNode.prototype.getPoseMatrix = function () {
  18743. return this._poseMatrix;
  18744. };
  18745. TransformNode.prototype._isSynchronized = function () {
  18746. if (this._isDirty) {
  18747. return false;
  18748. }
  18749. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  18750. return false;
  18751. if (this._cache.pivotMatrixUpdated) {
  18752. return false;
  18753. }
  18754. if (this.infiniteDistance) {
  18755. return false;
  18756. }
  18757. if (!this._cache.position.equals(this.position))
  18758. return false;
  18759. if (this.rotationQuaternion) {
  18760. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  18761. return false;
  18762. }
  18763. if (!this._cache.rotation.equals(this.rotation))
  18764. return false;
  18765. if (!this._cache.scaling.equals(this.scaling))
  18766. return false;
  18767. return true;
  18768. };
  18769. TransformNode.prototype._initCache = function () {
  18770. _super.prototype._initCache.call(this);
  18771. this._cache.localMatrixUpdated = false;
  18772. this._cache.position = BABYLON.Vector3.Zero();
  18773. this._cache.scaling = BABYLON.Vector3.Zero();
  18774. this._cache.rotation = BABYLON.Vector3.Zero();
  18775. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  18776. this._cache.billboardMode = -1;
  18777. };
  18778. TransformNode.prototype.markAsDirty = function (property) {
  18779. if (property === "rotation") {
  18780. this.rotationQuaternion = null;
  18781. }
  18782. this._currentRenderId = Number.MAX_VALUE;
  18783. this._isDirty = true;
  18784. return this;
  18785. };
  18786. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  18787. /**
  18788. * Returns the current mesh absolute position.
  18789. * Retuns a Vector3.
  18790. */
  18791. get: function () {
  18792. return this._absolutePosition;
  18793. },
  18794. enumerable: true,
  18795. configurable: true
  18796. });
  18797. /**
  18798. * Sets a new matrix to apply before all other transformation
  18799. * @param matrix defines the transform matrix
  18800. * @returns the current TransformNode
  18801. */
  18802. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  18803. return this.setPivotMatrix(matrix, false);
  18804. };
  18805. /**
  18806. * Sets a new pivot matrix to the current node
  18807. * @param matrix defines the new pivot matrix to use
  18808. * @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
  18809. * @returns the current TransformNode
  18810. */
  18811. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  18812. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  18813. this._pivotMatrix = matrix.clone();
  18814. this._cache.pivotMatrixUpdated = true;
  18815. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  18816. if (this._postMultiplyPivotMatrix) {
  18817. if (!this._pivotMatrixInverse) {
  18818. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  18819. }
  18820. else {
  18821. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  18822. }
  18823. }
  18824. return this;
  18825. };
  18826. /**
  18827. * Returns the mesh pivot matrix.
  18828. * Default : Identity.
  18829. * A Matrix is returned.
  18830. */
  18831. TransformNode.prototype.getPivotMatrix = function () {
  18832. return this._pivotMatrix;
  18833. };
  18834. /**
  18835. * Prevents the World matrix to be computed any longer.
  18836. * Returns the TransformNode.
  18837. */
  18838. TransformNode.prototype.freezeWorldMatrix = function () {
  18839. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  18840. this.computeWorldMatrix(true);
  18841. this._isWorldMatrixFrozen = true;
  18842. return this;
  18843. };
  18844. /**
  18845. * Allows back the World matrix computation.
  18846. * Returns the TransformNode.
  18847. */
  18848. TransformNode.prototype.unfreezeWorldMatrix = function () {
  18849. this._isWorldMatrixFrozen = false;
  18850. this.computeWorldMatrix(true);
  18851. return this;
  18852. };
  18853. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  18854. /**
  18855. * True if the World matrix has been frozen.
  18856. * Returns a boolean.
  18857. */
  18858. get: function () {
  18859. return this._isWorldMatrixFrozen;
  18860. },
  18861. enumerable: true,
  18862. configurable: true
  18863. });
  18864. /**
  18865. * Retuns the mesh absolute position in the World.
  18866. * Returns a Vector3.
  18867. */
  18868. TransformNode.prototype.getAbsolutePosition = function () {
  18869. this.computeWorldMatrix();
  18870. return this._absolutePosition;
  18871. };
  18872. /**
  18873. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  18874. * Returns the TransformNode.
  18875. */
  18876. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  18877. if (!absolutePosition) {
  18878. return this;
  18879. }
  18880. var absolutePositionX;
  18881. var absolutePositionY;
  18882. var absolutePositionZ;
  18883. if (absolutePosition.x === undefined) {
  18884. if (arguments.length < 3) {
  18885. return this;
  18886. }
  18887. absolutePositionX = arguments[0];
  18888. absolutePositionY = arguments[1];
  18889. absolutePositionZ = arguments[2];
  18890. }
  18891. else {
  18892. absolutePositionX = absolutePosition.x;
  18893. absolutePositionY = absolutePosition.y;
  18894. absolutePositionZ = absolutePosition.z;
  18895. }
  18896. if (this.parent) {
  18897. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18898. invertParentWorldMatrix.invert();
  18899. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  18900. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  18901. }
  18902. else {
  18903. this.position.x = absolutePositionX;
  18904. this.position.y = absolutePositionY;
  18905. this.position.z = absolutePositionZ;
  18906. }
  18907. return this;
  18908. };
  18909. /**
  18910. * Sets the mesh position in its local space.
  18911. * Returns the TransformNode.
  18912. */
  18913. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  18914. this.computeWorldMatrix();
  18915. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  18916. return this;
  18917. };
  18918. /**
  18919. * Returns the mesh position in the local space from the current World matrix values.
  18920. * Returns a new Vector3.
  18921. */
  18922. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  18923. this.computeWorldMatrix();
  18924. var invLocalWorldMatrix = this._localWorld.clone();
  18925. invLocalWorldMatrix.invert();
  18926. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  18927. };
  18928. /**
  18929. * Translates the mesh along the passed Vector3 in its local space.
  18930. * Returns the TransformNode.
  18931. */
  18932. TransformNode.prototype.locallyTranslate = function (vector3) {
  18933. this.computeWorldMatrix(true);
  18934. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  18935. return this;
  18936. };
  18937. /**
  18938. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  18939. * @param targetPoint the position (must be in same space as current mesh) to look at
  18940. * @param yawCor optional yaw (y-axis) correction in radians
  18941. * @param pitchCor optional pitch (x-axis) correction in radians
  18942. * @param rollCor optional roll (z-axis) correction in radians
  18943. * @param space the choosen space of the target
  18944. * @returns the TransformNode.
  18945. */
  18946. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  18947. if (yawCor === void 0) { yawCor = 0; }
  18948. if (pitchCor === void 0) { pitchCor = 0; }
  18949. if (rollCor === void 0) { rollCor = 0; }
  18950. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18951. var dv = TransformNode._lookAtVectorCache;
  18952. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  18953. targetPoint.subtractToRef(pos, dv);
  18954. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  18955. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  18956. var pitch = Math.atan2(dv.y, len);
  18957. if (this.rotationQuaternion) {
  18958. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  18959. }
  18960. else {
  18961. this.rotation.x = pitch + pitchCor;
  18962. this.rotation.y = yaw + yawCor;
  18963. this.rotation.z = rollCor;
  18964. }
  18965. return this;
  18966. };
  18967. /**
  18968. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  18969. * This Vector3 is expressed in the World space.
  18970. */
  18971. TransformNode.prototype.getDirection = function (localAxis) {
  18972. var result = BABYLON.Vector3.Zero();
  18973. this.getDirectionToRef(localAxis, result);
  18974. return result;
  18975. };
  18976. /**
  18977. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  18978. * localAxis is expressed in the mesh local space.
  18979. * result is computed in the Wordl space from the mesh World matrix.
  18980. * Returns the TransformNode.
  18981. */
  18982. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  18983. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  18984. return this;
  18985. };
  18986. /**
  18987. * Sets a new pivot point to the current node
  18988. * @param point defines the new pivot point to use
  18989. * @param space defines if the point is in world or local space (local by default)
  18990. * @returns the current TransformNode
  18991. */
  18992. TransformNode.prototype.setPivotPoint = function (point, space) {
  18993. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18994. if (this.getScene().getRenderId() == 0) {
  18995. this.computeWorldMatrix(true);
  18996. }
  18997. var wm = this.getWorldMatrix();
  18998. if (space == BABYLON.Space.WORLD) {
  18999. var tmat = BABYLON.Tmp.Matrix[0];
  19000. wm.invertToRef(tmat);
  19001. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  19002. }
  19003. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  19004. };
  19005. /**
  19006. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  19007. */
  19008. TransformNode.prototype.getPivotPoint = function () {
  19009. var point = BABYLON.Vector3.Zero();
  19010. this.getPivotPointToRef(point);
  19011. return point;
  19012. };
  19013. /**
  19014. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  19015. * Returns the TransformNode.
  19016. */
  19017. TransformNode.prototype.getPivotPointToRef = function (result) {
  19018. result.x = -this._pivotMatrix.m[12];
  19019. result.y = -this._pivotMatrix.m[13];
  19020. result.z = -this._pivotMatrix.m[14];
  19021. return this;
  19022. };
  19023. /**
  19024. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  19025. */
  19026. TransformNode.prototype.getAbsolutePivotPoint = function () {
  19027. var point = BABYLON.Vector3.Zero();
  19028. this.getAbsolutePivotPointToRef(point);
  19029. return point;
  19030. };
  19031. /**
  19032. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  19033. * Returns the TransformNode.
  19034. */
  19035. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  19036. result.x = this._pivotMatrix.m[12];
  19037. result.y = this._pivotMatrix.m[13];
  19038. result.z = this._pivotMatrix.m[14];
  19039. this.getPivotPointToRef(result);
  19040. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  19041. return this;
  19042. };
  19043. /**
  19044. * Defines the passed node as the parent of the current node.
  19045. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  19046. * Returns the TransformNode.
  19047. */
  19048. TransformNode.prototype.setParent = function (node) {
  19049. if (node === null) {
  19050. var rotation = BABYLON.Tmp.Quaternion[0];
  19051. var position = BABYLON.Tmp.Vector3[0];
  19052. var scale = BABYLON.Tmp.Vector3[1];
  19053. if (this.parent && this.parent.computeWorldMatrix) {
  19054. this.parent.computeWorldMatrix(true);
  19055. }
  19056. this.computeWorldMatrix(true);
  19057. this.getWorldMatrix().decompose(scale, rotation, position);
  19058. if (this.rotationQuaternion) {
  19059. this.rotationQuaternion.copyFrom(rotation);
  19060. }
  19061. else {
  19062. rotation.toEulerAnglesToRef(this.rotation);
  19063. }
  19064. this.scaling.x = scale.x;
  19065. this.scaling.y = scale.y;
  19066. this.scaling.z = scale.z;
  19067. this.position.x = position.x;
  19068. this.position.y = position.y;
  19069. this.position.z = position.z;
  19070. }
  19071. else {
  19072. var rotation = BABYLON.Tmp.Quaternion[0];
  19073. var position = BABYLON.Tmp.Vector3[0];
  19074. var scale = BABYLON.Tmp.Vector3[1];
  19075. var diffMatrix = BABYLON.Tmp.Matrix[0];
  19076. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  19077. this.computeWorldMatrix(true);
  19078. node.computeWorldMatrix(true);
  19079. node.getWorldMatrix().invertToRef(invParentMatrix);
  19080. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  19081. diffMatrix.decompose(scale, rotation, position);
  19082. if (this.rotationQuaternion) {
  19083. this.rotationQuaternion.copyFrom(rotation);
  19084. }
  19085. else {
  19086. rotation.toEulerAnglesToRef(this.rotation);
  19087. }
  19088. this.position.x = position.x;
  19089. this.position.y = position.y;
  19090. this.position.z = position.z;
  19091. this.scaling.x = scale.x;
  19092. this.scaling.y = scale.y;
  19093. this.scaling.z = scale.z;
  19094. }
  19095. this.parent = node;
  19096. return this;
  19097. };
  19098. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  19099. get: function () {
  19100. return this._nonUniformScaling;
  19101. },
  19102. enumerable: true,
  19103. configurable: true
  19104. });
  19105. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  19106. if (this._nonUniformScaling === value) {
  19107. return false;
  19108. }
  19109. this._nonUniformScaling = value;
  19110. return true;
  19111. };
  19112. /**
  19113. * Attach the current TransformNode to another TransformNode associated with a bone
  19114. * @param bone Bone affecting the TransformNode
  19115. * @param affectedTransformNode TransformNode associated with the bone
  19116. */
  19117. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  19118. this._transformToBoneReferal = affectedTransformNode;
  19119. this.parent = bone;
  19120. if (bone.getWorldMatrix().determinant() < 0) {
  19121. this.scalingDeterminant *= -1;
  19122. }
  19123. return this;
  19124. };
  19125. TransformNode.prototype.detachFromBone = function () {
  19126. if (!this.parent) {
  19127. return this;
  19128. }
  19129. if (this.parent.getWorldMatrix().determinant() < 0) {
  19130. this.scalingDeterminant *= -1;
  19131. }
  19132. this._transformToBoneReferal = null;
  19133. this.parent = null;
  19134. return this;
  19135. };
  19136. /**
  19137. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  19138. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19139. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19140. * The passed axis is also normalized.
  19141. * Returns the TransformNode.
  19142. */
  19143. TransformNode.prototype.rotate = function (axis, amount, space) {
  19144. axis.normalize();
  19145. if (!this.rotationQuaternion) {
  19146. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19147. this.rotation = BABYLON.Vector3.Zero();
  19148. }
  19149. var rotationQuaternion;
  19150. if (!space || space === BABYLON.Space.LOCAL) {
  19151. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  19152. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  19153. }
  19154. else {
  19155. if (this.parent) {
  19156. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  19157. invertParentWorldMatrix.invert();
  19158. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  19159. }
  19160. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  19161. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19162. }
  19163. return this;
  19164. };
  19165. /**
  19166. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  19167. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19168. * The passed axis is also normalized.
  19169. * Returns the TransformNode.
  19170. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  19171. */
  19172. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  19173. axis.normalize();
  19174. if (!this.rotationQuaternion) {
  19175. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19176. this.rotation.copyFromFloats(0, 0, 0);
  19177. }
  19178. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  19179. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  19180. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  19181. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  19182. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  19183. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  19184. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  19185. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  19186. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19187. return this;
  19188. };
  19189. /**
  19190. * Translates the mesh along the axis vector for the passed distance in the given space.
  19191. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19192. * Returns the TransformNode.
  19193. */
  19194. TransformNode.prototype.translate = function (axis, distance, space) {
  19195. var displacementVector = axis.scale(distance);
  19196. if (!space || space === BABYLON.Space.LOCAL) {
  19197. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  19198. this.setPositionWithLocalVector(tempV3);
  19199. }
  19200. else {
  19201. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  19202. }
  19203. return this;
  19204. };
  19205. /**
  19206. * Adds a rotation step to the mesh current rotation.
  19207. * x, y, z are Euler angles expressed in radians.
  19208. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  19209. * This means this rotation is made in the mesh local space only.
  19210. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  19211. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  19212. * ```javascript
  19213. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  19214. * ```
  19215. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  19216. * 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.
  19217. * Returns the TransformNode.
  19218. */
  19219. TransformNode.prototype.addRotation = function (x, y, z) {
  19220. var rotationQuaternion;
  19221. if (this.rotationQuaternion) {
  19222. rotationQuaternion = this.rotationQuaternion;
  19223. }
  19224. else {
  19225. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  19226. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  19227. }
  19228. var accumulation = BABYLON.Tmp.Quaternion[0];
  19229. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  19230. rotationQuaternion.multiplyInPlace(accumulation);
  19231. if (!this.rotationQuaternion) {
  19232. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  19233. }
  19234. return this;
  19235. };
  19236. /**
  19237. * Computes the mesh World matrix and returns it.
  19238. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  19239. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  19240. * If the parameter `force`is set to `true`, the actual computation is done.
  19241. * Returns the mesh World Matrix.
  19242. */
  19243. TransformNode.prototype.computeWorldMatrix = function (force) {
  19244. if (this._isWorldMatrixFrozen) {
  19245. return this._worldMatrix;
  19246. }
  19247. if (!force && this.isSynchronized(true)) {
  19248. this._currentRenderId = this.getScene().getRenderId();
  19249. return this._worldMatrix;
  19250. }
  19251. this._cache.position.copyFrom(this.position);
  19252. this._cache.scaling.copyFrom(this.scaling);
  19253. this._cache.pivotMatrixUpdated = false;
  19254. this._cache.billboardMode = this.billboardMode;
  19255. this._currentRenderId = this.getScene().getRenderId();
  19256. this._childRenderId = this.getScene().getRenderId();
  19257. this._isDirty = false;
  19258. // Scaling
  19259. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  19260. // Rotation
  19261. //rotate, if quaternion is set and rotation was used
  19262. if (this.rotationQuaternion) {
  19263. var len = this.rotation.length();
  19264. if (len) {
  19265. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  19266. this.rotation.copyFromFloats(0, 0, 0);
  19267. }
  19268. }
  19269. if (this.rotationQuaternion) {
  19270. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  19271. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  19272. }
  19273. else {
  19274. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  19275. this._cache.rotation.copyFrom(this.rotation);
  19276. }
  19277. // Translation
  19278. var camera = this.getScene().activeCamera;
  19279. if (this.infiniteDistance && !this.parent && camera) {
  19280. var cameraWorldMatrix = camera.getWorldMatrix();
  19281. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  19282. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  19283. }
  19284. else {
  19285. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  19286. }
  19287. // Composing transformations
  19288. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  19289. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19290. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  19291. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  19292. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  19293. // Need to decompose each rotation here
  19294. var currentPosition = BABYLON.Tmp.Vector3[3];
  19295. if (this.parent && this.parent.getWorldMatrix) {
  19296. if (this._transformToBoneReferal) {
  19297. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19298. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  19299. }
  19300. else {
  19301. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  19302. }
  19303. }
  19304. else {
  19305. currentPosition.copyFrom(this.position);
  19306. }
  19307. currentPosition.subtractInPlace(camera.globalPosition);
  19308. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  19309. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  19310. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  19311. }
  19312. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  19313. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  19314. }
  19315. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  19316. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  19317. }
  19318. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  19319. }
  19320. else {
  19321. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  19322. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  19323. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  19324. }
  19325. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  19326. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19327. }
  19328. // Local world
  19329. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  19330. // Parent
  19331. if (this.parent && this.parent.getWorldMatrix) {
  19332. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  19333. if (this._transformToBoneReferal) {
  19334. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19335. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  19336. }
  19337. else {
  19338. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  19339. }
  19340. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  19341. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  19342. this._worldMatrix.copyFrom(this._localWorld);
  19343. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  19344. }
  19345. else {
  19346. if (this._transformToBoneReferal) {
  19347. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19348. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  19349. }
  19350. else {
  19351. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  19352. }
  19353. }
  19354. this._markSyncedWithParent();
  19355. }
  19356. else {
  19357. this._worldMatrix.copyFrom(this._localWorld);
  19358. }
  19359. // Post multiply inverse of pivotMatrix
  19360. if (this._postMultiplyPivotMatrix) {
  19361. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  19362. }
  19363. // Normal matrix
  19364. if (!this.ignoreNonUniformScaling) {
  19365. if (this.scaling.isNonUniform) {
  19366. this._updateNonUniformScalingState(true);
  19367. }
  19368. else if (this.parent && this.parent._nonUniformScaling) {
  19369. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  19370. }
  19371. else {
  19372. this._updateNonUniformScalingState(false);
  19373. }
  19374. }
  19375. else {
  19376. this._updateNonUniformScalingState(false);
  19377. }
  19378. this._afterComputeWorldMatrix();
  19379. // Absolute position
  19380. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  19381. // Callbacks
  19382. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  19383. if (!this._poseMatrix) {
  19384. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  19385. }
  19386. // Cache the determinant
  19387. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  19388. return this._worldMatrix;
  19389. };
  19390. TransformNode.prototype._afterComputeWorldMatrix = function () {
  19391. };
  19392. /**
  19393. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  19394. * @param func: callback function to add
  19395. *
  19396. * Returns the TransformNode.
  19397. */
  19398. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  19399. this.onAfterWorldMatrixUpdateObservable.add(func);
  19400. return this;
  19401. };
  19402. /**
  19403. * Removes a registered callback function.
  19404. * Returns the TransformNode.
  19405. */
  19406. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  19407. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  19408. return this;
  19409. };
  19410. /**
  19411. * Clone the current transform node
  19412. * Returns the new transform node
  19413. * @param name Name of the new clone
  19414. * @param newParent New parent for the clone
  19415. * @param doNotCloneChildren Do not clone children hierarchy
  19416. */
  19417. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  19418. var _this = this;
  19419. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  19420. result.name = name;
  19421. result.id = name;
  19422. if (newParent) {
  19423. result.parent = newParent;
  19424. }
  19425. if (!doNotCloneChildren) {
  19426. // Children
  19427. var directDescendants = this.getDescendants(true);
  19428. for (var index = 0; index < directDescendants.length; index++) {
  19429. var child = directDescendants[index];
  19430. if (child.clone) {
  19431. child.clone(name + "." + child.name, result);
  19432. }
  19433. }
  19434. }
  19435. return result;
  19436. };
  19437. TransformNode.prototype.serialize = function (currentSerializationObject) {
  19438. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  19439. serializationObject.type = this.getClassName();
  19440. // Parent
  19441. if (this.parent) {
  19442. serializationObject.parentId = this.parent.id;
  19443. }
  19444. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  19445. serializationObject.tags = BABYLON.Tags.GetTags(this);
  19446. }
  19447. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  19448. serializationObject.isEnabled = this.isEnabled();
  19449. // Parent
  19450. if (this.parent) {
  19451. serializationObject.parentId = this.parent.id;
  19452. }
  19453. return serializationObject;
  19454. };
  19455. // Statics
  19456. /**
  19457. * Returns a new TransformNode object parsed from the source provided.
  19458. * The parameter `parsedMesh` is the source.
  19459. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  19460. */
  19461. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  19462. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  19463. if (BABYLON.Tags) {
  19464. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  19465. }
  19466. if (parsedTransformNode.localMatrix) {
  19467. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  19468. }
  19469. else if (parsedTransformNode.pivotMatrix) {
  19470. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  19471. }
  19472. transformNode.setEnabled(parsedTransformNode.isEnabled);
  19473. // Parent
  19474. if (parsedTransformNode.parentId) {
  19475. transformNode._waitingParentId = parsedTransformNode.parentId;
  19476. }
  19477. return transformNode;
  19478. };
  19479. /**
  19480. * Releases resources associated with this transform node.
  19481. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19482. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19483. */
  19484. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19485. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19486. // Animations
  19487. this.getScene().stopAnimation(this);
  19488. // Remove from scene
  19489. this.getScene().removeTransformNode(this);
  19490. this.onAfterWorldMatrixUpdateObservable.clear();
  19491. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19492. };
  19493. // Statics
  19494. TransformNode.BILLBOARDMODE_NONE = 0;
  19495. TransformNode.BILLBOARDMODE_X = 1;
  19496. TransformNode.BILLBOARDMODE_Y = 2;
  19497. TransformNode.BILLBOARDMODE_Z = 4;
  19498. TransformNode.BILLBOARDMODE_ALL = 7;
  19499. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  19500. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  19501. __decorate([
  19502. BABYLON.serializeAsVector3()
  19503. ], TransformNode.prototype, "_rotation", void 0);
  19504. __decorate([
  19505. BABYLON.serializeAsQuaternion()
  19506. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  19507. __decorate([
  19508. BABYLON.serializeAsVector3()
  19509. ], TransformNode.prototype, "_scaling", void 0);
  19510. __decorate([
  19511. BABYLON.serialize()
  19512. ], TransformNode.prototype, "billboardMode", void 0);
  19513. __decorate([
  19514. BABYLON.serialize()
  19515. ], TransformNode.prototype, "scalingDeterminant", void 0);
  19516. __decorate([
  19517. BABYLON.serialize()
  19518. ], TransformNode.prototype, "infiniteDistance", void 0);
  19519. __decorate([
  19520. BABYLON.serialize()
  19521. ], TransformNode.prototype, "ignoreNonUniformScaling", void 0);
  19522. __decorate([
  19523. BABYLON.serializeAsVector3()
  19524. ], TransformNode.prototype, "position", void 0);
  19525. return TransformNode;
  19526. }(BABYLON.Node));
  19527. BABYLON.TransformNode = TransformNode;
  19528. })(BABYLON || (BABYLON = {}));
  19529. //# sourceMappingURL=babylon.transformNode.js.map
  19530. var BABYLON;
  19531. (function (BABYLON) {
  19532. /**
  19533. * Class used to store all common mesh properties
  19534. */
  19535. var AbstractMesh = /** @class */ (function (_super) {
  19536. __extends(AbstractMesh, _super);
  19537. // Constructor
  19538. /**
  19539. * Creates a new AbstractMesh
  19540. * @param name defines the name of the mesh
  19541. * @param scene defines the hosting scene
  19542. */
  19543. function AbstractMesh(name, scene) {
  19544. if (scene === void 0) { scene = null; }
  19545. var _this = _super.call(this, name, scene, false) || this;
  19546. _this._facetNb = 0; // facet number
  19547. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  19548. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  19549. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  19550. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  19551. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  19552. _this._subDiv = {
  19553. max: 1,
  19554. X: 1,
  19555. Y: 1,
  19556. Z: 1
  19557. };
  19558. _this._facetDepthSort = false; // is the facet depth sort to be computed
  19559. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  19560. // Events
  19561. /**
  19562. * An event triggered when this mesh collides with another one
  19563. */
  19564. _this.onCollideObservable = new BABYLON.Observable();
  19565. /**
  19566. * An event triggered when the collision's position changes
  19567. */
  19568. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  19569. /**
  19570. * An event triggered when material is changed
  19571. */
  19572. _this.onMaterialChangedObservable = new BABYLON.Observable();
  19573. // Properties
  19574. /**
  19575. * Gets or sets the orientation for POV movement & rotation
  19576. */
  19577. _this.definedFacingForward = true;
  19578. /**
  19579. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  19580. * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  19581. * * 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.
  19582. * @see http://doc.babylonjs.com/features/occlusionquery
  19583. */
  19584. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  19585. /**
  19586. * 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:
  19587. * * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  19588. * * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  19589. * * 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.
  19590. * @see http://doc.babylonjs.com/features/occlusionquery
  19591. */
  19592. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  19593. /**
  19594. * 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.
  19595. * The default value is -1 which means don't break the query and wait till the result
  19596. * @see http://doc.babylonjs.com/features/occlusionquery
  19597. */
  19598. _this.occlusionRetryCount = -1;
  19599. _this._occlusionInternalRetryCounter = 0;
  19600. _this._isOccluded = false;
  19601. _this._isOcclusionQueryInProgress = false;
  19602. _this._visibility = 1.0;
  19603. /** Gets or sets the alpha index used to sort transparent meshes
  19604. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index
  19605. */
  19606. _this.alphaIndex = Number.MAX_VALUE;
  19607. /**
  19608. * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true
  19609. */
  19610. _this.isVisible = true;
  19611. /**
  19612. * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true
  19613. */
  19614. _this.isPickable = true;
  19615. /**
  19616. * Gets or sets a boolean indicating if the bounding box must be rendered as well (false by default)
  19617. */
  19618. _this.showBoundingBox = false;
  19619. /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */
  19620. _this.showSubMeshesBoundingBox = false;
  19621. /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)
  19622. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  19623. */
  19624. _this.isBlocker = false;
  19625. /**
  19626. * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)
  19627. */
  19628. _this.enablePointerMoveEvents = false;
  19629. /**
  19630. * Specifies the rendering group id for this mesh (0 by default)
  19631. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups
  19632. */
  19633. _this.renderingGroupId = 0;
  19634. _this._receiveShadows = false;
  19635. /**
  19636. * Gets or sets a boolean indicating if the outline must be rendered as well
  19637. * @see https://www.babylonjs-playground.com/#10WJ5S#3
  19638. */
  19639. _this.renderOutline = false;
  19640. /** Defines color to use when rendering outline */
  19641. _this.outlineColor = BABYLON.Color3.Red();
  19642. /** Define width to use when rendering outline */
  19643. _this.outlineWidth = 0.02;
  19644. /**
  19645. * Gets or sets a boolean indicating if the overlay must be rendered as well
  19646. * @see https://www.babylonjs-playground.com/#10WJ5S#2
  19647. */
  19648. _this.renderOverlay = false;
  19649. /** Defines color to use when rendering overlay */
  19650. _this.overlayColor = BABYLON.Color3.Red();
  19651. /** Defines alpha to use when rendering overlay */
  19652. _this.overlayAlpha = 0.5;
  19653. _this._hasVertexAlpha = false;
  19654. _this._useVertexColors = true;
  19655. _this._computeBonesUsingShaders = true;
  19656. _this._numBoneInfluencers = 4;
  19657. _this._applyFog = true;
  19658. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */
  19659. _this.useOctreeForRenderingSelection = true;
  19660. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */
  19661. _this.useOctreeForPicking = true;
  19662. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */
  19663. _this.useOctreeForCollisions = true;
  19664. _this._layerMask = 0x0FFFFFFF;
  19665. /**
  19666. * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)
  19667. */
  19668. _this.alwaysSelectAsActiveMesh = false;
  19669. /**
  19670. * Gets or sets the current action manager
  19671. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  19672. */
  19673. _this.actionManager = null;
  19674. /**
  19675. * Gets or sets impostor used for physic simulation
  19676. * @see http://doc.babylonjs.com/features/physics_engine
  19677. */
  19678. _this.physicsImpostor = null;
  19679. // Collisions
  19680. _this._checkCollisions = false;
  19681. _this._collisionMask = -1;
  19682. _this._collisionGroup = -1;
  19683. /**
  19684. * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))
  19685. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19686. */
  19687. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  19688. /**
  19689. * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))
  19690. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19691. */
  19692. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  19693. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19694. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19695. // Edges
  19696. /**
  19697. * Defines edge width used when edgesRenderer is enabled
  19698. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19699. */
  19700. _this.edgesWidth = 1;
  19701. /**
  19702. * Defines edge color used when edgesRenderer is enabled
  19703. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19704. */
  19705. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  19706. // Cache
  19707. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  19708. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  19709. /** @hidden */
  19710. _this._renderId = 0;
  19711. /** @hidden */
  19712. _this._intersectionsInProgress = new Array();
  19713. /** @hidden */
  19714. _this._unIndexed = false;
  19715. /** @hidden */
  19716. _this._lightSources = new Array();
  19717. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  19718. if (collidedMesh === void 0) { collidedMesh = null; }
  19719. //TODO move this to the collision coordinator!
  19720. if (_this.getScene().workerCollisions)
  19721. newPosition.multiplyInPlace(_this._collider._radius);
  19722. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  19723. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  19724. _this.position.addInPlace(_this._diffPositionForCollisions);
  19725. }
  19726. if (collidedMesh) {
  19727. _this.onCollideObservable.notifyObservers(collidedMesh);
  19728. }
  19729. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  19730. };
  19731. _this.getScene().addMesh(_this);
  19732. _this._resyncLightSources();
  19733. return _this;
  19734. }
  19735. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  19736. /**
  19737. * No billboard
  19738. */
  19739. get: function () {
  19740. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  19741. },
  19742. enumerable: true,
  19743. configurable: true
  19744. });
  19745. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  19746. /** Billboard on X axis */
  19747. get: function () {
  19748. return BABYLON.TransformNode.BILLBOARDMODE_X;
  19749. },
  19750. enumerable: true,
  19751. configurable: true
  19752. });
  19753. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  19754. /** Billboard on Y axis */
  19755. get: function () {
  19756. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  19757. },
  19758. enumerable: true,
  19759. configurable: true
  19760. });
  19761. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  19762. /** Billboard on Z axis */
  19763. get: function () {
  19764. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  19765. },
  19766. enumerable: true,
  19767. configurable: true
  19768. });
  19769. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  19770. /** Billboard on all axes */
  19771. get: function () {
  19772. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  19773. },
  19774. enumerable: true,
  19775. configurable: true
  19776. });
  19777. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  19778. /**
  19779. * Gets the number of facets in the mesh
  19780. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19781. */
  19782. get: function () {
  19783. return this._facetNb;
  19784. },
  19785. enumerable: true,
  19786. configurable: true
  19787. });
  19788. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  19789. /**
  19790. * Gets or set the number (integer) of subdivisions per axis in the partioning space
  19791. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19792. */
  19793. get: function () {
  19794. return this._partitioningSubdivisions;
  19795. },
  19796. set: function (nb) {
  19797. this._partitioningSubdivisions = nb;
  19798. },
  19799. enumerable: true,
  19800. configurable: true
  19801. });
  19802. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  19803. /**
  19804. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  19805. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box
  19806. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19807. */
  19808. get: function () {
  19809. return this._partitioningBBoxRatio;
  19810. },
  19811. set: function (ratio) {
  19812. this._partitioningBBoxRatio = ratio;
  19813. },
  19814. enumerable: true,
  19815. configurable: true
  19816. });
  19817. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  19818. /**
  19819. * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.
  19820. * Works only for updatable meshes.
  19821. * Doesn't work with multi-materials
  19822. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19823. */
  19824. get: function () {
  19825. return this._facetDepthSort;
  19826. },
  19827. set: function (sort) {
  19828. this._facetDepthSort = sort;
  19829. },
  19830. enumerable: true,
  19831. configurable: true
  19832. });
  19833. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  19834. /**
  19835. * The location (Vector3) where the facet depth sort must be computed from.
  19836. * By default, the active camera position.
  19837. * Used only when facet depth sort is enabled
  19838. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19839. */
  19840. get: function () {
  19841. return this._facetDepthSortFrom;
  19842. },
  19843. set: function (location) {
  19844. this._facetDepthSortFrom = location;
  19845. },
  19846. enumerable: true,
  19847. configurable: true
  19848. });
  19849. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  19850. /**
  19851. * gets a boolean indicating if facetData is enabled
  19852. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19853. */
  19854. get: function () {
  19855. return this._facetDataEnabled;
  19856. },
  19857. enumerable: true,
  19858. configurable: true
  19859. });
  19860. /** @hidden */
  19861. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  19862. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  19863. return false;
  19864. }
  19865. this._markSubMeshesAsMiscDirty();
  19866. return true;
  19867. };
  19868. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  19869. /** Set a function to call when this mesh collides with another one */
  19870. set: function (callback) {
  19871. if (this._onCollideObserver) {
  19872. this.onCollideObservable.remove(this._onCollideObserver);
  19873. }
  19874. this._onCollideObserver = this.onCollideObservable.add(callback);
  19875. },
  19876. enumerable: true,
  19877. configurable: true
  19878. });
  19879. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  19880. /** Set a function to call when the collision's position changes */
  19881. set: function (callback) {
  19882. if (this._onCollisionPositionChangeObserver) {
  19883. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  19884. }
  19885. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  19886. },
  19887. enumerable: true,
  19888. configurable: true
  19889. });
  19890. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  19891. /**
  19892. * 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
  19893. * @see http://doc.babylonjs.com/features/occlusionquery
  19894. */
  19895. get: function () {
  19896. return this._isOccluded;
  19897. },
  19898. set: function (value) {
  19899. this._isOccluded = value;
  19900. },
  19901. enumerable: true,
  19902. configurable: true
  19903. });
  19904. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  19905. /**
  19906. * Flag to check the progress status of the query
  19907. * @see http://doc.babylonjs.com/features/occlusionquery
  19908. */
  19909. get: function () {
  19910. return this._isOcclusionQueryInProgress;
  19911. },
  19912. enumerable: true,
  19913. configurable: true
  19914. });
  19915. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  19916. /**
  19917. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19918. */
  19919. get: function () {
  19920. return this._visibility;
  19921. },
  19922. /**
  19923. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19924. */
  19925. set: function (value) {
  19926. if (this._visibility === value) {
  19927. return;
  19928. }
  19929. this._visibility = value;
  19930. this._markSubMeshesAsMiscDirty();
  19931. },
  19932. enumerable: true,
  19933. configurable: true
  19934. });
  19935. Object.defineProperty(AbstractMesh.prototype, "material", {
  19936. /** Gets or sets current material */
  19937. get: function () {
  19938. return this._material;
  19939. },
  19940. set: function (value) {
  19941. if (this._material === value) {
  19942. return;
  19943. }
  19944. this._material = value;
  19945. if (this.onMaterialChangedObservable.hasObservers) {
  19946. this.onMaterialChangedObservable.notifyObservers(this);
  19947. }
  19948. if (!this.subMeshes) {
  19949. return;
  19950. }
  19951. this._unBindEffect();
  19952. },
  19953. enumerable: true,
  19954. configurable: true
  19955. });
  19956. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  19957. /**
  19958. * Gets or sets a boolean indicating that this mesh can receive realtime shadows
  19959. * @see http://doc.babylonjs.com/babylon101/shadows
  19960. */
  19961. get: function () {
  19962. return this._receiveShadows;
  19963. },
  19964. set: function (value) {
  19965. if (this._receiveShadows === value) {
  19966. return;
  19967. }
  19968. this._receiveShadows = value;
  19969. this._markSubMeshesAsLightDirty();
  19970. },
  19971. enumerable: true,
  19972. configurable: true
  19973. });
  19974. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  19975. /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */
  19976. get: function () {
  19977. return this._hasVertexAlpha;
  19978. },
  19979. set: function (value) {
  19980. if (this._hasVertexAlpha === value) {
  19981. return;
  19982. }
  19983. this._hasVertexAlpha = value;
  19984. this._markSubMeshesAsAttributesDirty();
  19985. this._markSubMeshesAsMiscDirty();
  19986. },
  19987. enumerable: true,
  19988. configurable: true
  19989. });
  19990. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  19991. /** 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) */
  19992. get: function () {
  19993. return this._useVertexColors;
  19994. },
  19995. set: function (value) {
  19996. if (this._useVertexColors === value) {
  19997. return;
  19998. }
  19999. this._useVertexColors = value;
  20000. this._markSubMeshesAsAttributesDirty();
  20001. },
  20002. enumerable: true,
  20003. configurable: true
  20004. });
  20005. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  20006. /**
  20007. * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)
  20008. */
  20009. get: function () {
  20010. return this._computeBonesUsingShaders;
  20011. },
  20012. set: function (value) {
  20013. if (this._computeBonesUsingShaders === value) {
  20014. return;
  20015. }
  20016. this._computeBonesUsingShaders = value;
  20017. this._markSubMeshesAsAttributesDirty();
  20018. },
  20019. enumerable: true,
  20020. configurable: true
  20021. });
  20022. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  20023. /** Gets or sets the number of allowed bone influences per vertex (4 by default) */
  20024. get: function () {
  20025. return this._numBoneInfluencers;
  20026. },
  20027. set: function (value) {
  20028. if (this._numBoneInfluencers === value) {
  20029. return;
  20030. }
  20031. this._numBoneInfluencers = value;
  20032. this._markSubMeshesAsAttributesDirty();
  20033. },
  20034. enumerable: true,
  20035. configurable: true
  20036. });
  20037. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  20038. /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */
  20039. get: function () {
  20040. return this._applyFog;
  20041. },
  20042. set: function (value) {
  20043. if (this._applyFog === value) {
  20044. return;
  20045. }
  20046. this._applyFog = value;
  20047. this._markSubMeshesAsMiscDirty();
  20048. },
  20049. enumerable: true,
  20050. configurable: true
  20051. });
  20052. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  20053. /**
  20054. * Gets or sets the current layer mask (default is 0x0FFFFFFF)
  20055. * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures
  20056. */
  20057. get: function () {
  20058. return this._layerMask;
  20059. },
  20060. set: function (value) {
  20061. if (value === this._layerMask) {
  20062. return;
  20063. }
  20064. this._layerMask = value;
  20065. this._resyncLightSources();
  20066. },
  20067. enumerable: true,
  20068. configurable: true
  20069. });
  20070. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  20071. /**
  20072. * Gets or sets a collision mask used to mask collisions (default is -1).
  20073. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  20074. */
  20075. get: function () {
  20076. return this._collisionMask;
  20077. },
  20078. set: function (mask) {
  20079. this._collisionMask = !isNaN(mask) ? mask : -1;
  20080. },
  20081. enumerable: true,
  20082. configurable: true
  20083. });
  20084. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  20085. /**
  20086. * Gets or sets the current collision group mask (-1 by default).
  20087. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  20088. */
  20089. get: function () {
  20090. return this._collisionGroup;
  20091. },
  20092. set: function (mask) {
  20093. this._collisionGroup = !isNaN(mask) ? mask : -1;
  20094. },
  20095. enumerable: true,
  20096. configurable: true
  20097. });
  20098. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  20099. /** @hidden */
  20100. get: function () {
  20101. return null;
  20102. },
  20103. enumerable: true,
  20104. configurable: true
  20105. });
  20106. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  20107. get: function () {
  20108. return this._skeleton;
  20109. },
  20110. /**
  20111. * Gets or sets a skeleton to apply skining transformations
  20112. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  20113. */
  20114. set: function (value) {
  20115. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  20116. this._skeleton._unregisterMeshWithPoseMatrix(this);
  20117. }
  20118. if (value && value.needInitialSkinMatrix) {
  20119. value._registerMeshWithPoseMatrix(this);
  20120. }
  20121. this._skeleton = value;
  20122. if (!this._skeleton) {
  20123. this._bonesTransformMatrices = null;
  20124. }
  20125. this._markSubMeshesAsAttributesDirty();
  20126. },
  20127. enumerable: true,
  20128. configurable: true
  20129. });
  20130. /**
  20131. * Returns the string "AbstractMesh"
  20132. * @returns "AbstractMesh"
  20133. */
  20134. AbstractMesh.prototype.getClassName = function () {
  20135. return "AbstractMesh";
  20136. };
  20137. /**
  20138. * Gets a string representation of the current mesh
  20139. * @param fullDetails defines a boolean indicating if full details must be included
  20140. * @returns a string representation of the current mesh
  20141. */
  20142. AbstractMesh.prototype.toString = function (fullDetails) {
  20143. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  20144. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  20145. if (this._skeleton) {
  20146. ret += ", skeleton: " + this._skeleton.name;
  20147. }
  20148. if (fullDetails) {
  20149. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  20150. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  20151. }
  20152. return ret;
  20153. };
  20154. /** @hidden */
  20155. AbstractMesh.prototype._rebuild = function () {
  20156. if (this._occlusionQuery) {
  20157. this._occlusionQuery = null;
  20158. }
  20159. if (this._edgesRenderer) {
  20160. this._edgesRenderer._rebuild();
  20161. }
  20162. if (!this.subMeshes) {
  20163. return;
  20164. }
  20165. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20166. var subMesh = _a[_i];
  20167. subMesh._rebuild();
  20168. }
  20169. };
  20170. /** @hidden */
  20171. AbstractMesh.prototype._resyncLightSources = function () {
  20172. this._lightSources.length = 0;
  20173. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  20174. var light = _a[_i];
  20175. if (!light.isEnabled()) {
  20176. continue;
  20177. }
  20178. if (light.canAffectMesh(this)) {
  20179. this._lightSources.push(light);
  20180. }
  20181. }
  20182. this._markSubMeshesAsLightDirty();
  20183. };
  20184. /** @hidden */
  20185. AbstractMesh.prototype._resyncLighSource = function (light) {
  20186. var isIn = light.isEnabled() && light.canAffectMesh(this);
  20187. var index = this._lightSources.indexOf(light);
  20188. if (index === -1) {
  20189. if (!isIn) {
  20190. return;
  20191. }
  20192. this._lightSources.push(light);
  20193. }
  20194. else {
  20195. if (isIn) {
  20196. return;
  20197. }
  20198. this._lightSources.splice(index, 1);
  20199. }
  20200. this._markSubMeshesAsLightDirty();
  20201. };
  20202. /** @hidden */
  20203. AbstractMesh.prototype._unBindEffect = function () {
  20204. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20205. var subMesh = _a[_i];
  20206. subMesh.setEffect(null);
  20207. }
  20208. };
  20209. /** @hidden */
  20210. AbstractMesh.prototype._removeLightSource = function (light) {
  20211. var index = this._lightSources.indexOf(light);
  20212. if (index === -1) {
  20213. return;
  20214. }
  20215. this._lightSources.splice(index, 1);
  20216. this._markSubMeshesAsLightDirty();
  20217. };
  20218. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  20219. if (!this.subMeshes) {
  20220. return;
  20221. }
  20222. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20223. var subMesh = _a[_i];
  20224. if (subMesh._materialDefines) {
  20225. func(subMesh._materialDefines);
  20226. }
  20227. }
  20228. };
  20229. /** @hidden */
  20230. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  20231. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  20232. };
  20233. /** @hidden */
  20234. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  20235. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  20236. };
  20237. /** @hidden */
  20238. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  20239. if (!this.subMeshes) {
  20240. return;
  20241. }
  20242. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20243. var subMesh = _a[_i];
  20244. var material = subMesh.getMaterial();
  20245. if (material) {
  20246. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  20247. }
  20248. }
  20249. };
  20250. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  20251. /**
  20252. * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0)
  20253. */
  20254. get: function () {
  20255. return this._scaling;
  20256. },
  20257. set: function (newScaling) {
  20258. this._scaling = newScaling;
  20259. if (this.physicsImpostor) {
  20260. this.physicsImpostor.forceUpdate();
  20261. }
  20262. },
  20263. enumerable: true,
  20264. configurable: true
  20265. });
  20266. // Methods
  20267. /**
  20268. * Disables the mesh edge rendering mode
  20269. * @returns the currentAbstractMesh
  20270. */
  20271. AbstractMesh.prototype.disableEdgesRendering = function () {
  20272. if (this._edgesRenderer) {
  20273. this._edgesRenderer.dispose();
  20274. this._edgesRenderer = null;
  20275. }
  20276. return this;
  20277. };
  20278. /**
  20279. * Enables the edge rendering mode on the mesh.
  20280. * This mode makes the mesh edges visible
  20281. * @param epsilon defines the maximal distance between two angles to detect a face
  20282. * @param checkVerticesInsteadOfIndices indicates that we should check vertex list directly instead of faces
  20283. * @returns the currentAbstractMesh
  20284. * @see https://www.babylonjs-playground.com/#19O9TU#0
  20285. */
  20286. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  20287. if (epsilon === void 0) { epsilon = 0.95; }
  20288. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  20289. this.disableEdgesRendering();
  20290. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  20291. return this;
  20292. };
  20293. Object.defineProperty(AbstractMesh.prototype, "edgesRenderer", {
  20294. /**
  20295. * Gets the edgesRenderer associated with the mesh
  20296. */
  20297. get: function () {
  20298. return this._edgesRenderer;
  20299. },
  20300. enumerable: true,
  20301. configurable: true
  20302. });
  20303. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  20304. /**
  20305. * Returns true if the mesh is blocked. Implemented by child classes
  20306. */
  20307. get: function () {
  20308. return false;
  20309. },
  20310. enumerable: true,
  20311. configurable: true
  20312. });
  20313. /**
  20314. * Returns the mesh itself by default. Implemented by child classes
  20315. * @param camera defines the camera to use to pick the right LOD level
  20316. * @returns the currentAbstractMesh
  20317. */
  20318. AbstractMesh.prototype.getLOD = function (camera) {
  20319. return this;
  20320. };
  20321. /**
  20322. * Returns 0 by default. Implemented by child classes
  20323. * @returns an integer
  20324. */
  20325. AbstractMesh.prototype.getTotalVertices = function () {
  20326. return 0;
  20327. };
  20328. /**
  20329. * Returns null by default. Implemented by child classes
  20330. * @returns null
  20331. */
  20332. AbstractMesh.prototype.getIndices = function () {
  20333. return null;
  20334. };
  20335. /**
  20336. * Returns the array of the requested vertex data kind. Implemented by child classes
  20337. * @param kind defines the vertex data kind to use
  20338. * @returns null
  20339. */
  20340. AbstractMesh.prototype.getVerticesData = function (kind) {
  20341. return null;
  20342. };
  20343. /**
  20344. * Sets the vertex data of the mesh geometry for the requested `kind`.
  20345. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  20346. * Note that a new underlying VertexBuffer object is created each call.
  20347. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  20348. * @param kind defines vertex data kind:
  20349. * * BABYLON.VertexBuffer.PositionKind
  20350. * * BABYLON.VertexBuffer.UVKind
  20351. * * BABYLON.VertexBuffer.UV2Kind
  20352. * * BABYLON.VertexBuffer.UV3Kind
  20353. * * BABYLON.VertexBuffer.UV4Kind
  20354. * * BABYLON.VertexBuffer.UV5Kind
  20355. * * BABYLON.VertexBuffer.UV6Kind
  20356. * * BABYLON.VertexBuffer.ColorKind
  20357. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20358. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20359. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20360. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20361. * @param data defines the data source
  20362. * @param updatable defines if the data must be flagged as updatable (or static)
  20363. * @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
  20364. * @returns the current mesh
  20365. */
  20366. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  20367. return this;
  20368. };
  20369. /**
  20370. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  20371. * If the mesh has no geometry, it is simply returned as it is.
  20372. * @param kind defines vertex data kind:
  20373. * * BABYLON.VertexBuffer.PositionKind
  20374. * * BABYLON.VertexBuffer.UVKind
  20375. * * BABYLON.VertexBuffer.UV2Kind
  20376. * * BABYLON.VertexBuffer.UV3Kind
  20377. * * BABYLON.VertexBuffer.UV4Kind
  20378. * * BABYLON.VertexBuffer.UV5Kind
  20379. * * BABYLON.VertexBuffer.UV6Kind
  20380. * * BABYLON.VertexBuffer.ColorKind
  20381. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20382. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20383. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20384. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20385. * @param data defines the data source
  20386. * @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
  20387. * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh
  20388. * @returns the current mesh
  20389. */
  20390. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20391. return this;
  20392. };
  20393. /**
  20394. * Sets the mesh indices,
  20395. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20396. * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  20397. * @param totalVertices Defines the total number of vertices
  20398. * @returns the current mesh
  20399. */
  20400. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  20401. return this;
  20402. };
  20403. /**
  20404. * Gets a boolean indicating if specific vertex data is present
  20405. * @param kind defines the vertex data kind to use
  20406. * @returns true is data kind is present
  20407. */
  20408. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  20409. return false;
  20410. };
  20411. /**
  20412. * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined
  20413. * @returns a BoundingInfo
  20414. */
  20415. AbstractMesh.prototype.getBoundingInfo = function () {
  20416. if (this._masterMesh) {
  20417. return this._masterMesh.getBoundingInfo();
  20418. }
  20419. if (!this._boundingInfo) {
  20420. // this._boundingInfo is being created here
  20421. this._updateBoundingInfo();
  20422. }
  20423. // cannot be null.
  20424. return this._boundingInfo;
  20425. };
  20426. /**
  20427. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)
  20428. * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box
  20429. * @returns the current mesh
  20430. */
  20431. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  20432. if (includeDescendants === void 0) { includeDescendants = true; }
  20433. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  20434. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  20435. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  20436. if (maxDimension === 0) {
  20437. return this;
  20438. }
  20439. var scale = 1 / maxDimension;
  20440. this.scaling.scaleInPlace(scale);
  20441. return this;
  20442. };
  20443. /**
  20444. * Overwrite the current bounding info
  20445. * @param boundingInfo defines the new bounding info
  20446. * @returns the current mesh
  20447. */
  20448. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  20449. this._boundingInfo = boundingInfo;
  20450. return this;
  20451. };
  20452. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  20453. /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */
  20454. get: function () {
  20455. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  20456. },
  20457. enumerable: true,
  20458. configurable: true
  20459. });
  20460. /** @hidden */
  20461. AbstractMesh.prototype._preActivate = function () {
  20462. };
  20463. /** @hidden */
  20464. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  20465. };
  20466. /** @hidden */
  20467. AbstractMesh.prototype._activate = function (renderId) {
  20468. this._renderId = renderId;
  20469. };
  20470. /**
  20471. * Gets the current world matrix
  20472. * @returns a Matrix
  20473. */
  20474. AbstractMesh.prototype.getWorldMatrix = function () {
  20475. if (this._masterMesh) {
  20476. return this._masterMesh.getWorldMatrix();
  20477. }
  20478. return _super.prototype.getWorldMatrix.call(this);
  20479. };
  20480. /** @hidden */
  20481. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  20482. if (this._masterMesh) {
  20483. return this._masterMesh._getWorldMatrixDeterminant();
  20484. }
  20485. return _super.prototype._getWorldMatrixDeterminant.call(this);
  20486. };
  20487. // ================================== Point of View Movement =================================
  20488. /**
  20489. * Perform relative position change from the point of view of behind the front of the mesh.
  20490. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20491. * Supports definition of mesh facing forward or backward
  20492. * @param amountRight defines the distance on the right axis
  20493. * @param amountUp defines the distance on the up axis
  20494. * @param amountForward defines the distance on the forward axis
  20495. * @returns the current mesh
  20496. */
  20497. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  20498. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  20499. return this;
  20500. };
  20501. /**
  20502. * Calculate relative position change from the point of view of behind the front of the mesh.
  20503. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20504. * Supports definition of mesh facing forward or backward
  20505. * @param amountRight defines the distance on the right axis
  20506. * @param amountUp defines the distance on the up axis
  20507. * @param amountForward defines the distance on the forward axis
  20508. * @returns the new displacement vector
  20509. */
  20510. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  20511. var rotMatrix = new BABYLON.Matrix();
  20512. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  20513. rotQuaternion.toRotationMatrix(rotMatrix);
  20514. var translationDelta = BABYLON.Vector3.Zero();
  20515. var defForwardMult = this.definedFacingForward ? -1 : 1;
  20516. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  20517. return translationDelta;
  20518. };
  20519. // ================================== Point of View Rotation =================================
  20520. /**
  20521. * Perform relative rotation change from the point of view of behind the front of the mesh.
  20522. * Supports definition of mesh facing forward or backward
  20523. * @param flipBack defines the flip
  20524. * @param twirlClockwise defines the twirl
  20525. * @param tiltRight defines the tilt
  20526. * @returns the current mesh
  20527. */
  20528. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20529. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  20530. return this;
  20531. };
  20532. /**
  20533. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  20534. * Supports definition of mesh facing forward or backward.
  20535. * @param flipBack defines the flip
  20536. * @param twirlClockwise defines the twirl
  20537. * @param tiltRight defines the tilt
  20538. * @returns the new rotation vector
  20539. */
  20540. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20541. var defForwardMult = this.definedFacingForward ? 1 : -1;
  20542. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  20543. };
  20544. /**
  20545. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  20546. * @param includeDescendants Include bounding info from descendants as well (true by default)
  20547. * @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
  20548. * @returns the new bounding vectors
  20549. */
  20550. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants, predicate) {
  20551. if (includeDescendants === void 0) { includeDescendants = true; }
  20552. if (predicate === void 0) { predicate = null; }
  20553. // Ensures that all world matrix will be recomputed.
  20554. this.getScene().incrementRenderId();
  20555. this.computeWorldMatrix(true);
  20556. var min;
  20557. var max;
  20558. var boundingInfo = this.getBoundingInfo();
  20559. if (!this.subMeshes) {
  20560. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20561. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  20562. }
  20563. else {
  20564. min = boundingInfo.boundingBox.minimumWorld;
  20565. max = boundingInfo.boundingBox.maximumWorld;
  20566. }
  20567. if (includeDescendants) {
  20568. var descendants = this.getDescendants(false);
  20569. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  20570. var descendant = descendants_1[_i];
  20571. var childMesh = descendant;
  20572. childMesh.computeWorldMatrix(true);
  20573. // Filters meshes based on custom predicate function.
  20574. if (predicate && !predicate(childMesh)) {
  20575. continue;
  20576. }
  20577. //make sure we have the needed params to get mix and max
  20578. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  20579. continue;
  20580. }
  20581. var childBoundingInfo = childMesh.getBoundingInfo();
  20582. var boundingBox = childBoundingInfo.boundingBox;
  20583. var minBox = boundingBox.minimumWorld;
  20584. var maxBox = boundingBox.maximumWorld;
  20585. BABYLON.Tools.CheckExtends(minBox, min, max);
  20586. BABYLON.Tools.CheckExtends(maxBox, min, max);
  20587. }
  20588. }
  20589. return {
  20590. min: min,
  20591. max: max
  20592. };
  20593. };
  20594. /** @hidden */
  20595. AbstractMesh.prototype._updateBoundingInfo = function () {
  20596. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  20597. this._boundingInfo.update(this.worldMatrixFromCache);
  20598. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  20599. return this;
  20600. };
  20601. /** @hidden */
  20602. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  20603. if (!this.subMeshes) {
  20604. return this;
  20605. }
  20606. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  20607. var subMesh = this.subMeshes[subIndex];
  20608. if (!subMesh.IsGlobal) {
  20609. subMesh.updateBoundingInfo(matrix);
  20610. }
  20611. }
  20612. return this;
  20613. };
  20614. /** @hidden */
  20615. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  20616. // Bounding info
  20617. this._updateBoundingInfo();
  20618. };
  20619. /**
  20620. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  20621. * A mesh is in the frustum if its bounding box intersects the frustum
  20622. * @param frustumPlanes defines the frustum to test
  20623. * @returns true if the mesh is in the frustum planes
  20624. */
  20625. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  20626. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  20627. };
  20628. /**
  20629. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  20630. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  20631. * @param frustumPlanes defines the frustum to test
  20632. * @returns true if the mesh is completely in the frustum planes
  20633. */
  20634. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  20635. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  20636. };
  20637. /**
  20638. * True if the mesh intersects another mesh or a SolidParticle object
  20639. * @param mesh defines a target mesh or SolidParticle to test
  20640. * @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)
  20641. * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  20642. * @returns true if there is an intersection
  20643. */
  20644. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  20645. if (precise === void 0) { precise = false; }
  20646. if (!this._boundingInfo || !mesh._boundingInfo) {
  20647. return false;
  20648. }
  20649. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  20650. return true;
  20651. }
  20652. if (includeDescendants) {
  20653. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  20654. var child = _a[_i];
  20655. if (child.intersectsMesh(mesh, precise, true)) {
  20656. return true;
  20657. }
  20658. }
  20659. }
  20660. return false;
  20661. };
  20662. /**
  20663. * Returns true if the passed point (Vector3) is inside the mesh bounding box
  20664. * @param point defines the point to test
  20665. * @returns true if there is an intersection
  20666. */
  20667. AbstractMesh.prototype.intersectsPoint = function (point) {
  20668. if (!this._boundingInfo) {
  20669. return false;
  20670. }
  20671. return this._boundingInfo.intersectsPoint(point);
  20672. };
  20673. /**
  20674. * Gets the current physics impostor
  20675. * @see http://doc.babylonjs.com/features/physics_engine
  20676. * @returns a physics impostor or null
  20677. */
  20678. AbstractMesh.prototype.getPhysicsImpostor = function () {
  20679. return this.physicsImpostor;
  20680. };
  20681. /**
  20682. * Gets the position of the current mesh in camera space
  20683. * @param camera defines the camera to use
  20684. * @returns a position
  20685. */
  20686. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  20687. if (camera === void 0) { camera = null; }
  20688. if (!camera) {
  20689. camera = this.getScene().activeCamera;
  20690. }
  20691. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  20692. };
  20693. /**
  20694. * Returns the distance from the mesh to the active camera
  20695. * @param camera defines the camera to use
  20696. * @returns the distance
  20697. */
  20698. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  20699. if (camera === void 0) { camera = null; }
  20700. if (!camera) {
  20701. camera = this.getScene().activeCamera;
  20702. }
  20703. return this.absolutePosition.subtract(camera.position).length();
  20704. };
  20705. /**
  20706. * Apply a physic impulse to the mesh
  20707. * @param force defines the force to apply
  20708. * @param contactPoint defines where to apply the force
  20709. * @returns the current mesh
  20710. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  20711. */
  20712. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  20713. if (!this.physicsImpostor) {
  20714. return this;
  20715. }
  20716. this.physicsImpostor.applyImpulse(force, contactPoint);
  20717. return this;
  20718. };
  20719. /**
  20720. * Creates a physic joint between two meshes
  20721. * @param otherMesh defines the other mesh to use
  20722. * @param pivot1 defines the pivot to use on this mesh
  20723. * @param pivot2 defines the pivot to use on the other mesh
  20724. * @param options defines additional options (can be plugin dependent)
  20725. * @returns the current mesh
  20726. * @see https://www.babylonjs-playground.com/#0BS5U0#0
  20727. */
  20728. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  20729. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  20730. return this;
  20731. }
  20732. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  20733. mainPivot: pivot1,
  20734. connectedPivot: pivot2,
  20735. nativeParams: options
  20736. });
  20737. return this;
  20738. };
  20739. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  20740. // Collisions
  20741. /**
  20742. * Gets or sets a boolean indicating that this mesh can be used in the collision engine
  20743. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20744. */
  20745. get: function () {
  20746. return this._checkCollisions;
  20747. },
  20748. set: function (collisionEnabled) {
  20749. this._checkCollisions = collisionEnabled;
  20750. if (this.getScene().workerCollisions) {
  20751. this.getScene().collisionCoordinator.onMeshUpdated(this);
  20752. }
  20753. },
  20754. enumerable: true,
  20755. configurable: true
  20756. });
  20757. Object.defineProperty(AbstractMesh.prototype, "collider", {
  20758. /**
  20759. * Gets Collider object used to compute collisions (not physics)
  20760. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20761. */
  20762. get: function () {
  20763. return this._collider;
  20764. },
  20765. enumerable: true,
  20766. configurable: true
  20767. });
  20768. /**
  20769. * Move the mesh using collision engine
  20770. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20771. * @param displacement defines the requested displacement vector
  20772. * @returns the current mesh
  20773. */
  20774. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  20775. var globalPosition = this.getAbsolutePosition();
  20776. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  20777. if (!this._collider) {
  20778. this._collider = new BABYLON.Collider();
  20779. }
  20780. this._collider._radius = this.ellipsoid;
  20781. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  20782. return this;
  20783. };
  20784. // Submeshes octree
  20785. /**
  20786. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  20787. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  20788. * @param maxCapacity defines the maximum size of each block (64 by default)
  20789. * @param maxDepth defines the maximum depth to use (no more than 2 levels by default)
  20790. * @returns the new octree
  20791. * @see https://www.babylonjs-playground.com/#NA4OQ#12
  20792. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  20793. */
  20794. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  20795. if (maxCapacity === void 0) { maxCapacity = 64; }
  20796. if (maxDepth === void 0) { maxDepth = 2; }
  20797. if (!this._submeshesOctree) {
  20798. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  20799. }
  20800. this.computeWorldMatrix(true);
  20801. var boundingInfo = this.getBoundingInfo();
  20802. // Update octree
  20803. var bbox = boundingInfo.boundingBox;
  20804. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  20805. return this._submeshesOctree;
  20806. };
  20807. // Collisions
  20808. /** @hidden */
  20809. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  20810. this._generatePointsArray();
  20811. if (!this._positions) {
  20812. return this;
  20813. }
  20814. // Transformation
  20815. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  20816. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  20817. subMesh._lastColliderWorldVertices = [];
  20818. subMesh._trianglePlanes = [];
  20819. var start = subMesh.verticesStart;
  20820. var end = (subMesh.verticesStart + subMesh.verticesCount);
  20821. for (var i = start; i < end; i++) {
  20822. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  20823. }
  20824. }
  20825. // Collide
  20826. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  20827. if (collider.collisionFound) {
  20828. collider.collidedMesh = this;
  20829. }
  20830. return this;
  20831. };
  20832. /** @hidden */
  20833. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  20834. var subMeshes;
  20835. var len;
  20836. // Octrees
  20837. if (this._submeshesOctree && this.useOctreeForCollisions) {
  20838. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  20839. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  20840. len = intersections.length;
  20841. subMeshes = intersections.data;
  20842. }
  20843. else {
  20844. subMeshes = this.subMeshes;
  20845. len = subMeshes.length;
  20846. }
  20847. for (var index = 0; index < len; index++) {
  20848. var subMesh = subMeshes[index];
  20849. // Bounding test
  20850. if (len > 1 && !subMesh._checkCollision(collider))
  20851. continue;
  20852. this._collideForSubMesh(subMesh, transformMatrix, collider);
  20853. }
  20854. return this;
  20855. };
  20856. /** @hidden */
  20857. AbstractMesh.prototype._checkCollision = function (collider) {
  20858. // Bounding box test
  20859. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  20860. return this;
  20861. // Transformation matrix
  20862. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  20863. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  20864. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  20865. return this;
  20866. };
  20867. // Picking
  20868. /** @hidden */
  20869. AbstractMesh.prototype._generatePointsArray = function () {
  20870. return false;
  20871. };
  20872. /**
  20873. * Checks if the passed Ray intersects with the mesh
  20874. * @param ray defines the ray to use
  20875. * @param fastCheck defines if fast mode (but less precise) must be used (false by default)
  20876. * @returns the picking info
  20877. * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  20878. */
  20879. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  20880. var pickingInfo = new BABYLON.PickingInfo();
  20881. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  20882. return pickingInfo;
  20883. }
  20884. if (!this._generatePointsArray()) {
  20885. return pickingInfo;
  20886. }
  20887. var intersectInfo = null;
  20888. // Octrees
  20889. var subMeshes;
  20890. var len;
  20891. if (this._submeshesOctree && this.useOctreeForPicking) {
  20892. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  20893. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  20894. len = intersections.length;
  20895. subMeshes = intersections.data;
  20896. }
  20897. else {
  20898. subMeshes = this.subMeshes;
  20899. len = subMeshes.length;
  20900. }
  20901. for (var index = 0; index < len; index++) {
  20902. var subMesh = subMeshes[index];
  20903. // Bounding test
  20904. if (len > 1 && !subMesh.canIntersects(ray))
  20905. continue;
  20906. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  20907. if (currentIntersectInfo) {
  20908. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  20909. intersectInfo = currentIntersectInfo;
  20910. intersectInfo.subMeshId = index;
  20911. if (fastCheck) {
  20912. break;
  20913. }
  20914. }
  20915. }
  20916. }
  20917. if (intersectInfo) {
  20918. // Get picked point
  20919. var world = this.getWorldMatrix();
  20920. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  20921. var direction = ray.direction.clone();
  20922. direction = direction.scale(intersectInfo.distance);
  20923. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  20924. var pickedPoint = worldOrigin.add(worldDirection);
  20925. // Return result
  20926. pickingInfo.hit = true;
  20927. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  20928. pickingInfo.pickedPoint = pickedPoint;
  20929. pickingInfo.pickedMesh = this;
  20930. pickingInfo.bu = intersectInfo.bu || 0;
  20931. pickingInfo.bv = intersectInfo.bv || 0;
  20932. pickingInfo.faceId = intersectInfo.faceId;
  20933. pickingInfo.subMeshId = intersectInfo.subMeshId;
  20934. return pickingInfo;
  20935. }
  20936. return pickingInfo;
  20937. };
  20938. /**
  20939. * Clones the current mesh
  20940. * @param name defines the mesh name
  20941. * @param newParent defines the new mesh parent
  20942. * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)
  20943. * @returns the new mesh
  20944. */
  20945. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  20946. return null;
  20947. };
  20948. /**
  20949. * Disposes all the submeshes of the current meshnp
  20950. * @returns the current mesh
  20951. */
  20952. AbstractMesh.prototype.releaseSubMeshes = function () {
  20953. if (this.subMeshes) {
  20954. while (this.subMeshes.length) {
  20955. this.subMeshes[0].dispose();
  20956. }
  20957. }
  20958. else {
  20959. this.subMeshes = new Array();
  20960. }
  20961. return this;
  20962. };
  20963. /**
  20964. * Releases resources associated with this abstract mesh.
  20965. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20966. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20967. */
  20968. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20969. var _this = this;
  20970. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20971. var index;
  20972. // Smart Array Retainers.
  20973. this.getScene().freeActiveMeshes();
  20974. this.getScene().freeRenderingGroups();
  20975. // Action manager
  20976. if (this.actionManager !== undefined && this.actionManager !== null) {
  20977. this.actionManager.dispose();
  20978. this.actionManager = null;
  20979. }
  20980. // Skeleton
  20981. this._skeleton = null;
  20982. // Physics
  20983. if (this.physicsImpostor) {
  20984. this.physicsImpostor.dispose( /*!doNotRecurse*/);
  20985. }
  20986. // Intersections in progress
  20987. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  20988. var other = this._intersectionsInProgress[index];
  20989. var pos = other._intersectionsInProgress.indexOf(this);
  20990. other._intersectionsInProgress.splice(pos, 1);
  20991. }
  20992. this._intersectionsInProgress = [];
  20993. // Lights
  20994. var lights = this.getScene().lights;
  20995. lights.forEach(function (light) {
  20996. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  20997. if (meshIndex !== -1) {
  20998. light.includedOnlyMeshes.splice(meshIndex, 1);
  20999. }
  21000. meshIndex = light.excludedMeshes.indexOf(_this);
  21001. if (meshIndex !== -1) {
  21002. light.excludedMeshes.splice(meshIndex, 1);
  21003. }
  21004. // Shadow generators
  21005. var generator = light.getShadowGenerator();
  21006. if (generator) {
  21007. var shadowMap = generator.getShadowMap();
  21008. if (shadowMap && shadowMap.renderList) {
  21009. meshIndex = shadowMap.renderList.indexOf(_this);
  21010. if (meshIndex !== -1) {
  21011. shadowMap.renderList.splice(meshIndex, 1);
  21012. }
  21013. }
  21014. }
  21015. });
  21016. // Edges
  21017. if (this._edgesRenderer) {
  21018. this._edgesRenderer.dispose();
  21019. this._edgesRenderer = null;
  21020. }
  21021. // SubMeshes
  21022. if (this.getClassName() !== "InstancedMesh") {
  21023. this.releaseSubMeshes();
  21024. }
  21025. // Octree
  21026. var sceneOctree = this.getScene().selectionOctree;
  21027. if (sceneOctree !== undefined && sceneOctree !== null) {
  21028. var index = sceneOctree.dynamicContent.indexOf(this);
  21029. if (index !== -1) {
  21030. sceneOctree.dynamicContent.splice(index, 1);
  21031. }
  21032. }
  21033. // Query
  21034. var engine = this.getScene().getEngine();
  21035. if (this._occlusionQuery) {
  21036. this._isOcclusionQueryInProgress = false;
  21037. engine.deleteQuery(this._occlusionQuery);
  21038. this._occlusionQuery = null;
  21039. }
  21040. // Engine
  21041. engine.wipeCaches();
  21042. // Remove from scene
  21043. this.getScene().removeMesh(this);
  21044. if (disposeMaterialAndTextures) {
  21045. if (this.material) {
  21046. this.material.dispose(false, true);
  21047. }
  21048. }
  21049. if (!doNotRecurse) {
  21050. // Particles
  21051. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  21052. if (this.getScene().particleSystems[index].emitter === this) {
  21053. this.getScene().particleSystems[index].dispose();
  21054. index--;
  21055. }
  21056. }
  21057. }
  21058. // facet data
  21059. if (this._facetDataEnabled) {
  21060. this.disableFacetData();
  21061. }
  21062. this.onAfterWorldMatrixUpdateObservable.clear();
  21063. this.onCollideObservable.clear();
  21064. this.onCollisionPositionChangeObservable.clear();
  21065. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21066. };
  21067. /**
  21068. * Adds the passed mesh as a child to the current mesh
  21069. * @param mesh defines the child mesh
  21070. * @returns the current mesh
  21071. */
  21072. AbstractMesh.prototype.addChild = function (mesh) {
  21073. mesh.setParent(this);
  21074. return this;
  21075. };
  21076. /**
  21077. * Removes the passed mesh from the current mesh children list
  21078. * @param mesh defines the child mesh
  21079. * @returns the current mesh
  21080. */
  21081. AbstractMesh.prototype.removeChild = function (mesh) {
  21082. mesh.setParent(null);
  21083. return this;
  21084. };
  21085. // Facet data
  21086. /** @hidden */
  21087. AbstractMesh.prototype._initFacetData = function () {
  21088. if (!this._facetNormals) {
  21089. this._facetNormals = new Array();
  21090. }
  21091. if (!this._facetPositions) {
  21092. this._facetPositions = new Array();
  21093. }
  21094. if (!this._facetPartitioning) {
  21095. this._facetPartitioning = new Array();
  21096. }
  21097. this._facetNb = (this.getIndices().length / 3) | 0;
  21098. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  21099. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  21100. for (var f = 0; f < this._facetNb; f++) {
  21101. this._facetNormals[f] = BABYLON.Vector3.Zero();
  21102. this._facetPositions[f] = BABYLON.Vector3.Zero();
  21103. }
  21104. this._facetDataEnabled = true;
  21105. return this;
  21106. };
  21107. /**
  21108. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  21109. * This method can be called within the render loop.
  21110. * 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
  21111. * @returns the current mesh
  21112. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21113. */
  21114. AbstractMesh.prototype.updateFacetData = function () {
  21115. if (!this._facetDataEnabled) {
  21116. this._initFacetData();
  21117. }
  21118. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21119. var indices = this.getIndices();
  21120. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21121. var bInfo = this.getBoundingInfo();
  21122. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  21123. // init arrays, matrix and sort function on first call
  21124. this._facetDepthSortEnabled = true;
  21125. if (indices instanceof Uint16Array) {
  21126. this._depthSortedIndices = new Uint16Array(indices);
  21127. }
  21128. else if (indices instanceof Uint32Array) {
  21129. this._depthSortedIndices = new Uint32Array(indices);
  21130. }
  21131. else {
  21132. var needs32bits = false;
  21133. for (var i = 0; i < indices.length; i++) {
  21134. if (indices[i] > 65535) {
  21135. needs32bits = true;
  21136. break;
  21137. }
  21138. }
  21139. if (needs32bits) {
  21140. this._depthSortedIndices = new Uint32Array(indices);
  21141. }
  21142. else {
  21143. this._depthSortedIndices = new Uint16Array(indices);
  21144. }
  21145. }
  21146. this._facetDepthSortFunction = function (f1, f2) {
  21147. return (f2.sqDistance - f1.sqDistance);
  21148. };
  21149. if (!this._facetDepthSortFrom) {
  21150. var camera = this.getScene().activeCamera;
  21151. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  21152. }
  21153. this._depthSortedFacets = [];
  21154. for (var f = 0; f < this._facetNb; f++) {
  21155. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  21156. this._depthSortedFacets.push(depthSortedFacet);
  21157. }
  21158. this._invertedMatrix = BABYLON.Matrix.Identity();
  21159. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  21160. }
  21161. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  21162. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  21163. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  21164. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  21165. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  21166. this._subDiv.max = this._partitioningSubdivisions;
  21167. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  21168. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  21169. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  21170. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  21171. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  21172. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  21173. // set the parameters for ComputeNormals()
  21174. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  21175. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  21176. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  21177. this._facetParameters.bInfo = bInfo;
  21178. this._facetParameters.bbSize = this._bbSize;
  21179. this._facetParameters.subDiv = this._subDiv;
  21180. this._facetParameters.ratio = this.partitioningBBoxRatio;
  21181. this._facetParameters.depthSort = this._facetDepthSort;
  21182. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  21183. this.computeWorldMatrix(true);
  21184. this._worldMatrix.invertToRef(this._invertedMatrix);
  21185. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  21186. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  21187. }
  21188. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  21189. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  21190. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  21191. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  21192. var l = (this._depthSortedIndices.length / 3) | 0;
  21193. for (var f = 0; f < l; f++) {
  21194. var sind = this._depthSortedFacets[f].ind;
  21195. this._depthSortedIndices[f * 3] = indices[sind];
  21196. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  21197. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  21198. }
  21199. this.updateIndices(this._depthSortedIndices);
  21200. }
  21201. return this;
  21202. };
  21203. /**
  21204. * Returns the facetLocalNormals array.
  21205. * The normals are expressed in the mesh local spac
  21206. * @returns an array of Vector3
  21207. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21208. */
  21209. AbstractMesh.prototype.getFacetLocalNormals = function () {
  21210. if (!this._facetNormals) {
  21211. this.updateFacetData();
  21212. }
  21213. return this._facetNormals;
  21214. };
  21215. /**
  21216. * Returns the facetLocalPositions array.
  21217. * The facet positions are expressed in the mesh local space
  21218. * @returns an array of Vector3
  21219. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21220. */
  21221. AbstractMesh.prototype.getFacetLocalPositions = function () {
  21222. if (!this._facetPositions) {
  21223. this.updateFacetData();
  21224. }
  21225. return this._facetPositions;
  21226. };
  21227. /**
  21228. * Returns the facetLocalPartioning array
  21229. * @returns an array of array of numbers
  21230. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21231. */
  21232. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  21233. if (!this._facetPartitioning) {
  21234. this.updateFacetData();
  21235. }
  21236. return this._facetPartitioning;
  21237. };
  21238. /**
  21239. * Returns the i-th facet position in the world system.
  21240. * This method allocates a new Vector3 per call
  21241. * @param i defines the facet index
  21242. * @returns a new Vector3
  21243. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21244. */
  21245. AbstractMesh.prototype.getFacetPosition = function (i) {
  21246. var pos = BABYLON.Vector3.Zero();
  21247. this.getFacetPositionToRef(i, pos);
  21248. return pos;
  21249. };
  21250. /**
  21251. * Sets the reference Vector3 with the i-th facet position in the world system
  21252. * @param i defines the facet index
  21253. * @param ref defines the target vector
  21254. * @returns the current mesh
  21255. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21256. */
  21257. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  21258. var localPos = (this.getFacetLocalPositions())[i];
  21259. var world = this.getWorldMatrix();
  21260. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  21261. return this;
  21262. };
  21263. /**
  21264. * Returns the i-th facet normal in the world system.
  21265. * This method allocates a new Vector3 per call
  21266. * @param i defines the facet index
  21267. * @returns a new Vector3
  21268. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21269. */
  21270. AbstractMesh.prototype.getFacetNormal = function (i) {
  21271. var norm = BABYLON.Vector3.Zero();
  21272. this.getFacetNormalToRef(i, norm);
  21273. return norm;
  21274. };
  21275. /**
  21276. * Sets the reference Vector3 with the i-th facet normal in the world system
  21277. * @param i defines the facet index
  21278. * @param ref defines the target vector
  21279. * @returns the current mesh
  21280. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21281. */
  21282. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  21283. var localNorm = (this.getFacetLocalNormals())[i];
  21284. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  21285. return this;
  21286. };
  21287. /**
  21288. * 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)
  21289. * @param x defines x coordinate
  21290. * @param y defines y coordinate
  21291. * @param z defines z coordinate
  21292. * @returns the array of facet indexes
  21293. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21294. */
  21295. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  21296. var bInfo = this.getBoundingInfo();
  21297. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  21298. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  21299. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  21300. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  21301. return null;
  21302. }
  21303. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  21304. };
  21305. /**
  21306. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found
  21307. * @param projected sets as the (x,y,z) world projection on the facet
  21308. * @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
  21309. * @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
  21310. * @param x defines x coordinate
  21311. * @param y defines y coordinate
  21312. * @param z defines z coordinate
  21313. * @returns the face index if found (or null instead)
  21314. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21315. */
  21316. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  21317. if (checkFace === void 0) { checkFace = false; }
  21318. if (facing === void 0) { facing = true; }
  21319. var world = this.getWorldMatrix();
  21320. var invMat = BABYLON.Tmp.Matrix[5];
  21321. world.invertToRef(invMat);
  21322. var invVect = BABYLON.Tmp.Vector3[8];
  21323. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  21324. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  21325. if (projected) {
  21326. // tranform the local computed projected vector to world coordinates
  21327. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  21328. }
  21329. return closest;
  21330. };
  21331. /**
  21332. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found
  21333. * @param projected sets as the (x,y,z) local projection on the facet
  21334. * @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
  21335. * @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
  21336. * @param x defines x coordinate
  21337. * @param y defines y coordinate
  21338. * @param z defines z coordinate
  21339. * @returns the face index if found (or null instead)
  21340. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21341. */
  21342. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  21343. if (checkFace === void 0) { checkFace = false; }
  21344. if (facing === void 0) { facing = true; }
  21345. var closest = null;
  21346. var tmpx = 0.0;
  21347. var tmpy = 0.0;
  21348. var tmpz = 0.0;
  21349. var d = 0.0; // tmp dot facet normal * facet position
  21350. var t0 = 0.0;
  21351. var projx = 0.0;
  21352. var projy = 0.0;
  21353. var projz = 0.0;
  21354. // Get all the facets in the same partitioning block than (x, y, z)
  21355. var facetPositions = this.getFacetLocalPositions();
  21356. var facetNormals = this.getFacetLocalNormals();
  21357. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  21358. if (!facetsInBlock) {
  21359. return null;
  21360. }
  21361. // Get the closest facet to (x, y, z)
  21362. var shortest = Number.MAX_VALUE; // init distance vars
  21363. var tmpDistance = shortest;
  21364. var fib; // current facet in the block
  21365. var norm; // current facet normal
  21366. var p0; // current facet barycenter position
  21367. // loop on all the facets in the current partitioning block
  21368. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  21369. fib = facetsInBlock[idx];
  21370. norm = facetNormals[fib];
  21371. p0 = facetPositions[fib];
  21372. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  21373. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  21374. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  21375. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  21376. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  21377. projx = x + norm.x * t0;
  21378. projy = y + norm.y * t0;
  21379. projz = z + norm.z * t0;
  21380. tmpx = projx - x;
  21381. tmpy = projy - y;
  21382. tmpz = projz - z;
  21383. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  21384. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  21385. shortest = tmpDistance;
  21386. closest = fib;
  21387. if (projected) {
  21388. projected.x = projx;
  21389. projected.y = projy;
  21390. projected.z = projz;
  21391. }
  21392. }
  21393. }
  21394. }
  21395. return closest;
  21396. };
  21397. /**
  21398. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  21399. * @returns the parameters
  21400. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21401. */
  21402. AbstractMesh.prototype.getFacetDataParameters = function () {
  21403. return this._facetParameters;
  21404. };
  21405. /**
  21406. * Disables the feature FacetData and frees the related memory
  21407. * @returns the current mesh
  21408. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21409. */
  21410. AbstractMesh.prototype.disableFacetData = function () {
  21411. if (this._facetDataEnabled) {
  21412. this._facetDataEnabled = false;
  21413. this._facetPositions = new Array();
  21414. this._facetNormals = new Array();
  21415. this._facetPartitioning = new Array();
  21416. this._facetParameters = null;
  21417. this._depthSortedIndices = new Uint32Array(0);
  21418. }
  21419. return this;
  21420. };
  21421. /**
  21422. * Updates the AbstractMesh indices array
  21423. * @param indices defines the data source
  21424. * @returns the current mesh
  21425. */
  21426. AbstractMesh.prototype.updateIndices = function (indices) {
  21427. return this;
  21428. };
  21429. /**
  21430. * Creates new normals data for the mesh
  21431. * @param updatable defines if the normal vertex buffer must be flagged as updatable
  21432. * @returns the current mesh
  21433. */
  21434. AbstractMesh.prototype.createNormals = function (updatable) {
  21435. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21436. var indices = this.getIndices();
  21437. var normals;
  21438. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21439. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21440. }
  21441. else {
  21442. normals = [];
  21443. }
  21444. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  21445. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  21446. return this;
  21447. };
  21448. /**
  21449. * Align the mesh with a normal
  21450. * @param normal defines the normal to use
  21451. * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)
  21452. * @returns the current mesh
  21453. */
  21454. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  21455. if (!upDirection) {
  21456. upDirection = BABYLON.Axis.Y;
  21457. }
  21458. var axisX = BABYLON.Tmp.Vector3[0];
  21459. var axisZ = BABYLON.Tmp.Vector3[1];
  21460. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  21461. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  21462. if (this.rotationQuaternion) {
  21463. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  21464. }
  21465. else {
  21466. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  21467. }
  21468. return this;
  21469. };
  21470. /** @hidden */
  21471. AbstractMesh.prototype._checkOcclusionQuery = function () {
  21472. var engine = this.getEngine();
  21473. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  21474. this._isOccluded = false;
  21475. return;
  21476. }
  21477. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  21478. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  21479. if (isOcclusionQueryAvailable) {
  21480. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  21481. this._isOcclusionQueryInProgress = false;
  21482. this._occlusionInternalRetryCounter = 0;
  21483. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  21484. }
  21485. else {
  21486. this._occlusionInternalRetryCounter++;
  21487. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  21488. this._isOcclusionQueryInProgress = false;
  21489. this._occlusionInternalRetryCounter = 0;
  21490. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  21491. // if strict continue the last state of the object.
  21492. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  21493. }
  21494. else {
  21495. return;
  21496. }
  21497. }
  21498. }
  21499. var scene = this.getScene();
  21500. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  21501. if (!this._occlusionQuery) {
  21502. this._occlusionQuery = engine.createQuery();
  21503. }
  21504. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  21505. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  21506. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  21507. this._isOcclusionQueryInProgress = true;
  21508. };
  21509. /** No occlusion */
  21510. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  21511. /** Occlusion set to optimisitic */
  21512. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  21513. /** Occlusion set to strict */
  21514. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  21515. /** Use an accurante occlusion algorithm */
  21516. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  21517. /** Use a conservative occlusion algorithm */
  21518. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  21519. return AbstractMesh;
  21520. }(BABYLON.TransformNode));
  21521. BABYLON.AbstractMesh = AbstractMesh;
  21522. })(BABYLON || (BABYLON = {}));
  21523. //# sourceMappingURL=babylon.abstractMesh.js.map
  21524. var BABYLON;
  21525. (function (BABYLON) {
  21526. /**
  21527. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  21528. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  21529. * 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.
  21530. */
  21531. var Light = /** @class */ (function (_super) {
  21532. __extends(Light, _super);
  21533. /**
  21534. * Creates a Light object in the scene.
  21535. * Documentation : http://doc.babylonjs.com/tutorials/lights
  21536. * @param name The firendly name of the light
  21537. * @param scene The scene the light belongs too
  21538. */
  21539. function Light(name, scene) {
  21540. var _this = _super.call(this, name, scene) || this;
  21541. /**
  21542. * Diffuse gives the basic color to an object.
  21543. */
  21544. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  21545. /**
  21546. * Specular produces a highlight color on an object.
  21547. * Note: This is note affecting PBR materials.
  21548. */
  21549. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  21550. /**
  21551. * Strength of the light.
  21552. * Note: By default it is define in the framework own unit.
  21553. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  21554. */
  21555. _this.intensity = 1.0;
  21556. /**
  21557. * Defines how far from the source the light is impacting in scene units.
  21558. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21559. */
  21560. _this.range = Number.MAX_VALUE;
  21561. /**
  21562. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  21563. * of light.
  21564. */
  21565. _this._photometricScale = 1.0;
  21566. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  21567. _this._radius = 0.00001;
  21568. /**
  21569. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  21570. * exceeding the number allowed of the materials.
  21571. */
  21572. _this.renderPriority = 0;
  21573. _this._shadowEnabled = true;
  21574. _this._excludeWithLayerMask = 0;
  21575. _this._includeOnlyWithLayerMask = 0;
  21576. _this._lightmapMode = 0;
  21577. /**
  21578. * @hidden Internal use only.
  21579. */
  21580. _this._excludedMeshesIds = new Array();
  21581. /**
  21582. * @hidden Internal use only.
  21583. */
  21584. _this._includedOnlyMeshesIds = new Array();
  21585. _this.getScene().addLight(_this);
  21586. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  21587. _this._buildUniformLayout();
  21588. _this.includedOnlyMeshes = new Array();
  21589. _this.excludedMeshes = new Array();
  21590. _this._resyncMeshes();
  21591. return _this;
  21592. }
  21593. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  21594. /**
  21595. * If every light affecting the material is in this lightmapMode,
  21596. * material.lightmapTexture adds or multiplies
  21597. * (depends on material.useLightmapAsShadowmap)
  21598. * after every other light calculations.
  21599. */
  21600. get: function () {
  21601. return Light._LIGHTMAP_DEFAULT;
  21602. },
  21603. enumerable: true,
  21604. configurable: true
  21605. });
  21606. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  21607. /**
  21608. * material.lightmapTexture as only diffuse lighting from this light
  21609. * adds only specular lighting from this light
  21610. * adds dynamic shadows
  21611. */
  21612. get: function () {
  21613. return Light._LIGHTMAP_SPECULAR;
  21614. },
  21615. enumerable: true,
  21616. configurable: true
  21617. });
  21618. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  21619. /**
  21620. * material.lightmapTexture as only lighting
  21621. * no light calculation from this light
  21622. * only adds dynamic shadows from this light
  21623. */
  21624. get: function () {
  21625. return Light._LIGHTMAP_SHADOWSONLY;
  21626. },
  21627. enumerable: true,
  21628. configurable: true
  21629. });
  21630. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  21631. /**
  21632. * Each light type uses the default quantity according to its type:
  21633. * point/spot lights use luminous intensity
  21634. * directional lights use illuminance
  21635. */
  21636. get: function () {
  21637. return Light._INTENSITYMODE_AUTOMATIC;
  21638. },
  21639. enumerable: true,
  21640. configurable: true
  21641. });
  21642. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  21643. /**
  21644. * lumen (lm)
  21645. */
  21646. get: function () {
  21647. return Light._INTENSITYMODE_LUMINOUSPOWER;
  21648. },
  21649. enumerable: true,
  21650. configurable: true
  21651. });
  21652. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  21653. /**
  21654. * candela (lm/sr)
  21655. */
  21656. get: function () {
  21657. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  21658. },
  21659. enumerable: true,
  21660. configurable: true
  21661. });
  21662. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  21663. /**
  21664. * lux (lm/m^2)
  21665. */
  21666. get: function () {
  21667. return Light._INTENSITYMODE_ILLUMINANCE;
  21668. },
  21669. enumerable: true,
  21670. configurable: true
  21671. });
  21672. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  21673. /**
  21674. * nit (cd/m^2)
  21675. */
  21676. get: function () {
  21677. return Light._INTENSITYMODE_LUMINANCE;
  21678. },
  21679. enumerable: true,
  21680. configurable: true
  21681. });
  21682. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  21683. /**
  21684. * Light type const id of the point light.
  21685. */
  21686. get: function () {
  21687. return Light._LIGHTTYPEID_POINTLIGHT;
  21688. },
  21689. enumerable: true,
  21690. configurable: true
  21691. });
  21692. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  21693. /**
  21694. * Light type const id of the directional light.
  21695. */
  21696. get: function () {
  21697. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  21698. },
  21699. enumerable: true,
  21700. configurable: true
  21701. });
  21702. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  21703. /**
  21704. * Light type const id of the spot light.
  21705. */
  21706. get: function () {
  21707. return Light._LIGHTTYPEID_SPOTLIGHT;
  21708. },
  21709. enumerable: true,
  21710. configurable: true
  21711. });
  21712. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  21713. /**
  21714. * Light type const id of the hemispheric light.
  21715. */
  21716. get: function () {
  21717. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  21718. },
  21719. enumerable: true,
  21720. configurable: true
  21721. });
  21722. Object.defineProperty(Light.prototype, "intensityMode", {
  21723. /**
  21724. * Gets the photometric scale used to interpret the intensity.
  21725. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21726. */
  21727. get: function () {
  21728. return this._intensityMode;
  21729. },
  21730. /**
  21731. * Sets the photometric scale used to interpret the intensity.
  21732. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21733. */
  21734. set: function (value) {
  21735. this._intensityMode = value;
  21736. this._computePhotometricScale();
  21737. },
  21738. enumerable: true,
  21739. configurable: true
  21740. });
  21741. ;
  21742. ;
  21743. Object.defineProperty(Light.prototype, "radius", {
  21744. /**
  21745. * Gets the light radius used by PBR Materials to simulate soft area lights.
  21746. */
  21747. get: function () {
  21748. return this._radius;
  21749. },
  21750. /**
  21751. * sets the light radius used by PBR Materials to simulate soft area lights.
  21752. */
  21753. set: function (value) {
  21754. this._radius = value;
  21755. this._computePhotometricScale();
  21756. },
  21757. enumerable: true,
  21758. configurable: true
  21759. });
  21760. ;
  21761. ;
  21762. Object.defineProperty(Light.prototype, "shadowEnabled", {
  21763. /**
  21764. * Gets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21765. * the current shadow generator.
  21766. */
  21767. get: function () {
  21768. return this._shadowEnabled;
  21769. },
  21770. /**
  21771. * Sets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21772. * the current shadow generator.
  21773. */
  21774. set: function (value) {
  21775. if (this._shadowEnabled === value) {
  21776. return;
  21777. }
  21778. this._shadowEnabled = value;
  21779. this._markMeshesAsLightDirty();
  21780. },
  21781. enumerable: true,
  21782. configurable: true
  21783. });
  21784. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  21785. /**
  21786. * Gets the only meshes impacted by this light.
  21787. */
  21788. get: function () {
  21789. return this._includedOnlyMeshes;
  21790. },
  21791. /**
  21792. * Sets the only meshes impacted by this light.
  21793. */
  21794. set: function (value) {
  21795. this._includedOnlyMeshes = value;
  21796. this._hookArrayForIncludedOnly(value);
  21797. },
  21798. enumerable: true,
  21799. configurable: true
  21800. });
  21801. Object.defineProperty(Light.prototype, "excludedMeshes", {
  21802. /**
  21803. * Gets the meshes not impacted by this light.
  21804. */
  21805. get: function () {
  21806. return this._excludedMeshes;
  21807. },
  21808. /**
  21809. * Sets the meshes not impacted by this light.
  21810. */
  21811. set: function (value) {
  21812. this._excludedMeshes = value;
  21813. this._hookArrayForExcluded(value);
  21814. },
  21815. enumerable: true,
  21816. configurable: true
  21817. });
  21818. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  21819. /**
  21820. * Gets the layer id use to find what meshes are not impacted by the light.
  21821. * Inactive if 0
  21822. */
  21823. get: function () {
  21824. return this._excludeWithLayerMask;
  21825. },
  21826. /**
  21827. * Sets the layer id use to find what meshes are not impacted by the light.
  21828. * Inactive if 0
  21829. */
  21830. set: function (value) {
  21831. this._excludeWithLayerMask = value;
  21832. this._resyncMeshes();
  21833. },
  21834. enumerable: true,
  21835. configurable: true
  21836. });
  21837. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  21838. /**
  21839. * Gets the layer id use to find what meshes are impacted by the light.
  21840. * Inactive if 0
  21841. */
  21842. get: function () {
  21843. return this._includeOnlyWithLayerMask;
  21844. },
  21845. /**
  21846. * Sets the layer id use to find what meshes are impacted by the light.
  21847. * Inactive if 0
  21848. */
  21849. set: function (value) {
  21850. this._includeOnlyWithLayerMask = value;
  21851. this._resyncMeshes();
  21852. },
  21853. enumerable: true,
  21854. configurable: true
  21855. });
  21856. Object.defineProperty(Light.prototype, "lightmapMode", {
  21857. /**
  21858. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21859. */
  21860. get: function () {
  21861. return this._lightmapMode;
  21862. },
  21863. /**
  21864. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21865. */
  21866. set: function (value) {
  21867. if (this._lightmapMode === value) {
  21868. return;
  21869. }
  21870. this._lightmapMode = value;
  21871. this._markMeshesAsLightDirty();
  21872. },
  21873. enumerable: true,
  21874. configurable: true
  21875. });
  21876. /**
  21877. * Returns the string "Light".
  21878. * @returns the class name
  21879. */
  21880. Light.prototype.getClassName = function () {
  21881. return "Light";
  21882. };
  21883. /**
  21884. * Converts the light information to a readable string for debug purpose.
  21885. * @param fullDetails Supports for multiple levels of logging within scene loading
  21886. * @returns the human readable light info
  21887. */
  21888. Light.prototype.toString = function (fullDetails) {
  21889. var ret = "Name: " + this.name;
  21890. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  21891. if (this.animations) {
  21892. for (var i = 0; i < this.animations.length; i++) {
  21893. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21894. }
  21895. }
  21896. if (fullDetails) {
  21897. }
  21898. return ret;
  21899. };
  21900. /**
  21901. * Set the enabled state of this node.
  21902. * @param value - the new enabled state
  21903. */
  21904. Light.prototype.setEnabled = function (value) {
  21905. _super.prototype.setEnabled.call(this, value);
  21906. this._resyncMeshes();
  21907. };
  21908. /**
  21909. * Returns the Light associated shadow generator if any.
  21910. * @return the associated shadow generator.
  21911. */
  21912. Light.prototype.getShadowGenerator = function () {
  21913. return this._shadowGenerator;
  21914. };
  21915. /**
  21916. * Returns a Vector3, the absolute light position in the World.
  21917. * @returns the world space position of the light
  21918. */
  21919. Light.prototype.getAbsolutePosition = function () {
  21920. return BABYLON.Vector3.Zero();
  21921. };
  21922. /**
  21923. * Specifies if the light will affect the passed mesh.
  21924. * @param mesh The mesh to test against the light
  21925. * @return true the mesh is affected otherwise, false.
  21926. */
  21927. Light.prototype.canAffectMesh = function (mesh) {
  21928. if (!mesh) {
  21929. return true;
  21930. }
  21931. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  21932. return false;
  21933. }
  21934. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  21935. return false;
  21936. }
  21937. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  21938. return false;
  21939. }
  21940. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  21941. return false;
  21942. }
  21943. return true;
  21944. };
  21945. /**
  21946. * Computes and Returns the light World matrix.
  21947. * @returns the world matrix
  21948. */
  21949. Light.prototype.getWorldMatrix = function () {
  21950. this._currentRenderId = this.getScene().getRenderId();
  21951. this._childRenderId = this._currentRenderId;
  21952. var worldMatrix = this._getWorldMatrix();
  21953. if (this.parent && this.parent.getWorldMatrix) {
  21954. if (!this._parentedWorldMatrix) {
  21955. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  21956. }
  21957. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  21958. this._markSyncedWithParent();
  21959. return this._parentedWorldMatrix;
  21960. }
  21961. return worldMatrix;
  21962. };
  21963. /**
  21964. * Sort function to order lights for rendering.
  21965. * @param a First Light object to compare to second.
  21966. * @param b Second Light object to compare first.
  21967. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  21968. */
  21969. Light.CompareLightsPriority = function (a, b) {
  21970. //shadow-casting lights have priority over non-shadow-casting lights
  21971. //the renderPrioirty is a secondary sort criterion
  21972. if (a.shadowEnabled !== b.shadowEnabled) {
  21973. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  21974. }
  21975. return b.renderPriority - a.renderPriority;
  21976. };
  21977. /**
  21978. * Releases resources associated with this node.
  21979. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21980. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21981. */
  21982. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21983. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21984. if (this._shadowGenerator) {
  21985. this._shadowGenerator.dispose();
  21986. this._shadowGenerator = null;
  21987. }
  21988. // Animations
  21989. this.getScene().stopAnimation(this);
  21990. // Remove from meshes
  21991. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21992. var mesh = _a[_i];
  21993. mesh._removeLightSource(this);
  21994. }
  21995. this._uniformBuffer.dispose();
  21996. // Remove from scene
  21997. this.getScene().removeLight(this);
  21998. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21999. };
  22000. /**
  22001. * Returns the light type ID (integer).
  22002. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  22003. */
  22004. Light.prototype.getTypeID = function () {
  22005. return 0;
  22006. };
  22007. /**
  22008. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  22009. * @returns the scaled intensity in intensity mode unit
  22010. */
  22011. Light.prototype.getScaledIntensity = function () {
  22012. return this._photometricScale * this.intensity;
  22013. };
  22014. /**
  22015. * Returns a new Light object, named "name", from the current one.
  22016. * @param name The name of the cloned light
  22017. * @returns the new created light
  22018. */
  22019. Light.prototype.clone = function (name) {
  22020. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  22021. if (!constructor) {
  22022. return null;
  22023. }
  22024. return BABYLON.SerializationHelper.Clone(constructor, this);
  22025. };
  22026. /**
  22027. * Serializes the current light into a Serialization object.
  22028. * @returns the serialized object.
  22029. */
  22030. Light.prototype.serialize = function () {
  22031. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22032. // Type
  22033. serializationObject.type = this.getTypeID();
  22034. // Parent
  22035. if (this.parent) {
  22036. serializationObject.parentId = this.parent.id;
  22037. }
  22038. // Inclusion / exclusions
  22039. if (this.excludedMeshes.length > 0) {
  22040. serializationObject.excludedMeshesIds = [];
  22041. this.excludedMeshes.forEach(function (mesh) {
  22042. serializationObject.excludedMeshesIds.push(mesh.id);
  22043. });
  22044. }
  22045. if (this.includedOnlyMeshes.length > 0) {
  22046. serializationObject.includedOnlyMeshesIds = [];
  22047. this.includedOnlyMeshes.forEach(function (mesh) {
  22048. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  22049. });
  22050. }
  22051. // Animations
  22052. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22053. serializationObject.ranges = this.serializeAnimationRanges();
  22054. return serializationObject;
  22055. };
  22056. /**
  22057. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  22058. * This new light is named "name" and added to the passed scene.
  22059. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  22060. * @param name The friendly name of the light
  22061. * @param scene The scene the new light will belong to
  22062. * @returns the constructor function
  22063. */
  22064. Light.GetConstructorFromName = function (type, name, scene) {
  22065. switch (type) {
  22066. case 0:
  22067. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  22068. case 1:
  22069. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  22070. case 2:
  22071. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  22072. case 3:
  22073. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  22074. }
  22075. return null;
  22076. };
  22077. /**
  22078. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  22079. * @param parsedLight The JSON representation of the light
  22080. * @param scene The scene to create the parsed light in
  22081. * @returns the created light after parsing
  22082. */
  22083. Light.Parse = function (parsedLight, scene) {
  22084. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  22085. if (!constructor) {
  22086. return null;
  22087. }
  22088. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  22089. // Inclusion / exclusions
  22090. if (parsedLight.excludedMeshesIds) {
  22091. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  22092. }
  22093. if (parsedLight.includedOnlyMeshesIds) {
  22094. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  22095. }
  22096. // Parent
  22097. if (parsedLight.parentId) {
  22098. light._waitingParentId = parsedLight.parentId;
  22099. }
  22100. // Animations
  22101. if (parsedLight.animations) {
  22102. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  22103. var parsedAnimation = parsedLight.animations[animationIndex];
  22104. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22105. }
  22106. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  22107. }
  22108. if (parsedLight.autoAnimate) {
  22109. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  22110. }
  22111. return light;
  22112. };
  22113. Light.prototype._hookArrayForExcluded = function (array) {
  22114. var _this = this;
  22115. var oldPush = array.push;
  22116. array.push = function () {
  22117. var items = [];
  22118. for (var _i = 0; _i < arguments.length; _i++) {
  22119. items[_i] = arguments[_i];
  22120. }
  22121. var result = oldPush.apply(array, items);
  22122. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  22123. var item = items_1[_a];
  22124. item._resyncLighSource(_this);
  22125. }
  22126. return result;
  22127. };
  22128. var oldSplice = array.splice;
  22129. array.splice = function (index, deleteCount) {
  22130. var deleted = oldSplice.apply(array, [index, deleteCount]);
  22131. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  22132. var item = deleted_1[_i];
  22133. item._resyncLighSource(_this);
  22134. }
  22135. return deleted;
  22136. };
  22137. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  22138. var item = array_1[_i];
  22139. item._resyncLighSource(this);
  22140. }
  22141. };
  22142. Light.prototype._hookArrayForIncludedOnly = function (array) {
  22143. var _this = this;
  22144. var oldPush = array.push;
  22145. array.push = function () {
  22146. var items = [];
  22147. for (var _i = 0; _i < arguments.length; _i++) {
  22148. items[_i] = arguments[_i];
  22149. }
  22150. var result = oldPush.apply(array, items);
  22151. _this._resyncMeshes();
  22152. return result;
  22153. };
  22154. var oldSplice = array.splice;
  22155. array.splice = function (index, deleteCount) {
  22156. var deleted = oldSplice.apply(array, [index, deleteCount]);
  22157. _this._resyncMeshes();
  22158. return deleted;
  22159. };
  22160. this._resyncMeshes();
  22161. };
  22162. Light.prototype._resyncMeshes = function () {
  22163. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22164. var mesh = _a[_i];
  22165. mesh._resyncLighSource(this);
  22166. }
  22167. };
  22168. /**
  22169. * Forces the meshes to update their light related information in their rendering used effects
  22170. * @hidden Internal Use Only
  22171. */
  22172. Light.prototype._markMeshesAsLightDirty = function () {
  22173. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22174. var mesh = _a[_i];
  22175. if (mesh._lightSources.indexOf(this) !== -1) {
  22176. mesh._markSubMeshesAsLightDirty();
  22177. }
  22178. }
  22179. };
  22180. /**
  22181. * Recomputes the cached photometric scale if needed.
  22182. */
  22183. Light.prototype._computePhotometricScale = function () {
  22184. this._photometricScale = this._getPhotometricScale();
  22185. this.getScene().resetCachedMaterial();
  22186. };
  22187. /**
  22188. * Returns the Photometric Scale according to the light type and intensity mode.
  22189. */
  22190. Light.prototype._getPhotometricScale = function () {
  22191. var photometricScale = 0.0;
  22192. var lightTypeID = this.getTypeID();
  22193. //get photometric mode
  22194. var photometricMode = this.intensityMode;
  22195. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  22196. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  22197. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  22198. }
  22199. else {
  22200. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  22201. }
  22202. }
  22203. //compute photometric scale
  22204. switch (lightTypeID) {
  22205. case Light.LIGHTTYPEID_POINTLIGHT:
  22206. case Light.LIGHTTYPEID_SPOTLIGHT:
  22207. switch (photometricMode) {
  22208. case Light.INTENSITYMODE_LUMINOUSPOWER:
  22209. photometricScale = 1.0 / (4.0 * Math.PI);
  22210. break;
  22211. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  22212. photometricScale = 1.0;
  22213. break;
  22214. case Light.INTENSITYMODE_LUMINANCE:
  22215. photometricScale = this.radius * this.radius;
  22216. break;
  22217. }
  22218. break;
  22219. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  22220. switch (photometricMode) {
  22221. case Light.INTENSITYMODE_ILLUMINANCE:
  22222. photometricScale = 1.0;
  22223. break;
  22224. case Light.INTENSITYMODE_LUMINANCE:
  22225. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  22226. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  22227. var apexAngleRadians = this.radius;
  22228. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  22229. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  22230. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  22231. photometricScale = solidAngle;
  22232. break;
  22233. }
  22234. break;
  22235. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  22236. // No fall off in hemisperic light.
  22237. photometricScale = 1.0;
  22238. break;
  22239. }
  22240. return photometricScale;
  22241. };
  22242. /**
  22243. * Reorder the light in the scene according to their defined priority.
  22244. * @hidden Internal Use Only
  22245. */
  22246. Light.prototype._reorderLightsInScene = function () {
  22247. var scene = this.getScene();
  22248. if (this._renderPriority != 0) {
  22249. scene.requireLightSorting = true;
  22250. }
  22251. this.getScene().sortLightsByPriority();
  22252. };
  22253. //lightmapMode Consts
  22254. Light._LIGHTMAP_DEFAULT = 0;
  22255. Light._LIGHTMAP_SPECULAR = 1;
  22256. Light._LIGHTMAP_SHADOWSONLY = 2;
  22257. // Intensity Mode Consts
  22258. Light._INTENSITYMODE_AUTOMATIC = 0;
  22259. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  22260. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  22261. Light._INTENSITYMODE_ILLUMINANCE = 3;
  22262. Light._INTENSITYMODE_LUMINANCE = 4;
  22263. // Light types ids const.
  22264. Light._LIGHTTYPEID_POINTLIGHT = 0;
  22265. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  22266. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  22267. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  22268. __decorate([
  22269. BABYLON.serializeAsColor3()
  22270. ], Light.prototype, "diffuse", void 0);
  22271. __decorate([
  22272. BABYLON.serializeAsColor3()
  22273. ], Light.prototype, "specular", void 0);
  22274. __decorate([
  22275. BABYLON.serialize()
  22276. ], Light.prototype, "intensity", void 0);
  22277. __decorate([
  22278. BABYLON.serialize()
  22279. ], Light.prototype, "range", void 0);
  22280. __decorate([
  22281. BABYLON.serialize()
  22282. ], Light.prototype, "intensityMode", null);
  22283. __decorate([
  22284. BABYLON.serialize()
  22285. ], Light.prototype, "radius", null);
  22286. __decorate([
  22287. BABYLON.serialize()
  22288. ], Light.prototype, "_renderPriority", void 0);
  22289. __decorate([
  22290. BABYLON.expandToProperty("_reorderLightsInScene")
  22291. ], Light.prototype, "renderPriority", void 0);
  22292. __decorate([
  22293. BABYLON.serialize("shadowEnabled")
  22294. ], Light.prototype, "_shadowEnabled", void 0);
  22295. __decorate([
  22296. BABYLON.serialize("excludeWithLayerMask")
  22297. ], Light.prototype, "_excludeWithLayerMask", void 0);
  22298. __decorate([
  22299. BABYLON.serialize("includeOnlyWithLayerMask")
  22300. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  22301. __decorate([
  22302. BABYLON.serialize("lightmapMode")
  22303. ], Light.prototype, "_lightmapMode", void 0);
  22304. return Light;
  22305. }(BABYLON.Node));
  22306. BABYLON.Light = Light;
  22307. })(BABYLON || (BABYLON = {}));
  22308. //# sourceMappingURL=babylon.light.js.map
  22309. var BABYLON;
  22310. (function (BABYLON) {
  22311. var Camera = /** @class */ (function (_super) {
  22312. __extends(Camera, _super);
  22313. function Camera(name, position, scene, setActiveOnSceneIfNoneActive) {
  22314. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  22315. var _this = _super.call(this, name, scene) || this;
  22316. /**
  22317. * The vector the camera should consider as up.
  22318. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  22319. */
  22320. _this.upVector = BABYLON.Vector3.Up();
  22321. _this.orthoLeft = null;
  22322. _this.orthoRight = null;
  22323. _this.orthoBottom = null;
  22324. _this.orthoTop = null;
  22325. /**
  22326. * FOV is set in Radians. (default is 0.8)
  22327. */
  22328. _this.fov = 0.8;
  22329. _this.minZ = 1;
  22330. _this.maxZ = 10000.0;
  22331. _this.inertia = 0.9;
  22332. _this.mode = Camera.PERSPECTIVE_CAMERA;
  22333. _this.isIntermediate = false;
  22334. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  22335. /**
  22336. * Restricts the camera to viewing objects with the same layerMask.
  22337. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  22338. */
  22339. _this.layerMask = 0x0FFFFFFF;
  22340. /**
  22341. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  22342. */
  22343. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  22344. // Camera rig members
  22345. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  22346. _this._rigCameras = new Array();
  22347. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  22348. _this._skipRendering = false;
  22349. _this.customRenderTargets = new Array();
  22350. // Observables
  22351. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  22352. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  22353. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  22354. _this.onRestoreStateObservable = new BABYLON.Observable();
  22355. // Cache
  22356. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  22357. _this._projectionMatrix = new BABYLON.Matrix();
  22358. _this._doNotComputeProjectionMatrix = false;
  22359. _this._worldMatrix = BABYLON.Matrix.Identity();
  22360. _this._postProcesses = new Array();
  22361. _this._transformMatrix = BABYLON.Matrix.Zero();
  22362. _this._activeMeshes = new BABYLON.SmartArray(256);
  22363. _this._globalPosition = BABYLON.Vector3.Zero();
  22364. _this._refreshFrustumPlanes = true;
  22365. _this.getScene().addCamera(_this);
  22366. if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) {
  22367. _this.getScene().activeCamera = _this;
  22368. }
  22369. _this.position = position;
  22370. return _this;
  22371. }
  22372. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  22373. get: function () {
  22374. return Camera._PERSPECTIVE_CAMERA;
  22375. },
  22376. enumerable: true,
  22377. configurable: true
  22378. });
  22379. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  22380. get: function () {
  22381. return Camera._ORTHOGRAPHIC_CAMERA;
  22382. },
  22383. enumerable: true,
  22384. configurable: true
  22385. });
  22386. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  22387. /**
  22388. * This is the default FOV mode for perspective cameras.
  22389. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  22390. *
  22391. */
  22392. get: function () {
  22393. return Camera._FOVMODE_VERTICAL_FIXED;
  22394. },
  22395. enumerable: true,
  22396. configurable: true
  22397. });
  22398. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  22399. /**
  22400. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  22401. *
  22402. */
  22403. get: function () {
  22404. return Camera._FOVMODE_HORIZONTAL_FIXED;
  22405. },
  22406. enumerable: true,
  22407. configurable: true
  22408. });
  22409. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  22410. get: function () {
  22411. return Camera._RIG_MODE_NONE;
  22412. },
  22413. enumerable: true,
  22414. configurable: true
  22415. });
  22416. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  22417. get: function () {
  22418. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  22419. },
  22420. enumerable: true,
  22421. configurable: true
  22422. });
  22423. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  22424. get: function () {
  22425. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  22426. },
  22427. enumerable: true,
  22428. configurable: true
  22429. });
  22430. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  22431. get: function () {
  22432. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22433. },
  22434. enumerable: true,
  22435. configurable: true
  22436. });
  22437. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  22438. get: function () {
  22439. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  22440. },
  22441. enumerable: true,
  22442. configurable: true
  22443. });
  22444. Object.defineProperty(Camera, "RIG_MODE_VR", {
  22445. get: function () {
  22446. return Camera._RIG_MODE_VR;
  22447. },
  22448. enumerable: true,
  22449. configurable: true
  22450. });
  22451. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  22452. get: function () {
  22453. return Camera._RIG_MODE_WEBVR;
  22454. },
  22455. enumerable: true,
  22456. configurable: true
  22457. });
  22458. /**
  22459. * Store current camera state (fov, position, etc..)
  22460. */
  22461. Camera.prototype.storeState = function () {
  22462. this._stateStored = true;
  22463. this._storedFov = this.fov;
  22464. return this;
  22465. };
  22466. /**
  22467. * Restores the camera state values if it has been stored. You must call storeState() first
  22468. */
  22469. Camera.prototype._restoreStateValues = function () {
  22470. if (!this._stateStored) {
  22471. return false;
  22472. }
  22473. this.fov = this._storedFov;
  22474. return true;
  22475. };
  22476. /**
  22477. * Restored camera state. You must call storeState() first
  22478. */
  22479. Camera.prototype.restoreState = function () {
  22480. if (this._restoreStateValues()) {
  22481. this.onRestoreStateObservable.notifyObservers(this);
  22482. return true;
  22483. }
  22484. return false;
  22485. };
  22486. Camera.prototype.getClassName = function () {
  22487. return "Camera";
  22488. };
  22489. /**
  22490. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  22491. */
  22492. Camera.prototype.toString = function (fullDetails) {
  22493. var ret = "Name: " + this.name;
  22494. ret += ", type: " + this.getClassName();
  22495. if (this.animations) {
  22496. for (var i = 0; i < this.animations.length; i++) {
  22497. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22498. }
  22499. }
  22500. if (fullDetails) {
  22501. }
  22502. return ret;
  22503. };
  22504. Object.defineProperty(Camera.prototype, "globalPosition", {
  22505. get: function () {
  22506. return this._globalPosition;
  22507. },
  22508. enumerable: true,
  22509. configurable: true
  22510. });
  22511. Camera.prototype.getActiveMeshes = function () {
  22512. return this._activeMeshes;
  22513. };
  22514. Camera.prototype.isActiveMesh = function (mesh) {
  22515. return (this._activeMeshes.indexOf(mesh) !== -1);
  22516. };
  22517. /**
  22518. * Is this camera ready to be used/rendered
  22519. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  22520. * @return true if the camera is ready
  22521. */
  22522. Camera.prototype.isReady = function (completeCheck) {
  22523. if (completeCheck === void 0) { completeCheck = false; }
  22524. if (completeCheck) {
  22525. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  22526. var pp = _a[_i];
  22527. if (pp && !pp.isReady()) {
  22528. return false;
  22529. }
  22530. }
  22531. }
  22532. return _super.prototype.isReady.call(this, completeCheck);
  22533. };
  22534. //Cache
  22535. Camera.prototype._initCache = function () {
  22536. _super.prototype._initCache.call(this);
  22537. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22538. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22539. this._cache.mode = undefined;
  22540. this._cache.minZ = undefined;
  22541. this._cache.maxZ = undefined;
  22542. this._cache.fov = undefined;
  22543. this._cache.fovMode = undefined;
  22544. this._cache.aspectRatio = undefined;
  22545. this._cache.orthoLeft = undefined;
  22546. this._cache.orthoRight = undefined;
  22547. this._cache.orthoBottom = undefined;
  22548. this._cache.orthoTop = undefined;
  22549. this._cache.renderWidth = undefined;
  22550. this._cache.renderHeight = undefined;
  22551. };
  22552. Camera.prototype._updateCache = function (ignoreParentClass) {
  22553. if (!ignoreParentClass) {
  22554. _super.prototype._updateCache.call(this);
  22555. }
  22556. this._cache.position.copyFrom(this.position);
  22557. this._cache.upVector.copyFrom(this.upVector);
  22558. };
  22559. // Synchronized
  22560. Camera.prototype._isSynchronized = function () {
  22561. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  22562. };
  22563. Camera.prototype._isSynchronizedViewMatrix = function () {
  22564. if (!_super.prototype._isSynchronized.call(this))
  22565. return false;
  22566. return this._cache.position.equals(this.position)
  22567. && this._cache.upVector.equals(this.upVector)
  22568. && this.isSynchronizedWithParent();
  22569. };
  22570. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  22571. var check = this._cache.mode === this.mode
  22572. && this._cache.minZ === this.minZ
  22573. && this._cache.maxZ === this.maxZ;
  22574. if (!check) {
  22575. return false;
  22576. }
  22577. var engine = this.getEngine();
  22578. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22579. check = this._cache.fov === this.fov
  22580. && this._cache.fovMode === this.fovMode
  22581. && this._cache.aspectRatio === engine.getAspectRatio(this);
  22582. }
  22583. else {
  22584. check = this._cache.orthoLeft === this.orthoLeft
  22585. && this._cache.orthoRight === this.orthoRight
  22586. && this._cache.orthoBottom === this.orthoBottom
  22587. && this._cache.orthoTop === this.orthoTop
  22588. && this._cache.renderWidth === engine.getRenderWidth()
  22589. && this._cache.renderHeight === engine.getRenderHeight();
  22590. }
  22591. return check;
  22592. };
  22593. // Controls
  22594. Camera.prototype.attachControl = function (element, noPreventDefault) {
  22595. };
  22596. Camera.prototype.detachControl = function (element) {
  22597. };
  22598. Camera.prototype.update = function () {
  22599. this._checkInputs();
  22600. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22601. this._updateRigCameras();
  22602. }
  22603. };
  22604. Camera.prototype._checkInputs = function () {
  22605. this.onAfterCheckInputsObservable.notifyObservers(this);
  22606. };
  22607. Object.defineProperty(Camera.prototype, "rigCameras", {
  22608. get: function () {
  22609. return this._rigCameras;
  22610. },
  22611. enumerable: true,
  22612. configurable: true
  22613. });
  22614. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  22615. get: function () {
  22616. return this._rigPostProcess;
  22617. },
  22618. enumerable: true,
  22619. configurable: true
  22620. });
  22621. /**
  22622. * Internal, gets the first post proces.
  22623. * @returns the first post process to be run on this camera.
  22624. */
  22625. Camera.prototype._getFirstPostProcess = function () {
  22626. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  22627. if (this._postProcesses[ppIndex] !== null) {
  22628. return this._postProcesses[ppIndex];
  22629. }
  22630. }
  22631. return null;
  22632. };
  22633. Camera.prototype._cascadePostProcessesToRigCams = function () {
  22634. // invalidate framebuffer
  22635. var firstPostProcess = this._getFirstPostProcess();
  22636. if (firstPostProcess) {
  22637. firstPostProcess.markTextureDirty();
  22638. }
  22639. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  22640. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  22641. var cam = this._rigCameras[i];
  22642. var rigPostProcess = cam._rigPostProcess;
  22643. // for VR rig, there does not have to be a post process
  22644. if (rigPostProcess) {
  22645. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  22646. if (isPass) {
  22647. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  22648. cam.isIntermediate = this._postProcesses.length === 0;
  22649. }
  22650. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  22651. rigPostProcess.markTextureDirty();
  22652. }
  22653. else {
  22654. cam._postProcesses = this._postProcesses.slice(0);
  22655. }
  22656. }
  22657. };
  22658. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  22659. if (insertAt === void 0) { insertAt = null; }
  22660. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  22661. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  22662. return 0;
  22663. }
  22664. if (insertAt == null || insertAt < 0) {
  22665. this._postProcesses.push(postProcess);
  22666. }
  22667. else if (this._postProcesses[insertAt] === null) {
  22668. this._postProcesses[insertAt] = postProcess;
  22669. }
  22670. else {
  22671. this._postProcesses.splice(insertAt, 0, postProcess);
  22672. }
  22673. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22674. return this._postProcesses.indexOf(postProcess);
  22675. };
  22676. Camera.prototype.detachPostProcess = function (postProcess) {
  22677. var idx = this._postProcesses.indexOf(postProcess);
  22678. if (idx !== -1) {
  22679. this._postProcesses[idx] = null;
  22680. }
  22681. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22682. };
  22683. Camera.prototype.getWorldMatrix = function () {
  22684. if (this._isSynchronizedViewMatrix()) {
  22685. return this._worldMatrix;
  22686. }
  22687. // Getting the the view matrix will also compute the world matrix.
  22688. this.getViewMatrix();
  22689. return this._worldMatrix;
  22690. };
  22691. Camera.prototype._getViewMatrix = function () {
  22692. return BABYLON.Matrix.Identity();
  22693. };
  22694. Camera.prototype.getViewMatrix = function (force) {
  22695. if (!force && this._isSynchronizedViewMatrix()) {
  22696. return this._computedViewMatrix;
  22697. }
  22698. this.updateCache();
  22699. this._computedViewMatrix = this._getViewMatrix();
  22700. this._currentRenderId = this.getScene().getRenderId();
  22701. this._childRenderId = this._currentRenderId;
  22702. this._refreshFrustumPlanes = true;
  22703. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  22704. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  22705. }
  22706. this.onViewMatrixChangedObservable.notifyObservers(this);
  22707. this._computedViewMatrix.invertToRef(this._worldMatrix);
  22708. return this._computedViewMatrix;
  22709. };
  22710. Camera.prototype.freezeProjectionMatrix = function (projection) {
  22711. this._doNotComputeProjectionMatrix = true;
  22712. if (projection !== undefined) {
  22713. this._projectionMatrix = projection;
  22714. }
  22715. };
  22716. ;
  22717. Camera.prototype.unfreezeProjectionMatrix = function () {
  22718. this._doNotComputeProjectionMatrix = false;
  22719. };
  22720. ;
  22721. Camera.prototype.getProjectionMatrix = function (force) {
  22722. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  22723. return this._projectionMatrix;
  22724. }
  22725. // Cache
  22726. this._cache.mode = this.mode;
  22727. this._cache.minZ = this.minZ;
  22728. this._cache.maxZ = this.maxZ;
  22729. // Matrix
  22730. this._refreshFrustumPlanes = true;
  22731. var engine = this.getEngine();
  22732. var scene = this.getScene();
  22733. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22734. this._cache.fov = this.fov;
  22735. this._cache.fovMode = this.fovMode;
  22736. this._cache.aspectRatio = engine.getAspectRatio(this);
  22737. if (this.minZ <= 0) {
  22738. this.minZ = 0.1;
  22739. }
  22740. if (scene.useRightHandedSystem) {
  22741. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22742. }
  22743. else {
  22744. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22745. }
  22746. }
  22747. else {
  22748. var halfWidth = engine.getRenderWidth() / 2.0;
  22749. var halfHeight = engine.getRenderHeight() / 2.0;
  22750. if (scene.useRightHandedSystem) {
  22751. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22752. }
  22753. else {
  22754. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22755. }
  22756. this._cache.orthoLeft = this.orthoLeft;
  22757. this._cache.orthoRight = this.orthoRight;
  22758. this._cache.orthoBottom = this.orthoBottom;
  22759. this._cache.orthoTop = this.orthoTop;
  22760. this._cache.renderWidth = engine.getRenderWidth();
  22761. this._cache.renderHeight = engine.getRenderHeight();
  22762. }
  22763. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  22764. return this._projectionMatrix;
  22765. };
  22766. Camera.prototype.getTranformationMatrix = function () {
  22767. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  22768. return this._transformMatrix;
  22769. };
  22770. Camera.prototype.updateFrustumPlanes = function () {
  22771. if (!this._refreshFrustumPlanes) {
  22772. return;
  22773. }
  22774. this.getTranformationMatrix();
  22775. if (!this._frustumPlanes) {
  22776. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  22777. }
  22778. else {
  22779. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  22780. }
  22781. this._refreshFrustumPlanes = false;
  22782. };
  22783. Camera.prototype.isInFrustum = function (target) {
  22784. this.updateFrustumPlanes();
  22785. return target.isInFrustum(this._frustumPlanes);
  22786. };
  22787. Camera.prototype.isCompletelyInFrustum = function (target) {
  22788. this.updateFrustumPlanes();
  22789. return target.isCompletelyInFrustum(this._frustumPlanes);
  22790. };
  22791. Camera.prototype.getForwardRay = function (length, transform, origin) {
  22792. if (length === void 0) { length = 100; }
  22793. if (!transform) {
  22794. transform = this.getWorldMatrix();
  22795. }
  22796. if (!origin) {
  22797. origin = this.position;
  22798. }
  22799. var forward = new BABYLON.Vector3(0, 0, 1);
  22800. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  22801. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  22802. return new BABYLON.Ray(origin, direction, length);
  22803. };
  22804. /**
  22805. * Releases resources associated with this node.
  22806. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22807. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22808. */
  22809. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22810. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22811. // Observables
  22812. this.onViewMatrixChangedObservable.clear();
  22813. this.onProjectionMatrixChangedObservable.clear();
  22814. this.onAfterCheckInputsObservable.clear();
  22815. this.onRestoreStateObservable.clear();
  22816. // Inputs
  22817. if (this.inputs) {
  22818. this.inputs.clear();
  22819. }
  22820. // Animations
  22821. this.getScene().stopAnimation(this);
  22822. // Remove from scene
  22823. this.getScene().removeCamera(this);
  22824. while (this._rigCameras.length > 0) {
  22825. var camera = this._rigCameras.pop();
  22826. if (camera) {
  22827. camera.dispose();
  22828. }
  22829. }
  22830. // Postprocesses
  22831. if (this._rigPostProcess) {
  22832. this._rigPostProcess.dispose(this);
  22833. this._rigPostProcess = null;
  22834. this._postProcesses = [];
  22835. }
  22836. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22837. this._rigPostProcess = null;
  22838. this._postProcesses = [];
  22839. }
  22840. else {
  22841. var i = this._postProcesses.length;
  22842. while (--i >= 0) {
  22843. var postProcess = this._postProcesses[i];
  22844. if (postProcess) {
  22845. postProcess.dispose(this);
  22846. }
  22847. }
  22848. }
  22849. // Render targets
  22850. var i = this.customRenderTargets.length;
  22851. while (--i >= 0) {
  22852. this.customRenderTargets[i].dispose();
  22853. }
  22854. this.customRenderTargets = [];
  22855. // Active Meshes
  22856. this._activeMeshes.dispose();
  22857. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22858. };
  22859. Object.defineProperty(Camera.prototype, "leftCamera", {
  22860. // ---- Camera rigs section ----
  22861. get: function () {
  22862. if (this._rigCameras.length < 1) {
  22863. return null;
  22864. }
  22865. return this._rigCameras[0];
  22866. },
  22867. enumerable: true,
  22868. configurable: true
  22869. });
  22870. Object.defineProperty(Camera.prototype, "rightCamera", {
  22871. get: function () {
  22872. if (this._rigCameras.length < 2) {
  22873. return null;
  22874. }
  22875. return this._rigCameras[1];
  22876. },
  22877. enumerable: true,
  22878. configurable: true
  22879. });
  22880. Camera.prototype.getLeftTarget = function () {
  22881. if (this._rigCameras.length < 1) {
  22882. return null;
  22883. }
  22884. return this._rigCameras[0].getTarget();
  22885. };
  22886. Camera.prototype.getRightTarget = function () {
  22887. if (this._rigCameras.length < 2) {
  22888. return null;
  22889. }
  22890. return this._rigCameras[1].getTarget();
  22891. };
  22892. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  22893. if (this.cameraRigMode === mode) {
  22894. return;
  22895. }
  22896. while (this._rigCameras.length > 0) {
  22897. var camera = this._rigCameras.pop();
  22898. if (camera) {
  22899. camera.dispose();
  22900. }
  22901. }
  22902. this.cameraRigMode = mode;
  22903. this._cameraRigParams = {};
  22904. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  22905. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  22906. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  22907. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  22908. // create the rig cameras, unless none
  22909. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22910. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  22911. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  22912. if (leftCamera && rightCamera) {
  22913. this._rigCameras.push(leftCamera);
  22914. this._rigCameras.push(rightCamera);
  22915. }
  22916. }
  22917. switch (this.cameraRigMode) {
  22918. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  22919. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22920. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  22921. break;
  22922. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  22923. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  22924. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  22925. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22926. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22927. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  22928. break;
  22929. case Camera.RIG_MODE_VR:
  22930. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  22931. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  22932. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22933. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22934. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  22935. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  22936. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  22937. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  22938. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22939. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22940. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  22941. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  22942. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  22943. if (metrics.compensateDistortion) {
  22944. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  22945. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  22946. }
  22947. break;
  22948. case Camera.RIG_MODE_WEBVR:
  22949. if (rigParams.vrDisplay) {
  22950. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  22951. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  22952. //Left eye
  22953. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22954. this._rigCameras[0].setCameraRigParameter("left", true);
  22955. //leaving this for future reference
  22956. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  22957. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  22958. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  22959. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22960. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22961. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22962. this._rigCameras[0].parent = this;
  22963. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  22964. //Right eye
  22965. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22966. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  22967. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  22968. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  22969. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22970. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22971. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22972. this._rigCameras[1].parent = this;
  22973. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  22974. if (Camera.UseAlternateWebVRRendering) {
  22975. this._rigCameras[1]._skipRendering = true;
  22976. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  22977. }
  22978. }
  22979. break;
  22980. }
  22981. this._cascadePostProcessesToRigCams();
  22982. this.update();
  22983. };
  22984. Camera.prototype._getVRProjectionMatrix = function () {
  22985. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  22986. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  22987. return this._projectionMatrix;
  22988. };
  22989. Camera.prototype._updateCameraRotationMatrix = function () {
  22990. //Here for WebVR
  22991. };
  22992. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  22993. //Here for WebVR
  22994. };
  22995. /**
  22996. * This function MUST be overwritten by the different WebVR cameras available.
  22997. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22998. */
  22999. Camera.prototype._getWebVRProjectionMatrix = function () {
  23000. return BABYLON.Matrix.Identity();
  23001. };
  23002. /**
  23003. * This function MUST be overwritten by the different WebVR cameras available.
  23004. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  23005. */
  23006. Camera.prototype._getWebVRViewMatrix = function () {
  23007. return BABYLON.Matrix.Identity();
  23008. };
  23009. Camera.prototype.setCameraRigParameter = function (name, value) {
  23010. if (!this._cameraRigParams) {
  23011. this._cameraRigParams = {};
  23012. }
  23013. this._cameraRigParams[name] = value;
  23014. //provisionnally:
  23015. if (name === "interaxialDistance") {
  23016. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  23017. }
  23018. };
  23019. /**
  23020. * needs to be overridden by children so sub has required properties to be copied
  23021. */
  23022. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  23023. return null;
  23024. };
  23025. /**
  23026. * May need to be overridden by children
  23027. */
  23028. Camera.prototype._updateRigCameras = function () {
  23029. for (var i = 0; i < this._rigCameras.length; i++) {
  23030. this._rigCameras[i].minZ = this.minZ;
  23031. this._rigCameras[i].maxZ = this.maxZ;
  23032. this._rigCameras[i].fov = this.fov;
  23033. }
  23034. // only update viewport when ANAGLYPH
  23035. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  23036. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  23037. }
  23038. };
  23039. Camera.prototype._setupInputs = function () {
  23040. };
  23041. Camera.prototype.serialize = function () {
  23042. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  23043. // Type
  23044. serializationObject.type = this.getClassName();
  23045. // Parent
  23046. if (this.parent) {
  23047. serializationObject.parentId = this.parent.id;
  23048. }
  23049. if (this.inputs) {
  23050. this.inputs.serialize(serializationObject);
  23051. }
  23052. // Animations
  23053. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  23054. serializationObject.ranges = this.serializeAnimationRanges();
  23055. return serializationObject;
  23056. };
  23057. Camera.prototype.clone = function (name) {
  23058. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  23059. };
  23060. Camera.prototype.getDirection = function (localAxis) {
  23061. var result = BABYLON.Vector3.Zero();
  23062. this.getDirectionToRef(localAxis, result);
  23063. return result;
  23064. };
  23065. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  23066. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  23067. };
  23068. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  23069. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  23070. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  23071. switch (type) {
  23072. case "ArcRotateCamera":
  23073. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  23074. case "DeviceOrientationCamera":
  23075. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  23076. case "FollowCamera":
  23077. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  23078. case "ArcFollowCamera":
  23079. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  23080. case "GamepadCamera":
  23081. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  23082. case "TouchCamera":
  23083. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  23084. case "VirtualJoysticksCamera":
  23085. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  23086. case "WebVRFreeCamera":
  23087. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  23088. case "WebVRGamepadCamera":
  23089. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  23090. case "VRDeviceOrientationFreeCamera":
  23091. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  23092. case "VRDeviceOrientationGamepadCamera":
  23093. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  23094. case "AnaglyphArcRotateCamera":
  23095. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  23096. case "AnaglyphFreeCamera":
  23097. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  23098. case "AnaglyphGamepadCamera":
  23099. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  23100. case "AnaglyphUniversalCamera":
  23101. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  23102. case "StereoscopicArcRotateCamera":
  23103. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  23104. case "StereoscopicFreeCamera":
  23105. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  23106. case "StereoscopicGamepadCamera":
  23107. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  23108. case "StereoscopicUniversalCamera":
  23109. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  23110. case "FreeCamera": // Forcing Universal here
  23111. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  23112. default: // Universal Camera is the default value
  23113. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  23114. }
  23115. };
  23116. Camera.prototype.computeWorldMatrix = function () {
  23117. return this.getWorldMatrix();
  23118. };
  23119. Camera.Parse = function (parsedCamera, scene) {
  23120. var type = parsedCamera.type;
  23121. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  23122. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  23123. // Parent
  23124. if (parsedCamera.parentId) {
  23125. camera._waitingParentId = parsedCamera.parentId;
  23126. }
  23127. //If camera has an input manager, let it parse inputs settings
  23128. if (camera.inputs) {
  23129. camera.inputs.parse(parsedCamera);
  23130. camera._setupInputs();
  23131. }
  23132. if (camera.setPosition) { // need to force position
  23133. camera.position.copyFromFloats(0, 0, 0);
  23134. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  23135. }
  23136. // Target
  23137. if (parsedCamera.target) {
  23138. if (camera.setTarget) {
  23139. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  23140. }
  23141. }
  23142. // Apply 3d rig, when found
  23143. if (parsedCamera.cameraRigMode) {
  23144. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  23145. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  23146. }
  23147. // Animations
  23148. if (parsedCamera.animations) {
  23149. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  23150. var parsedAnimation = parsedCamera.animations[animationIndex];
  23151. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23152. }
  23153. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  23154. }
  23155. if (parsedCamera.autoAnimate) {
  23156. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  23157. }
  23158. return camera;
  23159. };
  23160. // Statics
  23161. Camera._PERSPECTIVE_CAMERA = 0;
  23162. Camera._ORTHOGRAPHIC_CAMERA = 1;
  23163. Camera._FOVMODE_VERTICAL_FIXED = 0;
  23164. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  23165. Camera._RIG_MODE_NONE = 0;
  23166. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  23167. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  23168. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  23169. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  23170. Camera._RIG_MODE_VR = 20;
  23171. Camera._RIG_MODE_WEBVR = 21;
  23172. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  23173. Camera.UseAlternateWebVRRendering = false;
  23174. __decorate([
  23175. BABYLON.serializeAsVector3()
  23176. ], Camera.prototype, "position", void 0);
  23177. __decorate([
  23178. BABYLON.serializeAsVector3()
  23179. ], Camera.prototype, "upVector", void 0);
  23180. __decorate([
  23181. BABYLON.serialize()
  23182. ], Camera.prototype, "orthoLeft", void 0);
  23183. __decorate([
  23184. BABYLON.serialize()
  23185. ], Camera.prototype, "orthoRight", void 0);
  23186. __decorate([
  23187. BABYLON.serialize()
  23188. ], Camera.prototype, "orthoBottom", void 0);
  23189. __decorate([
  23190. BABYLON.serialize()
  23191. ], Camera.prototype, "orthoTop", void 0);
  23192. __decorate([
  23193. BABYLON.serialize()
  23194. ], Camera.prototype, "fov", void 0);
  23195. __decorate([
  23196. BABYLON.serialize()
  23197. ], Camera.prototype, "minZ", void 0);
  23198. __decorate([
  23199. BABYLON.serialize()
  23200. ], Camera.prototype, "maxZ", void 0);
  23201. __decorate([
  23202. BABYLON.serialize()
  23203. ], Camera.prototype, "inertia", void 0);
  23204. __decorate([
  23205. BABYLON.serialize()
  23206. ], Camera.prototype, "mode", void 0);
  23207. __decorate([
  23208. BABYLON.serialize()
  23209. ], Camera.prototype, "layerMask", void 0);
  23210. __decorate([
  23211. BABYLON.serialize()
  23212. ], Camera.prototype, "fovMode", void 0);
  23213. __decorate([
  23214. BABYLON.serialize()
  23215. ], Camera.prototype, "cameraRigMode", void 0);
  23216. __decorate([
  23217. BABYLON.serialize()
  23218. ], Camera.prototype, "interaxialDistance", void 0);
  23219. __decorate([
  23220. BABYLON.serialize()
  23221. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  23222. return Camera;
  23223. }(BABYLON.Node));
  23224. BABYLON.Camera = Camera;
  23225. })(BABYLON || (BABYLON = {}));
  23226. //# sourceMappingURL=babylon.camera.js.map
  23227. var BABYLON;
  23228. (function (BABYLON) {
  23229. var RenderingManager = /** @class */ (function () {
  23230. function RenderingManager(scene) {
  23231. this._renderingGroups = new Array();
  23232. this._autoClearDepthStencil = {};
  23233. this._customOpaqueSortCompareFn = {};
  23234. this._customAlphaTestSortCompareFn = {};
  23235. this._customTransparentSortCompareFn = {};
  23236. this._renderinGroupInfo = null;
  23237. this._scene = scene;
  23238. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  23239. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  23240. }
  23241. }
  23242. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  23243. if (depth === void 0) { depth = true; }
  23244. if (stencil === void 0) { stencil = true; }
  23245. if (this._depthStencilBufferAlreadyCleaned) {
  23246. return;
  23247. }
  23248. this._scene.getEngine().clear(null, false, depth, stencil);
  23249. this._depthStencilBufferAlreadyCleaned = true;
  23250. };
  23251. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  23252. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  23253. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  23254. var info = null;
  23255. if (observable) {
  23256. if (!this._renderinGroupInfo) {
  23257. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  23258. }
  23259. info = this._renderinGroupInfo;
  23260. info.scene = this._scene;
  23261. info.camera = this._scene.activeCamera;
  23262. }
  23263. // Dispatch sprites
  23264. if (renderSprites) {
  23265. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  23266. var manager = this._scene.spriteManagers[index];
  23267. this.dispatchSprites(manager);
  23268. }
  23269. }
  23270. // Render
  23271. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23272. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  23273. var renderingGroup = this._renderingGroups[index];
  23274. if (!renderingGroup && !observable)
  23275. continue;
  23276. var renderingGroupMask = 0;
  23277. // Fire PRECLEAR stage
  23278. if (observable && info) {
  23279. renderingGroupMask = Math.pow(2, index);
  23280. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  23281. info.renderingGroupId = index;
  23282. observable.notifyObservers(info, renderingGroupMask);
  23283. }
  23284. // Clear depth/stencil if needed
  23285. if (RenderingManager.AUTOCLEAR) {
  23286. var autoClear = this._autoClearDepthStencil[index];
  23287. if (autoClear && autoClear.autoClear) {
  23288. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  23289. }
  23290. }
  23291. if (observable && info) {
  23292. // Fire PREOPAQUE stage
  23293. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  23294. observable.notifyObservers(info, renderingGroupMask);
  23295. // Fire PRETRANSPARENT stage
  23296. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  23297. observable.notifyObservers(info, renderingGroupMask);
  23298. }
  23299. if (renderingGroup)
  23300. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  23301. // Fire POSTTRANSPARENT stage
  23302. if (observable && info) {
  23303. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  23304. observable.notifyObservers(info, renderingGroupMask);
  23305. }
  23306. }
  23307. };
  23308. RenderingManager.prototype.reset = function () {
  23309. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23310. var renderingGroup = this._renderingGroups[index];
  23311. if (renderingGroup) {
  23312. renderingGroup.prepare();
  23313. }
  23314. }
  23315. };
  23316. RenderingManager.prototype.dispose = function () {
  23317. this.freeRenderingGroups();
  23318. this._renderingGroups.length = 0;
  23319. };
  23320. /**
  23321. * Clear the info related to rendering groups preventing retention points during dispose.
  23322. */
  23323. RenderingManager.prototype.freeRenderingGroups = function () {
  23324. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23325. var renderingGroup = this._renderingGroups[index];
  23326. if (renderingGroup) {
  23327. renderingGroup.dispose();
  23328. }
  23329. }
  23330. };
  23331. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  23332. if (this._renderingGroups[renderingGroupId] === undefined) {
  23333. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  23334. }
  23335. };
  23336. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  23337. var renderingGroupId = spriteManager.renderingGroupId || 0;
  23338. this._prepareRenderingGroup(renderingGroupId);
  23339. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  23340. };
  23341. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  23342. var renderingGroupId = particleSystem.renderingGroupId || 0;
  23343. this._prepareRenderingGroup(renderingGroupId);
  23344. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  23345. };
  23346. /**
  23347. * @param subMesh The submesh to dispatch
  23348. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23349. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23350. */
  23351. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  23352. if (mesh === undefined) {
  23353. mesh = subMesh.getMesh();
  23354. }
  23355. var renderingGroupId = mesh.renderingGroupId || 0;
  23356. this._prepareRenderingGroup(renderingGroupId);
  23357. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  23358. };
  23359. /**
  23360. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  23361. * This allowed control for front to back rendering or reversly depending of the special needs.
  23362. *
  23363. * @param renderingGroupId The rendering group id corresponding to its index
  23364. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  23365. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  23366. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  23367. */
  23368. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23369. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23370. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23371. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23372. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  23373. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  23374. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  23375. if (this._renderingGroups[renderingGroupId]) {
  23376. var group = this._renderingGroups[renderingGroupId];
  23377. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  23378. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  23379. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  23380. }
  23381. };
  23382. /**
  23383. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  23384. *
  23385. * @param renderingGroupId The rendering group id corresponding to its index
  23386. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  23387. * @param depth Automatically clears depth between groups if true and autoClear is true.
  23388. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  23389. */
  23390. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  23391. if (depth === void 0) { depth = true; }
  23392. if (stencil === void 0) { stencil = true; }
  23393. this._autoClearDepthStencil[renderingGroupId] = {
  23394. autoClear: autoClearDepthStencil,
  23395. depth: depth,
  23396. stencil: stencil
  23397. };
  23398. };
  23399. /**
  23400. * The max id used for rendering groups (not included)
  23401. */
  23402. RenderingManager.MAX_RENDERINGGROUPS = 4;
  23403. /**
  23404. * The min id used for rendering groups (included)
  23405. */
  23406. RenderingManager.MIN_RENDERINGGROUPS = 0;
  23407. /**
  23408. * Used to globally prevent autoclearing scenes.
  23409. */
  23410. RenderingManager.AUTOCLEAR = true;
  23411. return RenderingManager;
  23412. }());
  23413. BABYLON.RenderingManager = RenderingManager;
  23414. })(BABYLON || (BABYLON = {}));
  23415. //# sourceMappingURL=babylon.renderingManager.js.map
  23416. var BABYLON;
  23417. (function (BABYLON) {
  23418. var RenderingGroup = /** @class */ (function () {
  23419. /**
  23420. * Creates a new rendering group.
  23421. * @param index The rendering group index
  23422. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  23423. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  23424. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  23425. */
  23426. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23427. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23428. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23429. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23430. this.index = index;
  23431. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  23432. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  23433. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  23434. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  23435. this._particleSystems = new BABYLON.SmartArray(256);
  23436. this._spriteManagers = new BABYLON.SmartArray(256);
  23437. this._edgesRenderers = new BABYLON.SmartArray(16);
  23438. this._scene = scene;
  23439. this.opaqueSortCompareFn = opaqueSortCompareFn;
  23440. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  23441. this.transparentSortCompareFn = transparentSortCompareFn;
  23442. }
  23443. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  23444. /**
  23445. * Set the opaque sort comparison function.
  23446. * If null the sub meshes will be render in the order they were created
  23447. */
  23448. set: function (value) {
  23449. this._opaqueSortCompareFn = value;
  23450. if (value) {
  23451. this._renderOpaque = this.renderOpaqueSorted;
  23452. }
  23453. else {
  23454. this._renderOpaque = RenderingGroup.renderUnsorted;
  23455. }
  23456. },
  23457. enumerable: true,
  23458. configurable: true
  23459. });
  23460. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  23461. /**
  23462. * Set the alpha test sort comparison function.
  23463. * If null the sub meshes will be render in the order they were created
  23464. */
  23465. set: function (value) {
  23466. this._alphaTestSortCompareFn = value;
  23467. if (value) {
  23468. this._renderAlphaTest = this.renderAlphaTestSorted;
  23469. }
  23470. else {
  23471. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  23472. }
  23473. },
  23474. enumerable: true,
  23475. configurable: true
  23476. });
  23477. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  23478. /**
  23479. * Set the transparent sort comparison function.
  23480. * If null the sub meshes will be render in the order they were created
  23481. */
  23482. set: function (value) {
  23483. if (value) {
  23484. this._transparentSortCompareFn = value;
  23485. }
  23486. else {
  23487. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  23488. }
  23489. this._renderTransparent = this.renderTransparentSorted;
  23490. },
  23491. enumerable: true,
  23492. configurable: true
  23493. });
  23494. /**
  23495. * Render all the sub meshes contained in the group.
  23496. * @param customRenderFunction Used to override the default render behaviour of the group.
  23497. * @returns true if rendered some submeshes.
  23498. */
  23499. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  23500. if (customRenderFunction) {
  23501. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  23502. return;
  23503. }
  23504. var engine = this._scene.getEngine();
  23505. // Depth only
  23506. if (this._depthOnlySubMeshes.length !== 0) {
  23507. engine.setColorWrite(false);
  23508. this._renderAlphaTest(this._depthOnlySubMeshes);
  23509. engine.setColorWrite(true);
  23510. }
  23511. // Opaque
  23512. if (this._opaqueSubMeshes.length !== 0) {
  23513. this._renderOpaque(this._opaqueSubMeshes);
  23514. }
  23515. // Alpha test
  23516. if (this._alphaTestSubMeshes.length !== 0) {
  23517. this._renderAlphaTest(this._alphaTestSubMeshes);
  23518. }
  23519. var stencilState = engine.getStencilBuffer();
  23520. engine.setStencilBuffer(false);
  23521. // Sprites
  23522. if (renderSprites) {
  23523. this._renderSprites();
  23524. }
  23525. // Particles
  23526. if (renderParticles) {
  23527. this._renderParticles(activeMeshes);
  23528. }
  23529. if (this.onBeforeTransparentRendering) {
  23530. this.onBeforeTransparentRendering();
  23531. }
  23532. // Transparent
  23533. if (this._transparentSubMeshes.length !== 0) {
  23534. this._renderTransparent(this._transparentSubMeshes);
  23535. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23536. }
  23537. // Set back stencil to false in case it changes before the edge renderer.
  23538. engine.setStencilBuffer(false);
  23539. // Edges
  23540. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  23541. this._edgesRenderers.data[edgesRendererIndex].render();
  23542. }
  23543. // Restore Stencil state.
  23544. engine.setStencilBuffer(stencilState);
  23545. };
  23546. /**
  23547. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  23548. * @param subMeshes The submeshes to render
  23549. */
  23550. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  23551. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  23552. };
  23553. /**
  23554. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  23555. * @param subMeshes The submeshes to render
  23556. */
  23557. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  23558. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  23559. };
  23560. /**
  23561. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  23562. * @param subMeshes The submeshes to render
  23563. */
  23564. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  23565. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  23566. };
  23567. /**
  23568. * Renders the submeshes in a specified order.
  23569. * @param subMeshes The submeshes to sort before render
  23570. * @param sortCompareFn The comparison function use to sort
  23571. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  23572. * @param transparent Specifies to activate blending if true
  23573. */
  23574. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  23575. var subIndex = 0;
  23576. var subMesh;
  23577. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  23578. for (; subIndex < subMeshes.length; subIndex++) {
  23579. subMesh = subMeshes.data[subIndex];
  23580. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  23581. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  23582. }
  23583. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  23584. if (sortCompareFn) {
  23585. sortedArray.sort(sortCompareFn);
  23586. }
  23587. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  23588. subMesh = sortedArray[subIndex];
  23589. if (transparent) {
  23590. var material = subMesh.getMaterial();
  23591. if (material && material.needDepthPrePass) {
  23592. var engine = material.getScene().getEngine();
  23593. engine.setColorWrite(false);
  23594. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23595. subMesh.render(false);
  23596. engine.setColorWrite(true);
  23597. }
  23598. }
  23599. subMesh.render(transparent);
  23600. }
  23601. };
  23602. /**
  23603. * Renders the submeshes in the order they were dispatched (no sort applied).
  23604. * @param subMeshes The submeshes to render
  23605. */
  23606. RenderingGroup.renderUnsorted = function (subMeshes) {
  23607. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  23608. var submesh = subMeshes.data[subIndex];
  23609. submesh.render(false);
  23610. }
  23611. };
  23612. /**
  23613. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23614. * are rendered back to front if in the same alpha index.
  23615. *
  23616. * @param a The first submesh
  23617. * @param b The second submesh
  23618. * @returns The result of the comparison
  23619. */
  23620. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  23621. // Alpha index first
  23622. if (a._alphaIndex > b._alphaIndex) {
  23623. return 1;
  23624. }
  23625. if (a._alphaIndex < b._alphaIndex) {
  23626. return -1;
  23627. }
  23628. // Then distance to camera
  23629. return RenderingGroup.backToFrontSortCompare(a, b);
  23630. };
  23631. /**
  23632. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23633. * are rendered back to front.
  23634. *
  23635. * @param a The first submesh
  23636. * @param b The second submesh
  23637. * @returns The result of the comparison
  23638. */
  23639. RenderingGroup.backToFrontSortCompare = function (a, b) {
  23640. // Then distance to camera
  23641. if (a._distanceToCamera < b._distanceToCamera) {
  23642. return 1;
  23643. }
  23644. if (a._distanceToCamera > b._distanceToCamera) {
  23645. return -1;
  23646. }
  23647. return 0;
  23648. };
  23649. /**
  23650. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23651. * are rendered front to back (prevent overdraw).
  23652. *
  23653. * @param a The first submesh
  23654. * @param b The second submesh
  23655. * @returns The result of the comparison
  23656. */
  23657. RenderingGroup.frontToBackSortCompare = function (a, b) {
  23658. // Then distance to camera
  23659. if (a._distanceToCamera < b._distanceToCamera) {
  23660. return -1;
  23661. }
  23662. if (a._distanceToCamera > b._distanceToCamera) {
  23663. return 1;
  23664. }
  23665. return 0;
  23666. };
  23667. /**
  23668. * Resets the different lists of submeshes to prepare a new frame.
  23669. */
  23670. RenderingGroup.prototype.prepare = function () {
  23671. this._opaqueSubMeshes.reset();
  23672. this._transparentSubMeshes.reset();
  23673. this._alphaTestSubMeshes.reset();
  23674. this._depthOnlySubMeshes.reset();
  23675. this._particleSystems.reset();
  23676. this._spriteManagers.reset();
  23677. this._edgesRenderers.reset();
  23678. };
  23679. RenderingGroup.prototype.dispose = function () {
  23680. this._opaqueSubMeshes.dispose();
  23681. this._transparentSubMeshes.dispose();
  23682. this._alphaTestSubMeshes.dispose();
  23683. this._depthOnlySubMeshes.dispose();
  23684. this._particleSystems.dispose();
  23685. this._spriteManagers.dispose();
  23686. this._edgesRenderers.dispose();
  23687. };
  23688. /**
  23689. * Inserts the submesh in its correct queue depending on its material.
  23690. * @param subMesh The submesh to dispatch
  23691. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23692. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23693. */
  23694. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  23695. // Get mesh and materials if not provided
  23696. if (mesh === undefined) {
  23697. mesh = subMesh.getMesh();
  23698. }
  23699. if (material === undefined) {
  23700. material = subMesh.getMaterial();
  23701. }
  23702. if (material === null || material === undefined) {
  23703. return;
  23704. }
  23705. if (material.needAlphaBlendingForMesh(mesh)) { // Transparent
  23706. this._transparentSubMeshes.push(subMesh);
  23707. }
  23708. else if (material.needAlphaTesting()) { // Alpha test
  23709. if (material.needDepthPrePass) {
  23710. this._depthOnlySubMeshes.push(subMesh);
  23711. }
  23712. this._alphaTestSubMeshes.push(subMesh);
  23713. }
  23714. else {
  23715. if (material.needDepthPrePass) {
  23716. this._depthOnlySubMeshes.push(subMesh);
  23717. }
  23718. this._opaqueSubMeshes.push(subMesh); // Opaque
  23719. }
  23720. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined && mesh._edgesRenderer.isEnabled) {
  23721. this._edgesRenderers.push(mesh._edgesRenderer);
  23722. }
  23723. };
  23724. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  23725. this._spriteManagers.push(spriteManager);
  23726. };
  23727. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  23728. this._particleSystems.push(particleSystem);
  23729. };
  23730. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  23731. if (this._particleSystems.length === 0) {
  23732. return;
  23733. }
  23734. // Particles
  23735. var activeCamera = this._scene.activeCamera;
  23736. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  23737. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  23738. var particleSystem = this._particleSystems.data[particleIndex];
  23739. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  23740. continue;
  23741. }
  23742. var emitter = particleSystem.emitter;
  23743. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  23744. this._scene._activeParticles.addCount(particleSystem.render(), false);
  23745. }
  23746. }
  23747. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  23748. };
  23749. RenderingGroup.prototype._renderSprites = function () {
  23750. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  23751. return;
  23752. }
  23753. // Sprites
  23754. var activeCamera = this._scene.activeCamera;
  23755. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  23756. for (var id = 0; id < this._spriteManagers.length; id++) {
  23757. var spriteManager = this._spriteManagers.data[id];
  23758. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  23759. spriteManager.render();
  23760. }
  23761. }
  23762. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  23763. };
  23764. return RenderingGroup;
  23765. }());
  23766. BABYLON.RenderingGroup = RenderingGroup;
  23767. })(BABYLON || (BABYLON = {}));
  23768. //# sourceMappingURL=babylon.renderingGroup.js.map
  23769. var BABYLON;
  23770. (function (BABYLON) {
  23771. /** @hidden */
  23772. var ClickInfo = /** @class */ (function () {
  23773. function ClickInfo() {
  23774. this._singleClick = false;
  23775. this._doubleClick = false;
  23776. this._hasSwiped = false;
  23777. this._ignore = false;
  23778. }
  23779. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  23780. get: function () {
  23781. return this._singleClick;
  23782. },
  23783. set: function (b) {
  23784. this._singleClick = b;
  23785. },
  23786. enumerable: true,
  23787. configurable: true
  23788. });
  23789. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  23790. get: function () {
  23791. return this._doubleClick;
  23792. },
  23793. set: function (b) {
  23794. this._doubleClick = b;
  23795. },
  23796. enumerable: true,
  23797. configurable: true
  23798. });
  23799. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  23800. get: function () {
  23801. return this._hasSwiped;
  23802. },
  23803. set: function (b) {
  23804. this._hasSwiped = b;
  23805. },
  23806. enumerable: true,
  23807. configurable: true
  23808. });
  23809. Object.defineProperty(ClickInfo.prototype, "ignore", {
  23810. get: function () {
  23811. return this._ignore;
  23812. },
  23813. set: function (b) {
  23814. this._ignore = b;
  23815. },
  23816. enumerable: true,
  23817. configurable: true
  23818. });
  23819. return ClickInfo;
  23820. }());
  23821. /**
  23822. * This class is used by the onRenderingGroupObservable
  23823. */
  23824. var RenderingGroupInfo = /** @class */ (function () {
  23825. function RenderingGroupInfo() {
  23826. }
  23827. /**
  23828. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  23829. * This stage will be fired no matter what
  23830. */
  23831. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  23832. /**
  23833. * Called before opaque object are rendered.
  23834. * This stage will be fired only if there's 3D Opaque content to render
  23835. */
  23836. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  23837. /**
  23838. * Called after the opaque objects are rendered and before the transparent ones
  23839. * This stage will be fired only if there's 3D transparent content to render
  23840. */
  23841. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  23842. /**
  23843. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  23844. * This stage will be fired no matter what
  23845. */
  23846. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  23847. return RenderingGroupInfo;
  23848. }());
  23849. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  23850. /**
  23851. * Represents a scene to be rendered by the engine.
  23852. * @see http://doc.babylonjs.com/features/scene
  23853. */
  23854. var Scene = /** @class */ (function () {
  23855. /**
  23856. * Creates a new Scene
  23857. * @param engine defines the engine to use to render this scene
  23858. */
  23859. function Scene(engine) {
  23860. // Members
  23861. /**
  23862. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  23863. */
  23864. this.autoClear = true;
  23865. /**
  23866. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  23867. */
  23868. this.autoClearDepthAndStencil = true;
  23869. /**
  23870. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  23871. */
  23872. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  23873. /**
  23874. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  23875. */
  23876. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  23877. this._forceWireframe = false;
  23878. this._forcePointsCloud = false;
  23879. /**
  23880. * Gets or sets a boolean indicating if all bounding boxes must be rendered
  23881. */
  23882. this.forceShowBoundingBoxes = false;
  23883. /**
  23884. * Gets or sets a boolean indicating if animations are enabled
  23885. */
  23886. this.animationsEnabled = true;
  23887. this._animationPropertiesOverride = null;
  23888. /**
  23889. * Gets or sets a boolean indicating if a constant deltatime has to be used
  23890. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  23891. */
  23892. this.useConstantAnimationDeltaTime = false;
  23893. /**
  23894. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  23895. * Please note that it requires to run a ray cast through the scene on every frame
  23896. */
  23897. this.constantlyUpdateMeshUnderPointer = false;
  23898. /**
  23899. * Defines the HTML cursor to use when hovering over interactive elements
  23900. */
  23901. this.hoverCursor = "pointer";
  23902. /**
  23903. * Defines the HTML default cursor to use (empty by default)
  23904. */
  23905. this.defaultCursor = "";
  23906. /**
  23907. * This is used to call preventDefault() on pointer down
  23908. * in order to block unwanted artifacts like system double clicks
  23909. */
  23910. this.preventDefaultOnPointerDown = true;
  23911. // Metadata
  23912. /**
  23913. * Gets or sets user defined metadata
  23914. */
  23915. this.metadata = null;
  23916. /**
  23917. * Use this array to add regular expressions used to disable offline support for specific urls
  23918. */
  23919. this.disableOfflineSupportExceptionRules = new Array();
  23920. /**
  23921. * An event triggered when the scene is disposed.
  23922. */
  23923. this.onDisposeObservable = new BABYLON.Observable();
  23924. this._onDisposeObserver = null;
  23925. /**
  23926. * An event triggered before rendering the scene (right after animations and physics)
  23927. */
  23928. this.onBeforeRenderObservable = new BABYLON.Observable();
  23929. this._onBeforeRenderObserver = null;
  23930. /**
  23931. * An event triggered after rendering the scene
  23932. */
  23933. this.onAfterRenderObservable = new BABYLON.Observable();
  23934. this._onAfterRenderObserver = null;
  23935. /**
  23936. * An event triggered before animating the scene
  23937. */
  23938. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  23939. /**
  23940. * An event triggered after animations processing
  23941. */
  23942. this.onAfterAnimationsObservable = new BABYLON.Observable();
  23943. /**
  23944. * An event triggered before draw calls are ready to be sent
  23945. */
  23946. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  23947. /**
  23948. * An event triggered after draw calls have been sent
  23949. */
  23950. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  23951. /**
  23952. * An event triggered when physic simulation is about to be run
  23953. */
  23954. this.onBeforePhysicsObservable = new BABYLON.Observable();
  23955. /**
  23956. * An event triggered when physic simulation has been done
  23957. */
  23958. this.onAfterPhysicsObservable = new BABYLON.Observable();
  23959. /**
  23960. * An event triggered when the scene is ready
  23961. */
  23962. this.onReadyObservable = new BABYLON.Observable();
  23963. /**
  23964. * An event triggered before rendering a camera
  23965. */
  23966. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  23967. this._onBeforeCameraRenderObserver = null;
  23968. /**
  23969. * An event triggered after rendering a camera
  23970. */
  23971. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  23972. this._onAfterCameraRenderObserver = null;
  23973. /**
  23974. * An event triggered when active meshes evaluation is about to start
  23975. */
  23976. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23977. /**
  23978. * An event triggered when active meshes evaluation is done
  23979. */
  23980. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23981. /**
  23982. * An event triggered when particles rendering is about to start
  23983. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23984. */
  23985. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  23986. /**
  23987. * An event triggered when particles rendering is done
  23988. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23989. */
  23990. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  23991. /**
  23992. * An event triggered when sprites rendering is about to start
  23993. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23994. */
  23995. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  23996. /**
  23997. * An event triggered when sprites rendering is done
  23998. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23999. */
  24000. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  24001. /**
  24002. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  24003. */
  24004. this.onDataLoadedObservable = new BABYLON.Observable();
  24005. /**
  24006. * An event triggered when a camera is created
  24007. */
  24008. this.onNewCameraAddedObservable = new BABYLON.Observable();
  24009. /**
  24010. * An event triggered when a camera is removed
  24011. */
  24012. this.onCameraRemovedObservable = new BABYLON.Observable();
  24013. /**
  24014. * An event triggered when a light is created
  24015. */
  24016. this.onNewLightAddedObservable = new BABYLON.Observable();
  24017. /**
  24018. * An event triggered when a light is removed
  24019. */
  24020. this.onLightRemovedObservable = new BABYLON.Observable();
  24021. /**
  24022. * An event triggered when a geometry is created
  24023. */
  24024. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  24025. /**
  24026. * An event triggered when a geometry is removed
  24027. */
  24028. this.onGeometryRemovedObservable = new BABYLON.Observable();
  24029. /**
  24030. * An event triggered when a transform node is created
  24031. */
  24032. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  24033. /**
  24034. * An event triggered when a transform node is removed
  24035. */
  24036. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  24037. /**
  24038. * An event triggered when a mesh is created
  24039. */
  24040. this.onNewMeshAddedObservable = new BABYLON.Observable();
  24041. /**
  24042. * An event triggered when a mesh is removed
  24043. */
  24044. this.onMeshRemovedObservable = new BABYLON.Observable();
  24045. /**
  24046. * An event triggered when render targets are about to be rendered
  24047. * Can happen multiple times per frame.
  24048. */
  24049. this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  24050. /**
  24051. * An event triggered when render targets were rendered.
  24052. * Can happen multiple times per frame.
  24053. */
  24054. this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  24055. /**
  24056. * An event triggered before calculating deterministic simulation step
  24057. */
  24058. this.onBeforeStepObservable = new BABYLON.Observable();
  24059. /**
  24060. * An event triggered after calculating deterministic simulation step
  24061. */
  24062. this.onAfterStepObservable = new BABYLON.Observable();
  24063. /**
  24064. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  24065. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  24066. * 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)
  24067. */
  24068. this.onRenderingGroupObservable = new BABYLON.Observable();
  24069. // Animations
  24070. /**
  24071. * Gets a list of Animations associated with the scene
  24072. */
  24073. this.animations = [];
  24074. this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  24075. /**
  24076. * 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).
  24077. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  24078. */
  24079. this.onPrePointerObservable = new BABYLON.Observable();
  24080. /**
  24081. * Observable event triggered each time an input event is received from the rendering canvas
  24082. */
  24083. this.onPointerObservable = new BABYLON.Observable();
  24084. this._meshPickProceed = false;
  24085. this._currentPickResult = null;
  24086. this._previousPickResult = null;
  24087. this._totalPointersPressed = 0;
  24088. this._doubleClickOccured = false;
  24089. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  24090. this.cameraToUseForPointers = null;
  24091. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  24092. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  24093. this._startingPointerTime = 0;
  24094. this._previousStartingPointerTime = 0;
  24095. this._pointerCaptures = {};
  24096. // Deterministic lockstep
  24097. this._timeAccumulator = 0;
  24098. this._currentStepId = 0;
  24099. this._currentInternalStep = 0;
  24100. // Keyboard
  24101. /**
  24102. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  24103. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  24104. */
  24105. this.onPreKeyboardObservable = new BABYLON.Observable();
  24106. /**
  24107. * Observable event triggered each time an keyboard event is received from the hosting window
  24108. */
  24109. this.onKeyboardObservable = new BABYLON.Observable();
  24110. // Coordinates system
  24111. this._useRightHandedSystem = false;
  24112. // Fog
  24113. this._fogEnabled = true;
  24114. this._fogMode = Scene.FOGMODE_NONE;
  24115. /**
  24116. * Gets or sets the fog color to use
  24117. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24118. */
  24119. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  24120. /**
  24121. * Gets or sets the fog density to use
  24122. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24123. */
  24124. this.fogDensity = 0.1;
  24125. /**
  24126. * Gets or sets the fog start distance to use
  24127. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24128. */
  24129. this.fogStart = 0;
  24130. /**
  24131. * Gets or sets the fog end distance to use
  24132. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24133. */
  24134. this.fogEnd = 1000.0;
  24135. // Lights
  24136. this._shadowsEnabled = true;
  24137. this._lightsEnabled = true;
  24138. /**
  24139. * All of the lights added to this scene
  24140. * @see http://doc.babylonjs.com/babylon101/lights
  24141. */
  24142. this.lights = new Array();
  24143. // Cameras
  24144. /** All of the cameras added to this scene.
  24145. * @see http://doc.babylonjs.com/babylon101/cameras
  24146. */
  24147. this.cameras = new Array();
  24148. /** All of the active cameras added to this scene. */
  24149. this.activeCameras = new Array();
  24150. // Meshes
  24151. /**
  24152. * All of the tranform nodes added to this scene
  24153. * @see http://doc.babylonjs.com/how_to/transformnode
  24154. */
  24155. this.transformNodes = new Array();
  24156. /**
  24157. * All of the (abstract) meshes added to this scene
  24158. */
  24159. this.meshes = new Array();
  24160. /**
  24161. * All of the animation groups added to this scene
  24162. * @see http://doc.babylonjs.com/how_to/group
  24163. */
  24164. this.animationGroups = new Array();
  24165. // Geometries
  24166. this._geometries = new Array();
  24167. /**
  24168. * All of the materials added to this scene
  24169. * @see http://doc.babylonjs.com/babylon101/materials
  24170. */
  24171. this.materials = new Array();
  24172. /**
  24173. * All of the multi-materials added to this scene
  24174. * @see http://doc.babylonjs.com/how_to/multi_materials
  24175. */
  24176. this.multiMaterials = new Array();
  24177. // Textures
  24178. this._texturesEnabled = true;
  24179. /**
  24180. * All of the textures added to this scene
  24181. */
  24182. this.textures = new Array();
  24183. // Particles
  24184. /**
  24185. * Gets or sets a boolean indicating if particles are enabled on this scene
  24186. */
  24187. this.particlesEnabled = true;
  24188. /**
  24189. * All of the particle systems added to this scene
  24190. * @see http://doc.babylonjs.com/babylon101/particles
  24191. */
  24192. this.particleSystems = new Array();
  24193. // Sprites
  24194. /**
  24195. * Gets or sets a boolean indicating if sprites are enabled on this scene
  24196. */
  24197. this.spritesEnabled = true;
  24198. /**
  24199. * All of the sprite managers added to this scene
  24200. * @see http://doc.babylonjs.com/babylon101/sprites
  24201. */
  24202. this.spriteManagers = new Array();
  24203. /**
  24204. * The list of layers (background and foreground) of the scene
  24205. */
  24206. this.layers = new Array();
  24207. /**
  24208. * The list of effect layers (highlights/glow) added to the scene
  24209. * @see http://doc.babylonjs.com/how_to/highlight_layer
  24210. * @see http://doc.babylonjs.com/how_to/glow_layer
  24211. */
  24212. this.effectLayers = new Array();
  24213. // Skeletons
  24214. this._skeletonsEnabled = true;
  24215. /**
  24216. * The list of skeletons added to the scene
  24217. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  24218. */
  24219. this.skeletons = new Array();
  24220. // Morph targets
  24221. /**
  24222. * The list of morph target managers added to the scene
  24223. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  24224. */
  24225. this.morphTargetManagers = new Array();
  24226. // Lens flares
  24227. /**
  24228. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  24229. */
  24230. this.lensFlaresEnabled = true;
  24231. /**
  24232. * The list of lens flare system added to the scene
  24233. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  24234. */
  24235. this.lensFlareSystems = new Array();
  24236. // Collisions
  24237. /**
  24238. * Gets or sets a boolean indicating if collisions are enabled on this scene
  24239. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24240. */
  24241. this.collisionsEnabled = true;
  24242. /**
  24243. * Defines the gravity applied to this scene (used only for collisions)
  24244. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24245. */
  24246. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  24247. // Postprocesses
  24248. /**
  24249. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  24250. */
  24251. this.postProcessesEnabled = true;
  24252. /**
  24253. * The list of postprocesses added to the scene
  24254. */
  24255. this.postProcesses = new Array();
  24256. // Customs render targets
  24257. /**
  24258. * Gets or sets a boolean indicating if render targets are enabled on this scene
  24259. */
  24260. this.renderTargetsEnabled = true;
  24261. /**
  24262. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  24263. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  24264. */
  24265. this.dumpNextRenderTargets = false;
  24266. /**
  24267. * The list of user defined render targets added to the scene
  24268. */
  24269. this.customRenderTargets = new Array();
  24270. /**
  24271. * Gets the list of meshes imported to the scene through SceneLoader
  24272. */
  24273. this.importedMeshesFiles = new Array();
  24274. // Probes
  24275. /**
  24276. * Gets or sets a boolean indicating if probes are enabled on this scene
  24277. */
  24278. this.probesEnabled = true;
  24279. /**
  24280. * The list of reflection probes added to the scene
  24281. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  24282. */
  24283. this.reflectionProbes = new Array();
  24284. /** @hidden */
  24285. this._actionManagers = new Array();
  24286. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  24287. // Procedural textures
  24288. /**
  24289. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  24290. */
  24291. this.proceduralTexturesEnabled = true;
  24292. /**
  24293. * The list of procedural textures added to the scene
  24294. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  24295. */
  24296. this.proceduralTextures = new Array();
  24297. /**
  24298. * The list of sound tracks added to the scene
  24299. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  24300. */
  24301. this.soundTracks = new Array();
  24302. this._audioEnabled = true;
  24303. this._headphone = false;
  24304. // Performance counters
  24305. this._totalVertices = new BABYLON.PerfCounter();
  24306. /** @hidden */
  24307. this._activeIndices = new BABYLON.PerfCounter();
  24308. /** @hidden */
  24309. this._activeParticles = new BABYLON.PerfCounter();
  24310. /** @hidden */
  24311. this._activeBones = new BABYLON.PerfCounter();
  24312. this._animationTime = 0;
  24313. /**
  24314. * Gets or sets a general scale for animation speed
  24315. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  24316. */
  24317. this.animationTimeScale = 1;
  24318. this._renderId = 0;
  24319. this._executeWhenReadyTimeoutId = -1;
  24320. this._intermediateRendering = false;
  24321. this._viewUpdateFlag = -1;
  24322. this._projectionUpdateFlag = -1;
  24323. this._alternateViewUpdateFlag = -1;
  24324. this._alternateProjectionUpdateFlag = -1;
  24325. /** @hidden */
  24326. this._toBeDisposed = new BABYLON.SmartArray(256);
  24327. this._activeRequests = new Array();
  24328. this._pendingData = new Array();
  24329. this._isDisposed = false;
  24330. /**
  24331. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  24332. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  24333. */
  24334. this.dispatchAllSubMeshesOfActiveMeshes = false;
  24335. this._activeMeshes = new BABYLON.SmartArray(256);
  24336. this._processedMaterials = new BABYLON.SmartArray(256);
  24337. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  24338. /** @hidden */
  24339. this._activeParticleSystems = new BABYLON.SmartArray(256);
  24340. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  24341. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  24342. /** @hidden */
  24343. this._activeAnimatables = new Array();
  24344. this._transformMatrix = BABYLON.Matrix.Zero();
  24345. this._useAlternateCameraConfiguration = false;
  24346. this._alternateRendering = false;
  24347. /**
  24348. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  24349. * This is useful if there are more lights that the maximum simulteanous authorized
  24350. */
  24351. this.requireLightSorting = false;
  24352. this._depthRenderer = {};
  24353. this._activeMeshesFrozen = false;
  24354. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  24355. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  24356. this._engine.scenes.push(this);
  24357. this._uid = null;
  24358. this._renderingManager = new BABYLON.RenderingManager(this);
  24359. if (BABYLON.PostProcessManager) {
  24360. this.postProcessManager = new BABYLON.PostProcessManager(this);
  24361. }
  24362. if (BABYLON.OutlineRenderer) {
  24363. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  24364. }
  24365. if (BABYLON.Tools.IsWindowObjectExist()) {
  24366. this.attachControl();
  24367. }
  24368. //simplification queue
  24369. if (BABYLON.SimplificationQueue) {
  24370. this.simplificationQueue = new BABYLON.SimplificationQueue();
  24371. }
  24372. //collision coordinator initialization. For now legacy per default.
  24373. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  24374. // Uniform Buffer
  24375. this._createUbo();
  24376. // Default Image processing definition
  24377. if (BABYLON.ImageProcessingConfiguration) {
  24378. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  24379. }
  24380. }
  24381. Object.defineProperty(Scene, "FOGMODE_NONE", {
  24382. /** The fog is deactivated */
  24383. get: function () {
  24384. return Scene._FOGMODE_NONE;
  24385. },
  24386. enumerable: true,
  24387. configurable: true
  24388. });
  24389. Object.defineProperty(Scene, "FOGMODE_EXP", {
  24390. /** The fog density is following an exponential function */
  24391. get: function () {
  24392. return Scene._FOGMODE_EXP;
  24393. },
  24394. enumerable: true,
  24395. configurable: true
  24396. });
  24397. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  24398. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  24399. get: function () {
  24400. return Scene._FOGMODE_EXP2;
  24401. },
  24402. enumerable: true,
  24403. configurable: true
  24404. });
  24405. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  24406. /** The fog density is following a linear function. */
  24407. get: function () {
  24408. return Scene._FOGMODE_LINEAR;
  24409. },
  24410. enumerable: true,
  24411. configurable: true
  24412. });
  24413. Object.defineProperty(Scene.prototype, "environmentTexture", {
  24414. /**
  24415. * Texture used in all pbr material as the reflection texture.
  24416. * As in the majority of the scene they are the same (exception for multi room and so on),
  24417. * this is easier to reference from here than from all the materials.
  24418. */
  24419. get: function () {
  24420. return this._environmentTexture;
  24421. },
  24422. /**
  24423. * Texture used in all pbr material as the reflection texture.
  24424. * As in the majority of the scene they are the same (exception for multi room and so on),
  24425. * this is easier to set here than in all the materials.
  24426. */
  24427. set: function (value) {
  24428. if (this._environmentTexture === value) {
  24429. return;
  24430. }
  24431. this._environmentTexture = value;
  24432. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24433. },
  24434. enumerable: true,
  24435. configurable: true
  24436. });
  24437. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  24438. /**
  24439. * Default image processing configuration used either in the rendering
  24440. * Forward main pass or through the imageProcessingPostProcess if present.
  24441. * As in the majority of the scene they are the same (exception for multi camera),
  24442. * this is easier to reference from here than from all the materials and post process.
  24443. *
  24444. * No setter as we it is a shared configuration, you can set the values instead.
  24445. */
  24446. get: function () {
  24447. return this._imageProcessingConfiguration;
  24448. },
  24449. enumerable: true,
  24450. configurable: true
  24451. });
  24452. Object.defineProperty(Scene.prototype, "forceWireframe", {
  24453. get: function () {
  24454. return this._forceWireframe;
  24455. },
  24456. /**
  24457. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  24458. */
  24459. set: function (value) {
  24460. if (this._forceWireframe === value) {
  24461. return;
  24462. }
  24463. this._forceWireframe = value;
  24464. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24465. },
  24466. enumerable: true,
  24467. configurable: true
  24468. });
  24469. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  24470. get: function () {
  24471. return this._forcePointsCloud;
  24472. },
  24473. /**
  24474. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  24475. */
  24476. set: function (value) {
  24477. if (this._forcePointsCloud === value) {
  24478. return;
  24479. }
  24480. this._forcePointsCloud = value;
  24481. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24482. },
  24483. enumerable: true,
  24484. configurable: true
  24485. });
  24486. Object.defineProperty(Scene.prototype, "animationPropertiesOverride", {
  24487. /**
  24488. * Gets or sets the animation properties override
  24489. */
  24490. get: function () {
  24491. return this._animationPropertiesOverride;
  24492. },
  24493. set: function (value) {
  24494. this._animationPropertiesOverride = value;
  24495. },
  24496. enumerable: true,
  24497. configurable: true
  24498. });
  24499. Object.defineProperty(Scene.prototype, "onDispose", {
  24500. /** Sets a function to be executed when this scene is disposed. */
  24501. set: function (callback) {
  24502. if (this._onDisposeObserver) {
  24503. this.onDisposeObservable.remove(this._onDisposeObserver);
  24504. }
  24505. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24506. },
  24507. enumerable: true,
  24508. configurable: true
  24509. });
  24510. Object.defineProperty(Scene.prototype, "beforeRender", {
  24511. /** Sets a function to be executed before rendering this scene */
  24512. set: function (callback) {
  24513. if (this._onBeforeRenderObserver) {
  24514. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  24515. }
  24516. if (callback) {
  24517. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  24518. }
  24519. },
  24520. enumerable: true,
  24521. configurable: true
  24522. });
  24523. Object.defineProperty(Scene.prototype, "afterRender", {
  24524. /** Sets a function to be executed after rendering this scene */
  24525. set: function (callback) {
  24526. if (this._onAfterRenderObserver) {
  24527. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  24528. }
  24529. if (callback) {
  24530. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  24531. }
  24532. },
  24533. enumerable: true,
  24534. configurable: true
  24535. });
  24536. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  24537. /** Sets a function to be executed before rendering a camera*/
  24538. set: function (callback) {
  24539. if (this._onBeforeCameraRenderObserver) {
  24540. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  24541. }
  24542. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  24543. },
  24544. enumerable: true,
  24545. configurable: true
  24546. });
  24547. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  24548. /** Sets a function to be executed after rendering a camera*/
  24549. set: function (callback) {
  24550. if (this._onAfterCameraRenderObserver) {
  24551. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  24552. }
  24553. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  24554. },
  24555. enumerable: true,
  24556. configurable: true
  24557. });
  24558. Object.defineProperty(Scene.prototype, "gamepadManager", {
  24559. /**
  24560. * Gets the gamepad manager associated with the scene
  24561. * @see http://doc.babylonjs.com/how_to/how_to_use_gamepads
  24562. */
  24563. get: function () {
  24564. if (!this._gamepadManager) {
  24565. this._gamepadManager = new BABYLON.GamepadManager(this);
  24566. }
  24567. return this._gamepadManager;
  24568. },
  24569. enumerable: true,
  24570. configurable: true
  24571. });
  24572. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  24573. /**
  24574. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  24575. */
  24576. get: function () {
  24577. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  24578. },
  24579. enumerable: true,
  24580. configurable: true
  24581. });
  24582. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  24583. get: function () {
  24584. return this._useRightHandedSystem;
  24585. },
  24586. /**
  24587. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  24588. */
  24589. set: function (value) {
  24590. if (this._useRightHandedSystem === value) {
  24591. return;
  24592. }
  24593. this._useRightHandedSystem = value;
  24594. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24595. },
  24596. enumerable: true,
  24597. configurable: true
  24598. });
  24599. /**
  24600. * Sets the step Id used by deterministic lock step
  24601. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24602. * @param newStepId defines the step Id
  24603. */
  24604. Scene.prototype.setStepId = function (newStepId) {
  24605. this._currentStepId = newStepId;
  24606. };
  24607. ;
  24608. /**
  24609. * Gets the step Id used by deterministic lock step
  24610. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24611. * @returns the step Id
  24612. */
  24613. Scene.prototype.getStepId = function () {
  24614. return this._currentStepId;
  24615. };
  24616. ;
  24617. /**
  24618. * Gets the internal step used by deterministic lock step
  24619. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24620. * @returns the internal step
  24621. */
  24622. Scene.prototype.getInternalStep = function () {
  24623. return this._currentInternalStep;
  24624. };
  24625. ;
  24626. Object.defineProperty(Scene.prototype, "fogEnabled", {
  24627. get: function () {
  24628. return this._fogEnabled;
  24629. },
  24630. /**
  24631. * Gets or sets a boolean indicating if fog is enabled on this scene
  24632. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24633. */
  24634. set: function (value) {
  24635. if (this._fogEnabled === value) {
  24636. return;
  24637. }
  24638. this._fogEnabled = value;
  24639. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24640. },
  24641. enumerable: true,
  24642. configurable: true
  24643. });
  24644. Object.defineProperty(Scene.prototype, "fogMode", {
  24645. get: function () {
  24646. return this._fogMode;
  24647. },
  24648. /**
  24649. * Gets or sets the fog mode to use
  24650. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24651. */
  24652. set: function (value) {
  24653. if (this._fogMode === value) {
  24654. return;
  24655. }
  24656. this._fogMode = value;
  24657. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24658. },
  24659. enumerable: true,
  24660. configurable: true
  24661. });
  24662. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  24663. get: function () {
  24664. return this._shadowsEnabled;
  24665. },
  24666. /**
  24667. * Gets or sets a boolean indicating if shadows are enabled on this scene
  24668. */
  24669. set: function (value) {
  24670. if (this._shadowsEnabled === value) {
  24671. return;
  24672. }
  24673. this._shadowsEnabled = value;
  24674. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24675. },
  24676. enumerable: true,
  24677. configurable: true
  24678. });
  24679. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  24680. get: function () {
  24681. return this._lightsEnabled;
  24682. },
  24683. /**
  24684. * Gets or sets a boolean indicating if lights are enabled on this scene
  24685. */
  24686. set: function (value) {
  24687. if (this._lightsEnabled === value) {
  24688. return;
  24689. }
  24690. this._lightsEnabled = value;
  24691. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24692. },
  24693. enumerable: true,
  24694. configurable: true
  24695. });
  24696. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  24697. /** The default material used on meshes when no material is affected */
  24698. get: function () {
  24699. if (!this._defaultMaterial) {
  24700. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  24701. }
  24702. return this._defaultMaterial;
  24703. },
  24704. /** The default material used on meshes when no material is affected */
  24705. set: function (value) {
  24706. this._defaultMaterial = value;
  24707. },
  24708. enumerable: true,
  24709. configurable: true
  24710. });
  24711. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  24712. get: function () {
  24713. return this._texturesEnabled;
  24714. },
  24715. /**
  24716. * Gets or sets a boolean indicating if textures are enabled on this scene
  24717. */
  24718. set: function (value) {
  24719. if (this._texturesEnabled === value) {
  24720. return;
  24721. }
  24722. this._texturesEnabled = value;
  24723. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24724. },
  24725. enumerable: true,
  24726. configurable: true
  24727. });
  24728. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  24729. get: function () {
  24730. return this._skeletonsEnabled;
  24731. },
  24732. /**
  24733. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  24734. */
  24735. set: function (value) {
  24736. if (this._skeletonsEnabled === value) {
  24737. return;
  24738. }
  24739. this._skeletonsEnabled = value;
  24740. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  24741. },
  24742. enumerable: true,
  24743. configurable: true
  24744. });
  24745. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  24746. /**
  24747. * Gets the postprocess render pipeline manager
  24748. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  24749. * @see http://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  24750. */
  24751. get: function () {
  24752. if (!this._postProcessRenderPipelineManager) {
  24753. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  24754. }
  24755. return this._postProcessRenderPipelineManager;
  24756. },
  24757. enumerable: true,
  24758. configurable: true
  24759. });
  24760. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  24761. /**
  24762. * Gets the main soundtrack associated with the scene
  24763. */
  24764. get: function () {
  24765. if (!this._mainSoundTrack) {
  24766. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  24767. }
  24768. return this._mainSoundTrack;
  24769. },
  24770. enumerable: true,
  24771. configurable: true
  24772. });
  24773. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  24774. /** @hidden */
  24775. get: function () {
  24776. return this._alternateRendering;
  24777. },
  24778. enumerable: true,
  24779. configurable: true
  24780. });
  24781. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  24782. /**
  24783. * Gets the list of frustum planes (built from the active camera)
  24784. */
  24785. get: function () {
  24786. return this._frustumPlanes;
  24787. },
  24788. enumerable: true,
  24789. configurable: true
  24790. });
  24791. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  24792. /**
  24793. * Gets the current geometry buffer associated to the scene.
  24794. */
  24795. get: function () {
  24796. return this._geometryBufferRenderer;
  24797. },
  24798. /**
  24799. * Sets the current geometry buffer for the scene.
  24800. */
  24801. set: function (geometryBufferRenderer) {
  24802. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  24803. this._geometryBufferRenderer = geometryBufferRenderer;
  24804. }
  24805. },
  24806. enumerable: true,
  24807. configurable: true
  24808. });
  24809. Object.defineProperty(Scene.prototype, "debugLayer", {
  24810. /**
  24811. * Gets the debug layer (aka Inspector) associated with the scene
  24812. * @see http://doc.babylonjs.com/features/playground_debuglayer
  24813. */
  24814. get: function () {
  24815. if (!this._debugLayer) {
  24816. this._debugLayer = new BABYLON.DebugLayer(this);
  24817. }
  24818. return this._debugLayer;
  24819. },
  24820. enumerable: true,
  24821. configurable: true
  24822. });
  24823. Object.defineProperty(Scene.prototype, "workerCollisions", {
  24824. /**
  24825. * Gets a boolean indicating if collisions are processed on a web worker
  24826. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  24827. */
  24828. get: function () {
  24829. return this._workerCollisions;
  24830. },
  24831. set: function (enabled) {
  24832. if (!BABYLON.CollisionCoordinatorLegacy) {
  24833. return;
  24834. }
  24835. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  24836. this._workerCollisions = enabled;
  24837. if (this.collisionCoordinator) {
  24838. this.collisionCoordinator.destroy();
  24839. }
  24840. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  24841. this.collisionCoordinator.init(this);
  24842. },
  24843. enumerable: true,
  24844. configurable: true
  24845. });
  24846. Object.defineProperty(Scene.prototype, "selectionOctree", {
  24847. /**
  24848. * Gets the octree used to boost mesh selection (picking)
  24849. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  24850. */
  24851. get: function () {
  24852. return this._selectionOctree;
  24853. },
  24854. enumerable: true,
  24855. configurable: true
  24856. });
  24857. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  24858. /**
  24859. * Gets the mesh that is currently under the pointer
  24860. */
  24861. get: function () {
  24862. return this._pointerOverMesh;
  24863. },
  24864. enumerable: true,
  24865. configurable: true
  24866. });
  24867. Object.defineProperty(Scene.prototype, "pointerX", {
  24868. /**
  24869. * Gets the current on-screen X position of the pointer
  24870. */
  24871. get: function () {
  24872. return this._pointerX;
  24873. },
  24874. enumerable: true,
  24875. configurable: true
  24876. });
  24877. Object.defineProperty(Scene.prototype, "pointerY", {
  24878. /**
  24879. * Gets the current on-screen Y position of the pointer
  24880. */
  24881. get: function () {
  24882. return this._pointerY;
  24883. },
  24884. enumerable: true,
  24885. configurable: true
  24886. });
  24887. /**
  24888. * Gets the cached material (ie. the latest rendered one)
  24889. * @returns the cached material
  24890. */
  24891. Scene.prototype.getCachedMaterial = function () {
  24892. return this._cachedMaterial;
  24893. };
  24894. /**
  24895. * Gets the cached effect (ie. the latest rendered one)
  24896. * @returns the cached effect
  24897. */
  24898. Scene.prototype.getCachedEffect = function () {
  24899. return this._cachedEffect;
  24900. };
  24901. /**
  24902. * Gets the cached visibility state (ie. the latest rendered one)
  24903. * @returns the cached visibility state
  24904. */
  24905. Scene.prototype.getCachedVisibility = function () {
  24906. return this._cachedVisibility;
  24907. };
  24908. /**
  24909. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  24910. * @param material defines the current material
  24911. * @param effect defines the current effect
  24912. * @param visibility defines the current visibility state
  24913. * @returns true if one parameter is not cached
  24914. */
  24915. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  24916. if (visibility === void 0) { visibility = 1; }
  24917. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  24918. };
  24919. /**
  24920. * Gets the bounding box renderer associated with the scene
  24921. * @returns a BoundingBoxRenderer
  24922. */
  24923. Scene.prototype.getBoundingBoxRenderer = function () {
  24924. if (!this._boundingBoxRenderer) {
  24925. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  24926. }
  24927. return this._boundingBoxRenderer;
  24928. };
  24929. /**
  24930. * Gets the outline renderer associated with the scene
  24931. * @returns a OutlineRenderer
  24932. */
  24933. Scene.prototype.getOutlineRenderer = function () {
  24934. return this._outlineRenderer;
  24935. };
  24936. /**
  24937. * Gets the engine associated with the scene
  24938. * @returns an Engine
  24939. */
  24940. Scene.prototype.getEngine = function () {
  24941. return this._engine;
  24942. };
  24943. /**
  24944. * Gets the total number of vertices rendered per frame
  24945. * @returns the total number of vertices rendered per frame
  24946. */
  24947. Scene.prototype.getTotalVertices = function () {
  24948. return this._totalVertices.current;
  24949. };
  24950. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  24951. /**
  24952. * Gets the performance counter for total vertices
  24953. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24954. */
  24955. get: function () {
  24956. return this._totalVertices;
  24957. },
  24958. enumerable: true,
  24959. configurable: true
  24960. });
  24961. /**
  24962. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  24963. * @returns the total number of active indices rendered per frame
  24964. */
  24965. Scene.prototype.getActiveIndices = function () {
  24966. return this._activeIndices.current;
  24967. };
  24968. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  24969. /**
  24970. * Gets the performance counter for active indices
  24971. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24972. */
  24973. get: function () {
  24974. return this._activeIndices;
  24975. },
  24976. enumerable: true,
  24977. configurable: true
  24978. });
  24979. /**
  24980. * Gets the total number of active particles rendered per frame
  24981. * @returns the total number of active particles rendered per frame
  24982. */
  24983. Scene.prototype.getActiveParticles = function () {
  24984. return this._activeParticles.current;
  24985. };
  24986. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  24987. /**
  24988. * Gets the performance counter for active particles
  24989. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24990. */
  24991. get: function () {
  24992. return this._activeParticles;
  24993. },
  24994. enumerable: true,
  24995. configurable: true
  24996. });
  24997. /**
  24998. * Gets the total number of active bones rendered per frame
  24999. * @returns the total number of active bones rendered per frame
  25000. */
  25001. Scene.prototype.getActiveBones = function () {
  25002. return this._activeBones.current;
  25003. };
  25004. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  25005. /**
  25006. * Gets the performance counter for active bones
  25007. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25008. */
  25009. get: function () {
  25010. return this._activeBones;
  25011. },
  25012. enumerable: true,
  25013. configurable: true
  25014. });
  25015. /** @hidden */
  25016. Scene.prototype.getInterFramePerfCounter = function () {
  25017. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25018. return 0;
  25019. };
  25020. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  25021. /** @hidden */
  25022. get: function () {
  25023. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25024. return null;
  25025. },
  25026. enumerable: true,
  25027. configurable: true
  25028. });
  25029. /** @hidden */
  25030. Scene.prototype.getLastFrameDuration = function () {
  25031. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  25032. return 0;
  25033. };
  25034. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  25035. /** @hidden */
  25036. get: function () {
  25037. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25038. return null;
  25039. },
  25040. enumerable: true,
  25041. configurable: true
  25042. });
  25043. /** @hidden */
  25044. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  25045. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  25046. return 0;
  25047. };
  25048. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  25049. /** @hidden */
  25050. get: function () {
  25051. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25052. return null;
  25053. },
  25054. enumerable: true,
  25055. configurable: true
  25056. });
  25057. /**
  25058. * Gets the array of active meshes
  25059. * @returns an array of AbstractMesh
  25060. */
  25061. Scene.prototype.getActiveMeshes = function () {
  25062. return this._activeMeshes;
  25063. };
  25064. /** @hidden */
  25065. Scene.prototype.getRenderTargetsDuration = function () {
  25066. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  25067. return 0;
  25068. };
  25069. /** @hidden */
  25070. Scene.prototype.getRenderDuration = function () {
  25071. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  25072. return 0;
  25073. };
  25074. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  25075. /** @hidden */
  25076. get: function () {
  25077. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25078. return null;
  25079. },
  25080. enumerable: true,
  25081. configurable: true
  25082. });
  25083. /** @hidden */
  25084. Scene.prototype.getParticlesDuration = function () {
  25085. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  25086. return 0;
  25087. };
  25088. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  25089. /** @hidden */
  25090. get: function () {
  25091. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25092. return null;
  25093. },
  25094. enumerable: true,
  25095. configurable: true
  25096. });
  25097. /** @hidden */
  25098. Scene.prototype.getSpritesDuration = function () {
  25099. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  25100. return 0;
  25101. };
  25102. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  25103. /** @hidden */
  25104. get: function () {
  25105. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  25106. return null;
  25107. },
  25108. enumerable: true,
  25109. configurable: true
  25110. });
  25111. /**
  25112. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  25113. * @returns a number
  25114. */
  25115. Scene.prototype.getAnimationRatio = function () {
  25116. return this._animationRatio;
  25117. };
  25118. /**
  25119. * Gets an unique Id for the current frame
  25120. * @returns a number
  25121. */
  25122. Scene.prototype.getRenderId = function () {
  25123. return this._renderId;
  25124. };
  25125. /** Call this function if you want to manually increment the render Id*/
  25126. Scene.prototype.incrementRenderId = function () {
  25127. this._renderId++;
  25128. };
  25129. Scene.prototype._updatePointerPosition = function (evt) {
  25130. var canvasRect = this._engine.getRenderingCanvasClientRect();
  25131. if (!canvasRect) {
  25132. return;
  25133. }
  25134. this._pointerX = evt.clientX - canvasRect.left;
  25135. this._pointerY = evt.clientY - canvasRect.top;
  25136. this._unTranslatedPointerX = this._pointerX;
  25137. this._unTranslatedPointerY = this._pointerY;
  25138. };
  25139. Scene.prototype._createUbo = function () {
  25140. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  25141. this._sceneUbo.addUniform("viewProjection", 16);
  25142. this._sceneUbo.addUniform("view", 16);
  25143. };
  25144. Scene.prototype._createAlternateUbo = function () {
  25145. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  25146. this._alternateSceneUbo.addUniform("viewProjection", 16);
  25147. this._alternateSceneUbo.addUniform("view", 16);
  25148. };
  25149. // Pointers handling
  25150. Scene.prototype._pickSpriteButKeepRay = function (originalPointerInfo, x, y, predicate, fastCheck, camera) {
  25151. var result = this.pickSprite(x, y, predicate, fastCheck, camera);
  25152. if (result) {
  25153. result.ray = originalPointerInfo ? originalPointerInfo.ray : null;
  25154. }
  25155. return result;
  25156. };
  25157. Scene.prototype._setRayOnPointerInfo = function (pointerInfo) {
  25158. if (pointerInfo.pickInfo) {
  25159. if (!pointerInfo.pickInfo.ray) {
  25160. pointerInfo.pickInfo.ray = this.createPickingRay(pointerInfo.event.offsetX, pointerInfo.event.offsetY, BABYLON.Matrix.Identity(), this.activeCamera);
  25161. }
  25162. }
  25163. };
  25164. /**
  25165. * Use this method to simulate a pointer move on a mesh
  25166. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25167. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25168. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25169. * @returns the current scene
  25170. */
  25171. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  25172. var evt = new PointerEvent("pointermove", pointerEventInit);
  25173. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERMOVE)) {
  25174. return this;
  25175. }
  25176. return this._processPointerMove(pickResult, evt);
  25177. };
  25178. Scene.prototype._processPointerMove = function (pickResult, evt) {
  25179. var canvas = this._engine.getRenderingCanvas();
  25180. if (!canvas) {
  25181. return this;
  25182. }
  25183. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  25184. this.setPointerOverSprite(null);
  25185. this.setPointerOverMesh(pickResult.pickedMesh);
  25186. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  25187. if (this._pointerOverMesh.actionManager.hoverCursor) {
  25188. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  25189. }
  25190. else {
  25191. canvas.style.cursor = this.hoverCursor;
  25192. }
  25193. }
  25194. else {
  25195. canvas.style.cursor = this.defaultCursor;
  25196. }
  25197. }
  25198. else {
  25199. this.setPointerOverMesh(null);
  25200. // Sprites
  25201. pickResult = this._pickSpriteButKeepRay(pickResult, this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  25202. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  25203. this.setPointerOverSprite(pickResult.pickedSprite);
  25204. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  25205. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  25206. }
  25207. else {
  25208. canvas.style.cursor = this.hoverCursor;
  25209. }
  25210. }
  25211. else {
  25212. this.setPointerOverSprite(null);
  25213. // Restore pointer
  25214. canvas.style.cursor = this.defaultCursor;
  25215. }
  25216. }
  25217. if (pickResult) {
  25218. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  25219. if (this.onPointerMove) {
  25220. this.onPointerMove(evt, pickResult, type);
  25221. }
  25222. if (this.onPointerObservable.hasObservers()) {
  25223. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25224. this._setRayOnPointerInfo(pi);
  25225. this.onPointerObservable.notifyObservers(pi, type);
  25226. }
  25227. }
  25228. return this;
  25229. };
  25230. Scene.prototype._checkPrePointerObservable = function (pickResult, evt, type) {
  25231. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  25232. if (pickResult) {
  25233. pi.ray = pickResult.ray;
  25234. }
  25235. this.onPrePointerObservable.notifyObservers(pi, type);
  25236. if (pi.skipOnPointerObservable) {
  25237. return true;
  25238. }
  25239. else {
  25240. return false;
  25241. }
  25242. };
  25243. /**
  25244. * Use this method to simulate a pointer down on a mesh
  25245. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25246. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25247. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25248. * @returns the current scene
  25249. */
  25250. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  25251. var evt = new PointerEvent("pointerdown", pointerEventInit);
  25252. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25253. return this;
  25254. }
  25255. return this._processPointerDown(pickResult, evt);
  25256. };
  25257. Scene.prototype._processPointerDown = function (pickResult, evt) {
  25258. var _this = this;
  25259. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  25260. this._pickedDownMesh = pickResult.pickedMesh;
  25261. var actionManager = pickResult.pickedMesh.actionManager;
  25262. if (actionManager) {
  25263. if (actionManager.hasPickTriggers) {
  25264. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25265. switch (evt.button) {
  25266. case 0:
  25267. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25268. break;
  25269. case 1:
  25270. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25271. break;
  25272. case 2:
  25273. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25274. break;
  25275. }
  25276. }
  25277. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  25278. window.setTimeout(function () {
  25279. 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);
  25280. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  25281. if (_this._totalPointersPressed !== 0 &&
  25282. ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  25283. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  25284. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  25285. _this._startingPointerTime = 0;
  25286. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25287. }
  25288. }
  25289. }, Scene.LongPressDelay);
  25290. }
  25291. }
  25292. }
  25293. if (pickResult) {
  25294. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  25295. if (this.onPointerDown) {
  25296. this.onPointerDown(evt, pickResult, type);
  25297. }
  25298. if (this.onPointerObservable.hasObservers()) {
  25299. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25300. this._setRayOnPointerInfo(pi);
  25301. this.onPointerObservable.notifyObservers(pi, type);
  25302. }
  25303. }
  25304. return this;
  25305. };
  25306. /**
  25307. * Use this method to simulate a pointer up on a mesh
  25308. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25309. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25310. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25311. * @returns the current scene
  25312. */
  25313. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  25314. var evt = new PointerEvent("pointerup", pointerEventInit);
  25315. var clickInfo = new ClickInfo();
  25316. clickInfo.singleClick = true;
  25317. clickInfo.ignore = true;
  25318. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25319. return this;
  25320. }
  25321. return this._processPointerUp(pickResult, evt, clickInfo);
  25322. };
  25323. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  25324. if (pickResult && pickResult && pickResult.pickedMesh) {
  25325. this._pickedUpMesh = pickResult.pickedMesh;
  25326. if (this._pickedDownMesh === this._pickedUpMesh) {
  25327. if (this.onPointerPick) {
  25328. this.onPointerPick(evt, pickResult);
  25329. }
  25330. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  25331. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  25332. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  25333. this._setRayOnPointerInfo(pi);
  25334. this.onPointerObservable.notifyObservers(pi, type_1);
  25335. }
  25336. }
  25337. if (pickResult.pickedMesh.actionManager) {
  25338. if (clickInfo.ignore) {
  25339. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25340. }
  25341. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  25342. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25343. }
  25344. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25345. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25346. }
  25347. }
  25348. }
  25349. if (this._pickedDownMesh &&
  25350. this._pickedDownMesh.actionManager &&
  25351. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  25352. this._pickedDownMesh !== this._pickedUpMesh) {
  25353. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  25354. }
  25355. var type = BABYLON.PointerEventTypes.POINTERUP;
  25356. if (this.onPointerObservable.hasObservers()) {
  25357. if (!clickInfo.ignore) {
  25358. if (!clickInfo.hasSwiped) {
  25359. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25360. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  25361. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  25362. this._setRayOnPointerInfo(pi);
  25363. this.onPointerObservable.notifyObservers(pi, type_2);
  25364. }
  25365. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25366. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  25367. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  25368. this._setRayOnPointerInfo(pi);
  25369. this.onPointerObservable.notifyObservers(pi, type_3);
  25370. }
  25371. }
  25372. }
  25373. else {
  25374. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25375. this._setRayOnPointerInfo(pi);
  25376. this.onPointerObservable.notifyObservers(pi, type);
  25377. }
  25378. }
  25379. if (this.onPointerUp) {
  25380. this.onPointerUp(evt, pickResult, type);
  25381. }
  25382. return this;
  25383. };
  25384. /**
  25385. * Gets a boolean indicating if the current pointer event is captured (meaning that the scene has already handled the pointer down)
  25386. * @param pointerId defines the pointer id to use in a multi-touch scenario (0 by default)
  25387. * @returns true if the pointer was captured
  25388. */
  25389. Scene.prototype.isPointerCaptured = function (pointerId) {
  25390. if (pointerId === void 0) { pointerId = 0; }
  25391. return this._pointerCaptures[pointerId];
  25392. };
  25393. /**
  25394. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  25395. * @param attachUp defines if you want to attach events to pointerup
  25396. * @param attachDown defines if you want to attach events to pointerdown
  25397. * @param attachMove defines if you want to attach events to pointermove
  25398. */
  25399. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  25400. var _this = this;
  25401. if (attachUp === void 0) { attachUp = true; }
  25402. if (attachDown === void 0) { attachDown = true; }
  25403. if (attachMove === void 0) { attachMove = true; }
  25404. this._initActionManager = function (act, clickInfo) {
  25405. if (!_this._meshPickProceed) {
  25406. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25407. _this._currentPickResult = pickResult;
  25408. if (pickResult) {
  25409. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  25410. }
  25411. _this._meshPickProceed = true;
  25412. }
  25413. return act;
  25414. };
  25415. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  25416. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  25417. if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  25418. btn !== _this._previousButtonPressed) {
  25419. _this._doubleClickOccured = false;
  25420. clickInfo.singleClick = true;
  25421. clickInfo.ignore = false;
  25422. cb(clickInfo, _this._currentPickResult);
  25423. }
  25424. };
  25425. this._initClickEvent = function (obs1, obs2, evt, cb) {
  25426. var clickInfo = new ClickInfo();
  25427. _this._currentPickResult = null;
  25428. var act = null;
  25429. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  25430. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  25431. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25432. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  25433. act = _this._initActionManager(act, clickInfo);
  25434. if (act)
  25435. checkPicking = act.hasPickTriggers;
  25436. }
  25437. if (checkPicking) {
  25438. var btn = evt.button;
  25439. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  25440. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  25441. if (!clickInfo.hasSwiped) {
  25442. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  25443. if (!checkSingleClickImmediately) {
  25444. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  25445. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25446. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25447. act = _this._initActionManager(act, clickInfo);
  25448. if (act)
  25449. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25450. }
  25451. }
  25452. if (checkSingleClickImmediately) {
  25453. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  25454. if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  25455. btn !== _this._previousButtonPressed) {
  25456. clickInfo.singleClick = true;
  25457. cb(clickInfo, _this._currentPickResult);
  25458. }
  25459. }
  25460. // at least one double click is required to be check and exclusive double click is enabled
  25461. else {
  25462. // wait that no double click has been raised during the double click delay
  25463. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25464. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  25465. }
  25466. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  25467. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25468. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25469. act = _this._initActionManager(act, clickInfo);
  25470. if (act)
  25471. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25472. }
  25473. if (checkDoubleClick) {
  25474. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  25475. if (btn === _this._previousButtonPressed &&
  25476. Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  25477. !_this._doubleClickOccured) {
  25478. // pointer has not moved for 2 clicks, it's a double click
  25479. if (!clickInfo.hasSwiped &&
  25480. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  25481. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  25482. _this._previousStartingPointerTime = 0;
  25483. _this._doubleClickOccured = true;
  25484. clickInfo.doubleClick = true;
  25485. clickInfo.ignore = false;
  25486. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  25487. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25488. }
  25489. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25490. cb(clickInfo, _this._currentPickResult);
  25491. }
  25492. // if the two successive clicks are too far, it's just two simple clicks
  25493. else {
  25494. _this._doubleClickOccured = false;
  25495. _this._previousStartingPointerTime = _this._startingPointerTime;
  25496. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25497. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25498. _this._previousButtonPressed = btn;
  25499. if (Scene.ExclusiveDoubleClickMode) {
  25500. if (_this._previousDelayedSimpleClickTimeout) {
  25501. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25502. }
  25503. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25504. cb(clickInfo, _this._previousPickResult);
  25505. }
  25506. else {
  25507. cb(clickInfo, _this._currentPickResult);
  25508. }
  25509. }
  25510. }
  25511. // just the first click of the double has been raised
  25512. else {
  25513. _this._doubleClickOccured = false;
  25514. _this._previousStartingPointerTime = _this._startingPointerTime;
  25515. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25516. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25517. _this._previousButtonPressed = btn;
  25518. }
  25519. }
  25520. }
  25521. }
  25522. clickInfo.ignore = true;
  25523. cb(clickInfo, _this._currentPickResult);
  25524. };
  25525. this._spritePredicate = function (sprite) {
  25526. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  25527. };
  25528. this._onPointerMove = function (evt) {
  25529. _this._updatePointerPosition(evt);
  25530. // PreObservable support
  25531. if (_this._checkPrePointerObservable(null, evt, evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE)) {
  25532. return;
  25533. }
  25534. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25535. return;
  25536. }
  25537. if (!_this.pointerMovePredicate) {
  25538. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  25539. }
  25540. // Meshes
  25541. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  25542. _this._processPointerMove(pickResult, evt);
  25543. };
  25544. this._onPointerDown = function (evt) {
  25545. _this._totalPointersPressed++;
  25546. _this._pickedDownMesh = null;
  25547. _this._meshPickProceed = false;
  25548. _this._updatePointerPosition(evt);
  25549. if (_this.preventDefaultOnPointerDown && canvas) {
  25550. evt.preventDefault();
  25551. canvas.focus();
  25552. }
  25553. // PreObservable support
  25554. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25555. return;
  25556. }
  25557. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25558. return;
  25559. }
  25560. _this._pointerCaptures[evt.pointerId] = true;
  25561. _this._startingPointerPosition.x = _this._pointerX;
  25562. _this._startingPointerPosition.y = _this._pointerY;
  25563. _this._startingPointerTime = Date.now();
  25564. if (!_this.pointerDownPredicate) {
  25565. _this.pointerDownPredicate = function (mesh) {
  25566. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25567. };
  25568. }
  25569. // Meshes
  25570. _this._pickedDownMesh = null;
  25571. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25572. _this._processPointerDown(pickResult, evt);
  25573. // Sprites
  25574. _this._pickedDownSprite = null;
  25575. if (_this.spriteManagers.length > 0) {
  25576. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25577. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  25578. if (pickResult.pickedSprite.actionManager) {
  25579. _this._pickedDownSprite = pickResult.pickedSprite;
  25580. switch (evt.button) {
  25581. case 0:
  25582. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25583. break;
  25584. case 1:
  25585. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25586. break;
  25587. case 2:
  25588. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25589. break;
  25590. }
  25591. if (pickResult.pickedSprite.actionManager) {
  25592. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25593. }
  25594. }
  25595. }
  25596. }
  25597. };
  25598. this._onPointerUp = function (evt) {
  25599. if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  25600. return; // So we need to test it the pointer down was pressed before.
  25601. }
  25602. _this._totalPointersPressed--;
  25603. _this._pickedUpMesh = null;
  25604. _this._meshPickProceed = false;
  25605. _this._updatePointerPosition(evt);
  25606. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  25607. // PreObservable support
  25608. if (_this.onPrePointerObservable.hasObservers()) {
  25609. if (!clickInfo.ignore) {
  25610. if (!clickInfo.hasSwiped) {
  25611. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25612. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERTAP)) {
  25613. return;
  25614. }
  25615. }
  25616. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25617. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25618. return;
  25619. }
  25620. }
  25621. }
  25622. }
  25623. else {
  25624. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25625. return;
  25626. }
  25627. }
  25628. }
  25629. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25630. return;
  25631. }
  25632. _this._pointerCaptures[evt.pointerId] = false;
  25633. if (!_this.pointerUpPredicate) {
  25634. _this.pointerUpPredicate = function (mesh) {
  25635. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25636. };
  25637. }
  25638. // Meshes
  25639. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  25640. _this._initActionManager(null, clickInfo);
  25641. }
  25642. if (!pickResult) {
  25643. pickResult = _this._currentPickResult;
  25644. }
  25645. _this._processPointerUp(pickResult, evt, clickInfo);
  25646. // Sprites
  25647. if (!clickInfo.ignore) {
  25648. if (_this.spriteManagers.length > 0) {
  25649. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25650. if (spritePickResult) {
  25651. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  25652. if (spritePickResult.pickedSprite.actionManager) {
  25653. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25654. if (spritePickResult.pickedSprite.actionManager) {
  25655. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  25656. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25657. }
  25658. }
  25659. }
  25660. }
  25661. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  25662. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  25663. }
  25664. }
  25665. }
  25666. }
  25667. _this._previousPickResult = _this._currentPickResult;
  25668. });
  25669. };
  25670. this._onKeyDown = function (evt) {
  25671. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  25672. if (_this.onPreKeyboardObservable.hasObservers()) {
  25673. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25674. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25675. if (pi.skipOnPointerObservable) {
  25676. return;
  25677. }
  25678. }
  25679. if (_this.onKeyboardObservable.hasObservers()) {
  25680. var pi = new BABYLON.KeyboardInfo(type, evt);
  25681. _this.onKeyboardObservable.notifyObservers(pi, type);
  25682. }
  25683. if (_this.actionManager) {
  25684. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25685. }
  25686. };
  25687. this._onKeyUp = function (evt) {
  25688. var type = BABYLON.KeyboardEventTypes.KEYUP;
  25689. if (_this.onPreKeyboardObservable.hasObservers()) {
  25690. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25691. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25692. if (pi.skipOnPointerObservable) {
  25693. return;
  25694. }
  25695. }
  25696. if (_this.onKeyboardObservable.hasObservers()) {
  25697. var pi = new BABYLON.KeyboardInfo(type, evt);
  25698. _this.onKeyboardObservable.notifyObservers(pi, type);
  25699. }
  25700. if (_this.actionManager) {
  25701. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25702. }
  25703. };
  25704. var engine = this.getEngine();
  25705. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  25706. if (!canvas) {
  25707. return;
  25708. }
  25709. canvas.addEventListener("keydown", _this._onKeyDown, false);
  25710. canvas.addEventListener("keyup", _this._onKeyUp, false);
  25711. });
  25712. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  25713. if (!canvas) {
  25714. return;
  25715. }
  25716. canvas.removeEventListener("keydown", _this._onKeyDown);
  25717. canvas.removeEventListener("keyup", _this._onKeyUp);
  25718. });
  25719. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25720. var canvas = this._engine.getRenderingCanvas();
  25721. if (!canvas) {
  25722. return;
  25723. }
  25724. if (attachMove) {
  25725. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  25726. // Wheel
  25727. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  25728. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  25729. }
  25730. if (attachDown) {
  25731. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  25732. }
  25733. if (attachUp) {
  25734. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  25735. }
  25736. canvas.tabIndex = 1;
  25737. };
  25738. /** Detaches all event handlers*/
  25739. Scene.prototype.detachControl = function () {
  25740. var engine = this.getEngine();
  25741. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25742. var canvas = engine.getRenderingCanvas();
  25743. if (!canvas) {
  25744. return;
  25745. }
  25746. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  25747. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  25748. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  25749. if (this._onCanvasBlurObserver) {
  25750. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  25751. }
  25752. if (this._onCanvasFocusObserver) {
  25753. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  25754. }
  25755. // Wheel
  25756. canvas.removeEventListener('mousewheel', this._onPointerMove);
  25757. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  25758. // Keyboard
  25759. canvas.removeEventListener("keydown", this._onKeyDown);
  25760. canvas.removeEventListener("keyup", this._onKeyUp);
  25761. // Observables
  25762. this.onKeyboardObservable.clear();
  25763. this.onPreKeyboardObservable.clear();
  25764. this.onPointerObservable.clear();
  25765. this.onPrePointerObservable.clear();
  25766. };
  25767. /**
  25768. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  25769. * Delay loaded resources are not taking in account
  25770. * @return true if all required resources are ready
  25771. */
  25772. Scene.prototype.isReady = function () {
  25773. if (this._isDisposed) {
  25774. return false;
  25775. }
  25776. if (this._pendingData.length > 0) {
  25777. return false;
  25778. }
  25779. var index;
  25780. var engine = this.getEngine();
  25781. // Geometries
  25782. for (index = 0; index < this._geometries.length; index++) {
  25783. var geometry = this._geometries[index];
  25784. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25785. return false;
  25786. }
  25787. }
  25788. // Meshes
  25789. for (index = 0; index < this.meshes.length; index++) {
  25790. var mesh = this.meshes[index];
  25791. if (!mesh.isEnabled()) {
  25792. continue;
  25793. }
  25794. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  25795. continue;
  25796. }
  25797. if (!mesh.isReady(true)) {
  25798. return false;
  25799. }
  25800. // Effect layers
  25801. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  25802. for (var _i = 0, _a = this.effectLayers; _i < _a.length; _i++) {
  25803. var layer = _a[_i];
  25804. if (!layer.hasMesh(mesh)) {
  25805. continue;
  25806. }
  25807. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  25808. var subMesh = _c[_b];
  25809. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  25810. return false;
  25811. }
  25812. }
  25813. }
  25814. }
  25815. // Post-processes
  25816. if (this.activeCameras && this.activeCameras.length > 0) {
  25817. for (var _d = 0, _e = this.activeCameras; _d < _e.length; _d++) {
  25818. var camera = _e[_d];
  25819. if (!camera.isReady(true)) {
  25820. return false;
  25821. }
  25822. }
  25823. }
  25824. else if (this.activeCamera) {
  25825. if (!this.activeCamera.isReady(true)) {
  25826. return false;
  25827. }
  25828. }
  25829. // Particles
  25830. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  25831. var particleSystem = _g[_f];
  25832. if (!particleSystem.isReady()) {
  25833. return false;
  25834. }
  25835. }
  25836. return true;
  25837. };
  25838. /** Resets all cached information relative to material (including effect and visibility) */
  25839. Scene.prototype.resetCachedMaterial = function () {
  25840. this._cachedMaterial = null;
  25841. this._cachedEffect = null;
  25842. this._cachedVisibility = null;
  25843. };
  25844. /**
  25845. * Registers a function to be called before every frame render
  25846. * @param func defines the function to register
  25847. */
  25848. Scene.prototype.registerBeforeRender = function (func) {
  25849. this.onBeforeRenderObservable.add(func);
  25850. };
  25851. /**
  25852. * Unregisters a function called before every frame render
  25853. * @param func defines the function to unregister
  25854. */
  25855. Scene.prototype.unregisterBeforeRender = function (func) {
  25856. this.onBeforeRenderObservable.removeCallback(func);
  25857. };
  25858. /**
  25859. * Registers a function to be called after every frame render
  25860. * @param func defines the function to register
  25861. */
  25862. Scene.prototype.registerAfterRender = function (func) {
  25863. this.onAfterRenderObservable.add(func);
  25864. };
  25865. /**
  25866. * Unregisters a function called after every frame render
  25867. * @param func defines the function to unregister
  25868. */
  25869. Scene.prototype.unregisterAfterRender = function (func) {
  25870. this.onAfterRenderObservable.removeCallback(func);
  25871. };
  25872. Scene.prototype._executeOnceBeforeRender = function (func) {
  25873. var _this = this;
  25874. var execFunc = function () {
  25875. func();
  25876. setTimeout(function () {
  25877. _this.unregisterBeforeRender(execFunc);
  25878. });
  25879. };
  25880. this.registerBeforeRender(execFunc);
  25881. };
  25882. /**
  25883. * The provided function will run before render once and will be disposed afterwards.
  25884. * A timeout delay can be provided so that the function will be executed in N ms.
  25885. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  25886. * @param func The function to be executed.
  25887. * @param timeout optional delay in ms
  25888. */
  25889. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  25890. var _this = this;
  25891. if (timeout !== undefined) {
  25892. setTimeout(function () {
  25893. _this._executeOnceBeforeRender(func);
  25894. }, timeout);
  25895. }
  25896. else {
  25897. this._executeOnceBeforeRender(func);
  25898. }
  25899. };
  25900. /** @hidden */
  25901. Scene.prototype._addPendingData = function (data) {
  25902. this._pendingData.push(data);
  25903. };
  25904. /** @hidden */
  25905. Scene.prototype._removePendingData = function (data) {
  25906. var wasLoading = this.isLoading;
  25907. var index = this._pendingData.indexOf(data);
  25908. if (index !== -1) {
  25909. this._pendingData.splice(index, 1);
  25910. }
  25911. if (wasLoading && !this.isLoading) {
  25912. this.onDataLoadedObservable.notifyObservers(this);
  25913. }
  25914. };
  25915. /**
  25916. * Returns the number of items waiting to be loaded
  25917. * @returns the number of items waiting to be loaded
  25918. */
  25919. Scene.prototype.getWaitingItemsCount = function () {
  25920. return this._pendingData.length;
  25921. };
  25922. Object.defineProperty(Scene.prototype, "isLoading", {
  25923. /**
  25924. * Returns a boolean indicating if the scene is still loading data
  25925. */
  25926. get: function () {
  25927. return this._pendingData.length > 0;
  25928. },
  25929. enumerable: true,
  25930. configurable: true
  25931. });
  25932. /**
  25933. * Registers a function to be executed when the scene is ready
  25934. * @param {Function} func - the function to be executed
  25935. */
  25936. Scene.prototype.executeWhenReady = function (func) {
  25937. var _this = this;
  25938. this.onReadyObservable.add(func);
  25939. if (this._executeWhenReadyTimeoutId !== -1) {
  25940. return;
  25941. }
  25942. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25943. _this._checkIsReady();
  25944. }, 150);
  25945. };
  25946. /**
  25947. * Returns a promise that resolves when the scene is ready
  25948. * @returns A promise that resolves when the scene is ready
  25949. */
  25950. Scene.prototype.whenReadyAsync = function () {
  25951. var _this = this;
  25952. return new Promise(function (resolve) {
  25953. _this.executeWhenReady(function () {
  25954. resolve();
  25955. });
  25956. });
  25957. };
  25958. /** @hidden */
  25959. Scene.prototype._checkIsReady = function () {
  25960. var _this = this;
  25961. if (this.isReady()) {
  25962. this.onReadyObservable.notifyObservers(this);
  25963. this.onReadyObservable.clear();
  25964. this._executeWhenReadyTimeoutId = -1;
  25965. return;
  25966. }
  25967. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25968. _this._checkIsReady();
  25969. }, 150);
  25970. };
  25971. // Animations
  25972. /**
  25973. * Will start the animation sequence of a given target
  25974. * @param target defines the target
  25975. * @param from defines from which frame should animation start
  25976. * @param to defines until which frame should animation run.
  25977. * @param weight defines the weight to apply to the animation (1.0 by default)
  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. * @returns the animatable object created for this animation
  25983. */
  25984. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable) {
  25985. if (weight === void 0) { weight = 1.0; }
  25986. if (speedRatio === void 0) { speedRatio = 1.0; }
  25987. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false);
  25988. returnedAnimatable.weight = weight;
  25989. return returnedAnimatable;
  25990. };
  25991. /**
  25992. * Will start the animation sequence of a given target
  25993. * @param target defines the target
  25994. * @param from defines from which frame should animation start
  25995. * @param to defines until which frame should animation run.
  25996. * @param loop defines if the animation loops
  25997. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25998. * @param onAnimationEnd defines the function to be executed when the animation ends
  25999. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  26000. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  26001. * @returns the animatable object created for this animation
  26002. */
  26003. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent) {
  26004. if (speedRatio === void 0) { speedRatio = 1.0; }
  26005. if (stopCurrent === void 0) { stopCurrent = true; }
  26006. if (from > to && speedRatio > 0) {
  26007. speedRatio *= -1;
  26008. }
  26009. if (stopCurrent) {
  26010. this.stopAnimation(target);
  26011. }
  26012. if (!animatable) {
  26013. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  26014. }
  26015. // Local animations
  26016. if (target.animations) {
  26017. animatable.appendAnimations(target, target.animations);
  26018. }
  26019. // Children animations
  26020. if (target.getAnimatables) {
  26021. var animatables = target.getAnimatables();
  26022. for (var index = 0; index < animatables.length; index++) {
  26023. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent);
  26024. }
  26025. }
  26026. animatable.reset();
  26027. return animatable;
  26028. };
  26029. /**
  26030. * Begin a new animation on a given node
  26031. * @param target defines the target where the animation will take place
  26032. * @param animations defines the list of animations to start
  26033. * @param from defines the initial value
  26034. * @param to defines the final value
  26035. * @param loop defines if you want animation to loop (off by default)
  26036. * @param speedRatio defines the speed ratio to apply to all animations
  26037. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  26038. * @returns the list of created animatables
  26039. */
  26040. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  26041. if (speedRatio === undefined) {
  26042. speedRatio = 1.0;
  26043. }
  26044. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  26045. return animatable;
  26046. };
  26047. /**
  26048. * Begin a new animation on a given node and its hierarchy
  26049. * @param target defines the root node where the animation will take place
  26050. * @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.
  26051. * @param animations defines the list of animations to start
  26052. * @param from defines the initial value
  26053. * @param to defines the final value
  26054. * @param loop defines if you want animation to loop (off by default)
  26055. * @param speedRatio defines the speed ratio to apply to all animations
  26056. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  26057. * @returns the list of animatables created for all nodes
  26058. */
  26059. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  26060. var children = target.getDescendants(directDescendantsOnly);
  26061. var result = [];
  26062. result.push(this.beginDirectAnimation(target, animations, from, to, loop, speedRatio, onAnimationEnd));
  26063. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  26064. var child = children_1[_i];
  26065. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  26066. }
  26067. return result;
  26068. };
  26069. /**
  26070. * Gets the animatable associated with a specific target
  26071. * @param target defines the target of the animatable
  26072. * @returns the required animatable if found
  26073. */
  26074. Scene.prototype.getAnimatableByTarget = function (target) {
  26075. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26076. if (this._activeAnimatables[index].target === target) {
  26077. return this._activeAnimatables[index];
  26078. }
  26079. }
  26080. return null;
  26081. };
  26082. /**
  26083. * Gets all animatables associated with a given target
  26084. * @param target defines the target to look animatables for
  26085. * @returns an array of Animatables
  26086. */
  26087. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  26088. var result = [];
  26089. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26090. if (this._activeAnimatables[index].target === target) {
  26091. result.push(this._activeAnimatables[index]);
  26092. }
  26093. }
  26094. return result;
  26095. };
  26096. Object.defineProperty(Scene.prototype, "animatables", {
  26097. /**
  26098. * Gets all animatable attached to the scene
  26099. */
  26100. get: function () {
  26101. return this._activeAnimatables;
  26102. },
  26103. enumerable: true,
  26104. configurable: true
  26105. });
  26106. /**
  26107. * Will stop the animation of the given target
  26108. * @param target - the target
  26109. * @param animationName - the name of the animation to stop (all animations will be stopped if empty)
  26110. */
  26111. Scene.prototype.stopAnimation = function (target, animationName) {
  26112. var animatables = this.getAllAnimatablesByTarget(target);
  26113. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  26114. var animatable = animatables_1[_i];
  26115. animatable.stop(animationName);
  26116. }
  26117. };
  26118. /**
  26119. * Stops and removes all animations that have been applied to the scene
  26120. */
  26121. Scene.prototype.stopAllAnimations = function () {
  26122. if (this._activeAnimatables) {
  26123. for (var i = 0; i < this._activeAnimatables.length; i++) {
  26124. this._activeAnimatables[i].stop();
  26125. }
  26126. this._activeAnimatables = [];
  26127. }
  26128. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  26129. var group = _a[_i];
  26130. group.stop();
  26131. }
  26132. };
  26133. Scene.prototype._animate = function () {
  26134. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  26135. return;
  26136. }
  26137. // Getting time
  26138. var now = BABYLON.Tools.Now;
  26139. if (!this._animationTimeLast) {
  26140. if (this._pendingData.length > 0) {
  26141. return;
  26142. }
  26143. this._animationTimeLast = now;
  26144. }
  26145. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  26146. this._animationTime += deltaTime;
  26147. this._animationTimeLast = now;
  26148. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26149. this._activeAnimatables[index]._animate(this._animationTime);
  26150. }
  26151. // Late animation bindings
  26152. this._processLateAnimationBindings();
  26153. };
  26154. /** @hidden */
  26155. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation, originalValue) {
  26156. var target = runtimeAnimation.target;
  26157. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  26158. if (!target._lateAnimationHolders) {
  26159. target._lateAnimationHolders = {};
  26160. }
  26161. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  26162. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  26163. totalWeight: 0,
  26164. animations: [],
  26165. originalValue: originalValue
  26166. };
  26167. }
  26168. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  26169. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  26170. };
  26171. Scene.prototype._processLateAnimationBindingsForMatrices = function (holder) {
  26172. var normalizer = 1.0;
  26173. var finalPosition = BABYLON.Tmp.Vector3[0];
  26174. var finalScaling = BABYLON.Tmp.Vector3[1];
  26175. var finalQuaternion = BABYLON.Tmp.Quaternion[0];
  26176. var startIndex = 0;
  26177. var originalAnimation = holder.animations[0];
  26178. var originalValue = holder.originalValue;
  26179. var scale = 1;
  26180. if (holder.totalWeight < 1.0) {
  26181. // We need to mix the original value in
  26182. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  26183. scale = 1.0 - holder.totalWeight;
  26184. }
  26185. else {
  26186. startIndex = 1;
  26187. // We need to normalize the weights
  26188. normalizer = holder.totalWeight;
  26189. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  26190. scale = originalAnimation.weight / normalizer;
  26191. if (scale == 1) {
  26192. return originalAnimation.currentValue;
  26193. }
  26194. }
  26195. finalScaling.scaleInPlace(scale);
  26196. finalPosition.scaleInPlace(scale);
  26197. finalQuaternion.scaleInPlace(scale);
  26198. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26199. var runtimeAnimation = holder.animations[animIndex];
  26200. var scale = runtimeAnimation.weight / normalizer;
  26201. var currentPosition = BABYLON.Tmp.Vector3[2];
  26202. var currentScaling = BABYLON.Tmp.Vector3[3];
  26203. var currentQuaternion = BABYLON.Tmp.Quaternion[1];
  26204. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  26205. currentScaling.scaleAndAddToRef(scale, finalScaling);
  26206. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  26207. currentPosition.scaleAndAddToRef(scale, finalPosition);
  26208. }
  26209. BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  26210. return originalAnimation._workValue;
  26211. };
  26212. Scene.prototype._processLateAnimationBindingsForQuaternions = function (holder) {
  26213. var originalAnimation = holder.animations[0];
  26214. var originalValue = holder.originalValue;
  26215. if (holder.animations.length === 1) {
  26216. return BABYLON.Quaternion.Slerp(originalValue, originalAnimation.currentValue, Math.min(1.0, holder.totalWeight));
  26217. }
  26218. var normalizer = 1.0;
  26219. var quaternions;
  26220. var weights;
  26221. if (holder.totalWeight < 1.0) {
  26222. var scale = 1.0 - holder.totalWeight;
  26223. quaternions = [];
  26224. weights = [];
  26225. quaternions.push(originalValue);
  26226. weights.push(scale);
  26227. }
  26228. else {
  26229. if (holder.animations.length === 2) { // Slerp as soon as we can
  26230. return BABYLON.Quaternion.Slerp(holder.animations[0].currentValue, holder.animations[1].currentValue, holder.animations[1].weight / holder.totalWeight);
  26231. }
  26232. quaternions = [];
  26233. weights = [];
  26234. normalizer = holder.totalWeight;
  26235. }
  26236. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  26237. var runtimeAnimation = holder.animations[animIndex];
  26238. quaternions.push(runtimeAnimation.currentValue);
  26239. weights.push(runtimeAnimation.weight / normalizer);
  26240. }
  26241. // https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions
  26242. var cumulativeAmount = 0;
  26243. var cumulativeQuaternion = null;
  26244. for (var index = 0; index < quaternions.length;) {
  26245. if (!cumulativeQuaternion) {
  26246. cumulativeQuaternion = BABYLON.Quaternion.Slerp(quaternions[index], quaternions[index + 1], weights[index + 1] / (weights[index] + weights[index + 1]));
  26247. cumulativeAmount = weights[index] + weights[index + 1];
  26248. index += 2;
  26249. continue;
  26250. }
  26251. cumulativeAmount += weights[index];
  26252. BABYLON.Quaternion.SlerpToRef(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount, cumulativeQuaternion);
  26253. index++;
  26254. }
  26255. return cumulativeQuaternion;
  26256. };
  26257. Scene.prototype._processLateAnimationBindings = function () {
  26258. if (!this._registeredForLateAnimationBindings.length) {
  26259. return;
  26260. }
  26261. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  26262. var target = this._registeredForLateAnimationBindings.data[index];
  26263. for (var path in target._lateAnimationHolders) {
  26264. var holder = target._lateAnimationHolders[path];
  26265. var originalAnimation = holder.animations[0];
  26266. var originalValue = holder.originalValue;
  26267. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  26268. var finalValue = void 0;
  26269. if (matrixDecomposeMode) {
  26270. finalValue = this._processLateAnimationBindingsForMatrices(holder);
  26271. }
  26272. else {
  26273. var quaternionMode = originalValue.w !== undefined;
  26274. if (quaternionMode) {
  26275. finalValue = this._processLateAnimationBindingsForQuaternions(holder);
  26276. }
  26277. else {
  26278. var startIndex = 0;
  26279. var normalizer = 1.0;
  26280. if (holder.totalWeight < 1.0) {
  26281. // We need to mix the original value in
  26282. if (originalValue.scale) {
  26283. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  26284. }
  26285. else {
  26286. finalValue = originalValue * (1.0 - holder.totalWeight);
  26287. }
  26288. }
  26289. else {
  26290. // We need to normalize the weights
  26291. normalizer = holder.totalWeight;
  26292. var scale_1 = originalAnimation.weight / normalizer;
  26293. if (scale_1 !== 1) {
  26294. if (originalAnimation.currentValue.scale) {
  26295. finalValue = originalAnimation.currentValue.scale(scale_1);
  26296. }
  26297. else {
  26298. finalValue = originalAnimation.currentValue * scale_1;
  26299. }
  26300. }
  26301. else {
  26302. finalValue = originalAnimation.currentValue;
  26303. }
  26304. startIndex = 1;
  26305. }
  26306. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26307. var runtimeAnimation = holder.animations[animIndex];
  26308. var scale = runtimeAnimation.weight / normalizer;
  26309. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  26310. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  26311. }
  26312. else {
  26313. finalValue += runtimeAnimation.currentValue * scale;
  26314. }
  26315. }
  26316. }
  26317. }
  26318. target[path] = finalValue;
  26319. }
  26320. target._lateAnimationHolders = {};
  26321. }
  26322. this._registeredForLateAnimationBindings.reset();
  26323. };
  26324. // Matrix
  26325. /** @hidden */
  26326. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  26327. this._useAlternateCameraConfiguration = active;
  26328. };
  26329. /**
  26330. * Gets the current view matrix
  26331. * @returns a Matrix
  26332. */
  26333. Scene.prototype.getViewMatrix = function () {
  26334. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  26335. };
  26336. /**
  26337. * Gets the current projection matrix
  26338. * @returns a Matrix
  26339. */
  26340. Scene.prototype.getProjectionMatrix = function () {
  26341. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  26342. };
  26343. /**
  26344. * Gets the current transform matrix
  26345. * @returns a Matrix made of View * Projection
  26346. */
  26347. Scene.prototype.getTransformMatrix = function () {
  26348. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  26349. };
  26350. /**
  26351. * Sets the current transform matrix
  26352. * @param view defines the View matrix to use
  26353. * @param projection defines the Projection matrix to use
  26354. */
  26355. Scene.prototype.setTransformMatrix = function (view, projection) {
  26356. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  26357. return;
  26358. }
  26359. this._viewUpdateFlag = view.updateFlag;
  26360. this._projectionUpdateFlag = projection.updateFlag;
  26361. this._viewMatrix = view;
  26362. this._projectionMatrix = projection;
  26363. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  26364. // Update frustum
  26365. if (!this._frustumPlanes) {
  26366. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  26367. }
  26368. else {
  26369. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  26370. }
  26371. if (this.activeCamera && this.activeCamera._alternateCamera) {
  26372. var otherCamera = this.activeCamera._alternateCamera;
  26373. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  26374. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  26375. }
  26376. if (this._sceneUbo.useUbo) {
  26377. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  26378. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  26379. this._sceneUbo.update();
  26380. }
  26381. };
  26382. /** @hidden */
  26383. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  26384. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  26385. return;
  26386. }
  26387. this._alternateViewUpdateFlag = view.updateFlag;
  26388. this._alternateProjectionUpdateFlag = projection.updateFlag;
  26389. this._alternateViewMatrix = view;
  26390. this._alternateProjectionMatrix = projection;
  26391. if (!this._alternateTransformMatrix) {
  26392. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  26393. }
  26394. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  26395. if (!this._alternateSceneUbo) {
  26396. this._createAlternateUbo();
  26397. }
  26398. if (this._alternateSceneUbo.useUbo) {
  26399. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  26400. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  26401. this._alternateSceneUbo.update();
  26402. }
  26403. };
  26404. /**
  26405. * Gets the uniform buffer used to store scene data
  26406. * @returns a UniformBuffer
  26407. */
  26408. Scene.prototype.getSceneUniformBuffer = function () {
  26409. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  26410. };
  26411. /**
  26412. * Gets an unique (relatively to the current scene) Id
  26413. * @returns an unique number for the scene
  26414. */
  26415. Scene.prototype.getUniqueId = function () {
  26416. var result = Scene._uniqueIdCounter;
  26417. Scene._uniqueIdCounter++;
  26418. return result;
  26419. };
  26420. /**
  26421. * Add a mesh to the list of scene's meshes
  26422. * @param newMesh defines the mesh to add
  26423. * @param recursive if all child meshes should also be added to the scene
  26424. */
  26425. Scene.prototype.addMesh = function (newMesh, recursive) {
  26426. var _this = this;
  26427. if (recursive === void 0) { recursive = false; }
  26428. this.meshes.push(newMesh);
  26429. //notify the collision coordinator
  26430. if (this.collisionCoordinator) {
  26431. this.collisionCoordinator.onMeshAdded(newMesh);
  26432. }
  26433. newMesh._resyncLightSources();
  26434. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  26435. if (recursive) {
  26436. newMesh.getChildMeshes().forEach(function (m) {
  26437. _this.addMesh(m);
  26438. });
  26439. }
  26440. };
  26441. /**
  26442. * Remove a mesh for the list of scene's meshes
  26443. * @param toRemove defines the mesh to remove
  26444. * @param recursive if all child meshes should also be removed from the scene
  26445. * @returns the index where the mesh was in the mesh list
  26446. */
  26447. Scene.prototype.removeMesh = function (toRemove, recursive) {
  26448. var _this = this;
  26449. if (recursive === void 0) { recursive = false; }
  26450. var index = this.meshes.indexOf(toRemove);
  26451. if (index !== -1) {
  26452. // Remove from the scene if mesh found
  26453. this.meshes.splice(index, 1);
  26454. }
  26455. this.onMeshRemovedObservable.notifyObservers(toRemove);
  26456. if (recursive) {
  26457. toRemove.getChildMeshes().forEach(function (m) {
  26458. _this.removeMesh(m);
  26459. });
  26460. }
  26461. return index;
  26462. };
  26463. /**
  26464. * Add a transform node to the list of scene's transform nodes
  26465. * @param newTransformNode defines the transform node to add
  26466. */
  26467. Scene.prototype.addTransformNode = function (newTransformNode) {
  26468. this.transformNodes.push(newTransformNode);
  26469. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  26470. };
  26471. /**
  26472. * Remove a transform node for the list of scene's transform nodes
  26473. * @param toRemove defines the transform node to remove
  26474. * @returns the index where the transform node was in the transform node list
  26475. */
  26476. Scene.prototype.removeTransformNode = function (toRemove) {
  26477. var index = this.transformNodes.indexOf(toRemove);
  26478. if (index !== -1) {
  26479. // Remove from the scene if found
  26480. this.transformNodes.splice(index, 1);
  26481. }
  26482. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  26483. return index;
  26484. };
  26485. /**
  26486. * Remove a skeleton for the list of scene's skeletons
  26487. * @param toRemove defines the skeleton to remove
  26488. * @returns the index where the skeleton was in the skeleton list
  26489. */
  26490. Scene.prototype.removeSkeleton = function (toRemove) {
  26491. var index = this.skeletons.indexOf(toRemove);
  26492. if (index !== -1) {
  26493. // Remove from the scene if found
  26494. this.skeletons.splice(index, 1);
  26495. }
  26496. return index;
  26497. };
  26498. /**
  26499. * Remove a morph target for the list of scene's morph targets
  26500. * @param toRemove defines the morph target to remove
  26501. * @returns the index where the morph target was in the morph target list
  26502. */
  26503. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  26504. var index = this.morphTargetManagers.indexOf(toRemove);
  26505. if (index !== -1) {
  26506. // Remove from the scene if found
  26507. this.morphTargetManagers.splice(index, 1);
  26508. }
  26509. return index;
  26510. };
  26511. /**
  26512. * Remove a light for the list of scene's lights
  26513. * @param toRemove defines the light to remove
  26514. * @returns the index where the light was in the light list
  26515. */
  26516. Scene.prototype.removeLight = function (toRemove) {
  26517. var index = this.lights.indexOf(toRemove);
  26518. if (index !== -1) {
  26519. // Remove from meshes
  26520. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26521. var mesh = _a[_i];
  26522. mesh._removeLightSource(toRemove);
  26523. }
  26524. // Remove from the scene if mesh found
  26525. this.lights.splice(index, 1);
  26526. this.sortLightsByPriority();
  26527. }
  26528. this.onLightRemovedObservable.notifyObservers(toRemove);
  26529. return index;
  26530. };
  26531. /**
  26532. * Remove a camera for the list of scene's cameras
  26533. * @param toRemove defines the camera to remove
  26534. * @returns the index where the camera was in the camera list
  26535. */
  26536. Scene.prototype.removeCamera = function (toRemove) {
  26537. var index = this.cameras.indexOf(toRemove);
  26538. if (index !== -1) {
  26539. // Remove from the scene if mesh found
  26540. this.cameras.splice(index, 1);
  26541. }
  26542. // Remove from activeCameras
  26543. var index2 = this.activeCameras.indexOf(toRemove);
  26544. if (index2 !== -1) {
  26545. // Remove from the scene if mesh found
  26546. this.activeCameras.splice(index2, 1);
  26547. }
  26548. // Reset the activeCamera
  26549. if (this.activeCamera === toRemove) {
  26550. if (this.cameras.length > 0) {
  26551. this.activeCamera = this.cameras[0];
  26552. }
  26553. else {
  26554. this.activeCamera = null;
  26555. }
  26556. }
  26557. this.onCameraRemovedObservable.notifyObservers(toRemove);
  26558. return index;
  26559. };
  26560. /**
  26561. * Remove a particle system for the list of scene's particle systems
  26562. * @param toRemove defines the particle system to remove
  26563. * @returns the index where the particle system was in the particle system list
  26564. */
  26565. Scene.prototype.removeParticleSystem = function (toRemove) {
  26566. var index = this.particleSystems.indexOf(toRemove);
  26567. if (index !== -1) {
  26568. this.particleSystems.splice(index, 1);
  26569. }
  26570. return index;
  26571. };
  26572. /**
  26573. * Remove a animation for the list of scene's animations
  26574. * @param toRemove defines the animation to remove
  26575. * @returns the index where the animation was in the animation list
  26576. */
  26577. Scene.prototype.removeAnimation = function (toRemove) {
  26578. var index = this.animations.indexOf(toRemove);
  26579. if (index !== -1) {
  26580. this.animations.splice(index, 1);
  26581. }
  26582. return index;
  26583. };
  26584. /**
  26585. * Removes the given animation group from this scene.
  26586. * @param toRemove The animation group to remove
  26587. * @returns The index of the removed animation group
  26588. */
  26589. Scene.prototype.removeAnimationGroup = function (toRemove) {
  26590. var index = this.animationGroups.indexOf(toRemove);
  26591. if (index !== -1) {
  26592. this.animationGroups.splice(index, 1);
  26593. }
  26594. return index;
  26595. };
  26596. /**
  26597. * Removes the given multi-material from this scene.
  26598. * @param toRemove The multi-material to remove
  26599. * @returns The index of the removed multi-material
  26600. */
  26601. Scene.prototype.removeMultiMaterial = function (toRemove) {
  26602. var index = this.multiMaterials.indexOf(toRemove);
  26603. if (index !== -1) {
  26604. this.multiMaterials.splice(index, 1);
  26605. }
  26606. return index;
  26607. };
  26608. /**
  26609. * Removes the given material from this scene.
  26610. * @param toRemove The material to remove
  26611. * @returns The index of the removed material
  26612. */
  26613. Scene.prototype.removeMaterial = function (toRemove) {
  26614. var index = this.materials.indexOf(toRemove);
  26615. if (index !== -1) {
  26616. this.materials.splice(index, 1);
  26617. }
  26618. return index;
  26619. };
  26620. /**
  26621. * Removes the given lens flare system from this scene.
  26622. * @param toRemove The lens flare system to remove
  26623. * @returns The index of the removed lens flare system
  26624. */
  26625. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  26626. var index = this.lensFlareSystems.indexOf(toRemove);
  26627. if (index !== -1) {
  26628. this.lensFlareSystems.splice(index, 1);
  26629. }
  26630. return index;
  26631. };
  26632. /**
  26633. * Removes the given action manager from this scene.
  26634. * @param toRemove The action manager to remove
  26635. * @returns The index of the removed action manager
  26636. */
  26637. Scene.prototype.removeActionManager = function (toRemove) {
  26638. var index = this._actionManagers.indexOf(toRemove);
  26639. if (index !== -1) {
  26640. this._actionManagers.splice(index, 1);
  26641. }
  26642. return index;
  26643. };
  26644. /**
  26645. * Removes the given effect layer from this scene.
  26646. * @param toRemove defines the effect layer to remove
  26647. * @returns the index of the removed effect layer
  26648. */
  26649. Scene.prototype.removeEffectLayer = function (toRemove) {
  26650. var index = this.effectLayers.indexOf(toRemove);
  26651. if (index !== -1) {
  26652. this.effectLayers.splice(index, 1);
  26653. }
  26654. return index;
  26655. };
  26656. /**
  26657. * Removes the given texture from this scene.
  26658. * @param toRemove The texture to remove
  26659. * @returns The index of the removed texture
  26660. */
  26661. Scene.prototype.removeTexture = function (toRemove) {
  26662. var index = this.textures.indexOf(toRemove);
  26663. if (index !== -1) {
  26664. this.textures.splice(index, 1);
  26665. }
  26666. return index;
  26667. };
  26668. /**
  26669. * Adds the given light to this scene
  26670. * @param newLight The light to add
  26671. */
  26672. Scene.prototype.addLight = function (newLight) {
  26673. this.lights.push(newLight);
  26674. this.sortLightsByPriority();
  26675. // Add light to all meshes (To support if the light is removed and then readded)
  26676. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26677. var mesh = _a[_i];
  26678. if (mesh._lightSources.indexOf(newLight) === -1) {
  26679. mesh._lightSources.push(newLight);
  26680. mesh._resyncLightSources();
  26681. }
  26682. }
  26683. this.onNewLightAddedObservable.notifyObservers(newLight);
  26684. };
  26685. /**
  26686. * Sorts the list list based on light priorities
  26687. */
  26688. Scene.prototype.sortLightsByPriority = function () {
  26689. if (this.requireLightSorting) {
  26690. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  26691. }
  26692. };
  26693. /**
  26694. * Adds the given camera to this scene
  26695. * @param newCamera The camera to add
  26696. */
  26697. Scene.prototype.addCamera = function (newCamera) {
  26698. this.cameras.push(newCamera);
  26699. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  26700. };
  26701. /**
  26702. * Adds the given skeleton to this scene
  26703. * @param newSkeleton The skeleton to add
  26704. */
  26705. Scene.prototype.addSkeleton = function (newSkeleton) {
  26706. this.skeletons.push(newSkeleton);
  26707. };
  26708. /**
  26709. * Adds the given particle system to this scene
  26710. * @param newParticleSystem The particle system to add
  26711. */
  26712. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  26713. this.particleSystems.push(newParticleSystem);
  26714. };
  26715. /**
  26716. * Adds the given animation to this scene
  26717. * @param newAnimation The animation to add
  26718. */
  26719. Scene.prototype.addAnimation = function (newAnimation) {
  26720. this.animations.push(newAnimation);
  26721. };
  26722. /**
  26723. * Adds the given animation group to this scene.
  26724. * @param newAnimationGroup The animation group to add
  26725. */
  26726. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  26727. this.animationGroups.push(newAnimationGroup);
  26728. };
  26729. /**
  26730. * Adds the given multi-material to this scene
  26731. * @param newMultiMaterial The multi-material to add
  26732. */
  26733. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  26734. this.multiMaterials.push(newMultiMaterial);
  26735. };
  26736. /**
  26737. * Adds the given material to this scene
  26738. * @param newMaterial The material to add
  26739. */
  26740. Scene.prototype.addMaterial = function (newMaterial) {
  26741. this.materials.push(newMaterial);
  26742. };
  26743. /**
  26744. * Adds the given morph target to this scene
  26745. * @param newMorphTargetManager The morph target to add
  26746. */
  26747. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  26748. this.morphTargetManagers.push(newMorphTargetManager);
  26749. };
  26750. /**
  26751. * Adds the given geometry to this scene
  26752. * @param newGeometry The geometry to add
  26753. */
  26754. Scene.prototype.addGeometry = function (newGeometry) {
  26755. this._geometries.push(newGeometry);
  26756. };
  26757. /**
  26758. * Adds the given lens flare system to this scene
  26759. * @param newLensFlareSystem The lens flare system to add
  26760. */
  26761. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  26762. this.lensFlareSystems.push(newLensFlareSystem);
  26763. };
  26764. /**
  26765. * Adds the given effect layer to this scene
  26766. * @param newEffectLayer defines the effect layer to add
  26767. */
  26768. Scene.prototype.addEffectLayer = function (newEffectLayer) {
  26769. this.effectLayers.push(newEffectLayer);
  26770. };
  26771. /**
  26772. * Adds the given action manager to this scene
  26773. * @param newActionManager The action manager to add
  26774. */
  26775. Scene.prototype.addActionManager = function (newActionManager) {
  26776. this._actionManagers.push(newActionManager);
  26777. };
  26778. /**
  26779. * Adds the given texture to this scene.
  26780. * @param newTexture The texture to add
  26781. */
  26782. Scene.prototype.addTexture = function (newTexture) {
  26783. this.textures.push(newTexture);
  26784. };
  26785. /**
  26786. * Switch active camera
  26787. * @param newCamera defines the new active camera
  26788. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  26789. */
  26790. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  26791. if (attachControl === void 0) { attachControl = true; }
  26792. var canvas = this._engine.getRenderingCanvas();
  26793. if (!canvas) {
  26794. return;
  26795. }
  26796. if (this.activeCamera) {
  26797. this.activeCamera.detachControl(canvas);
  26798. }
  26799. this.activeCamera = newCamera;
  26800. if (attachControl) {
  26801. newCamera.attachControl(canvas);
  26802. }
  26803. };
  26804. /**
  26805. * sets the active camera of the scene using its ID
  26806. * @param id defines the camera's ID
  26807. * @return the new active camera or null if none found.
  26808. */
  26809. Scene.prototype.setActiveCameraByID = function (id) {
  26810. var camera = this.getCameraByID(id);
  26811. if (camera) {
  26812. this.activeCamera = camera;
  26813. return camera;
  26814. }
  26815. return null;
  26816. };
  26817. /**
  26818. * sets the active camera of the scene using its name
  26819. * @param name defines the camera's name
  26820. * @returns the new active camera or null if none found.
  26821. */
  26822. Scene.prototype.setActiveCameraByName = function (name) {
  26823. var camera = this.getCameraByName(name);
  26824. if (camera) {
  26825. this.activeCamera = camera;
  26826. return camera;
  26827. }
  26828. return null;
  26829. };
  26830. /**
  26831. * get an animation group using its name
  26832. * @param name defines the material's name
  26833. * @return the animation group or null if none found.
  26834. */
  26835. Scene.prototype.getAnimationGroupByName = function (name) {
  26836. for (var index = 0; index < this.animationGroups.length; index++) {
  26837. if (this.animationGroups[index].name === name) {
  26838. return this.animationGroups[index];
  26839. }
  26840. }
  26841. return null;
  26842. };
  26843. /**
  26844. * get a material using its id
  26845. * @param id defines the material's ID
  26846. * @return the material or null if none found.
  26847. */
  26848. Scene.prototype.getMaterialByID = function (id) {
  26849. for (var index = 0; index < this.materials.length; index++) {
  26850. if (this.materials[index].id === id) {
  26851. return this.materials[index];
  26852. }
  26853. }
  26854. return null;
  26855. };
  26856. /**
  26857. * Gets a material using its name
  26858. * @param name defines the material's name
  26859. * @return the material or null if none found.
  26860. */
  26861. Scene.prototype.getMaterialByName = function (name) {
  26862. for (var index = 0; index < this.materials.length; index++) {
  26863. if (this.materials[index].name === name) {
  26864. return this.materials[index];
  26865. }
  26866. }
  26867. return null;
  26868. };
  26869. /**
  26870. * Gets a lens flare system using its name
  26871. * @param name defines the name to look for
  26872. * @returns the lens flare system or null if not found
  26873. */
  26874. Scene.prototype.getLensFlareSystemByName = function (name) {
  26875. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  26876. if (this.lensFlareSystems[index].name === name) {
  26877. return this.lensFlareSystems[index];
  26878. }
  26879. }
  26880. return null;
  26881. };
  26882. /**
  26883. * Gets a lens flare system using its id
  26884. * @param id defines the id to look for
  26885. * @returns the lens flare system or null if not found
  26886. */
  26887. Scene.prototype.getLensFlareSystemByID = function (id) {
  26888. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  26889. if (this.lensFlareSystems[index].id === id) {
  26890. return this.lensFlareSystems[index];
  26891. }
  26892. }
  26893. return null;
  26894. };
  26895. /**
  26896. * Gets a camera using its id
  26897. * @param id defines the id to look for
  26898. * @returns the camera or null if not found
  26899. */
  26900. Scene.prototype.getCameraByID = function (id) {
  26901. for (var index = 0; index < this.cameras.length; index++) {
  26902. if (this.cameras[index].id === id) {
  26903. return this.cameras[index];
  26904. }
  26905. }
  26906. return null;
  26907. };
  26908. /**
  26909. * Gets a camera using its unique id
  26910. * @param uniqueId defines the unique id to look for
  26911. * @returns the camera or null if not found
  26912. */
  26913. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  26914. for (var index = 0; index < this.cameras.length; index++) {
  26915. if (this.cameras[index].uniqueId === uniqueId) {
  26916. return this.cameras[index];
  26917. }
  26918. }
  26919. return null;
  26920. };
  26921. /**
  26922. * Gets a camera using its name
  26923. * @param name defines the camera's name
  26924. * @return the camera or null if none found.
  26925. */
  26926. Scene.prototype.getCameraByName = function (name) {
  26927. for (var index = 0; index < this.cameras.length; index++) {
  26928. if (this.cameras[index].name === name) {
  26929. return this.cameras[index];
  26930. }
  26931. }
  26932. return null;
  26933. };
  26934. /**
  26935. * Gets a bone using its id
  26936. * @param id defines the bone's id
  26937. * @return the bone or null if not found
  26938. */
  26939. Scene.prototype.getBoneByID = function (id) {
  26940. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26941. var skeleton = this.skeletons[skeletonIndex];
  26942. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26943. if (skeleton.bones[boneIndex].id === id) {
  26944. return skeleton.bones[boneIndex];
  26945. }
  26946. }
  26947. }
  26948. return null;
  26949. };
  26950. /**
  26951. * Gets a bone using its id
  26952. * @param name defines the bone's name
  26953. * @return the bone or null if not found
  26954. */
  26955. Scene.prototype.getBoneByName = function (name) {
  26956. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26957. var skeleton = this.skeletons[skeletonIndex];
  26958. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26959. if (skeleton.bones[boneIndex].name === name) {
  26960. return skeleton.bones[boneIndex];
  26961. }
  26962. }
  26963. }
  26964. return null;
  26965. };
  26966. /**
  26967. * Gets a light node using its name
  26968. * @param name defines the the light's name
  26969. * @return the light or null if none found.
  26970. */
  26971. Scene.prototype.getLightByName = function (name) {
  26972. for (var index = 0; index < this.lights.length; index++) {
  26973. if (this.lights[index].name === name) {
  26974. return this.lights[index];
  26975. }
  26976. }
  26977. return null;
  26978. };
  26979. /**
  26980. * Gets a light node using its id
  26981. * @param id defines the light's id
  26982. * @return the light or null if none found.
  26983. */
  26984. Scene.prototype.getLightByID = function (id) {
  26985. for (var index = 0; index < this.lights.length; index++) {
  26986. if (this.lights[index].id === id) {
  26987. return this.lights[index];
  26988. }
  26989. }
  26990. return null;
  26991. };
  26992. /**
  26993. * Gets a light node using its scene-generated unique ID
  26994. * @param uniqueId defines the light's unique id
  26995. * @return the light or null if none found.
  26996. */
  26997. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  26998. for (var index = 0; index < this.lights.length; index++) {
  26999. if (this.lights[index].uniqueId === uniqueId) {
  27000. return this.lights[index];
  27001. }
  27002. }
  27003. return null;
  27004. };
  27005. /**
  27006. * Gets a particle system by id
  27007. * @param id defines the particle system id
  27008. * @return the corresponding system or null if none found
  27009. */
  27010. Scene.prototype.getParticleSystemByID = function (id) {
  27011. for (var index = 0; index < this.particleSystems.length; index++) {
  27012. if (this.particleSystems[index].id === id) {
  27013. return this.particleSystems[index];
  27014. }
  27015. }
  27016. return null;
  27017. };
  27018. /**
  27019. * Gets a geometry using its ID
  27020. * @param id defines the geometry's id
  27021. * @return the geometry or null if none found.
  27022. */
  27023. Scene.prototype.getGeometryByID = function (id) {
  27024. for (var index = 0; index < this._geometries.length; index++) {
  27025. if (this._geometries[index].id === id) {
  27026. return this._geometries[index];
  27027. }
  27028. }
  27029. return null;
  27030. };
  27031. /**
  27032. * Add a new geometry to this scene
  27033. * @param geometry defines the geometry to be added to the scene.
  27034. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  27035. * @return a boolean defining if the geometry was added or not
  27036. */
  27037. Scene.prototype.pushGeometry = function (geometry, force) {
  27038. if (!force && this.getGeometryByID(geometry.id)) {
  27039. return false;
  27040. }
  27041. this._geometries.push(geometry);
  27042. //notify the collision coordinator
  27043. if (this.collisionCoordinator) {
  27044. this.collisionCoordinator.onGeometryAdded(geometry);
  27045. }
  27046. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  27047. return true;
  27048. };
  27049. /**
  27050. * Removes an existing geometry
  27051. * @param geometry defines the geometry to be removed from the scene
  27052. * @return a boolean defining if the geometry was removed or not
  27053. */
  27054. Scene.prototype.removeGeometry = function (geometry) {
  27055. var index = this._geometries.indexOf(geometry);
  27056. if (index > -1) {
  27057. this._geometries.splice(index, 1);
  27058. //notify the collision coordinator
  27059. if (this.collisionCoordinator) {
  27060. this.collisionCoordinator.onGeometryDeleted(geometry);
  27061. }
  27062. this.onGeometryRemovedObservable.notifyObservers(geometry);
  27063. return true;
  27064. }
  27065. return false;
  27066. };
  27067. /**
  27068. * Gets the list of geometries attached to the scene
  27069. * @returns an array of Geometry
  27070. */
  27071. Scene.prototype.getGeometries = function () {
  27072. return this._geometries;
  27073. };
  27074. /**
  27075. * Gets the first added mesh found of a given ID
  27076. * @param id defines the id to search for
  27077. * @return the mesh found or null if not found at all
  27078. */
  27079. Scene.prototype.getMeshByID = function (id) {
  27080. for (var index = 0; index < this.meshes.length; index++) {
  27081. if (this.meshes[index].id === id) {
  27082. return this.meshes[index];
  27083. }
  27084. }
  27085. return null;
  27086. };
  27087. /**
  27088. * Gets a list of meshes using their id
  27089. * @param id defines the id to search for
  27090. * @returns a list of meshes
  27091. */
  27092. Scene.prototype.getMeshesByID = function (id) {
  27093. return this.meshes.filter(function (m) {
  27094. return m.id === id;
  27095. });
  27096. };
  27097. /**
  27098. * Gets the first added transform node found of a given ID
  27099. * @param id defines the id to search for
  27100. * @return the found transform node or null if not found at all.
  27101. */
  27102. Scene.prototype.getTransformNodeByID = function (id) {
  27103. for (var index = 0; index < this.transformNodes.length; index++) {
  27104. if (this.transformNodes[index].id === id) {
  27105. return this.transformNodes[index];
  27106. }
  27107. }
  27108. return null;
  27109. };
  27110. /**
  27111. * Gets a list of transform nodes using their id
  27112. * @param id defines the id to search for
  27113. * @returns a list of transform nodes
  27114. */
  27115. Scene.prototype.getTransformNodesByID = function (id) {
  27116. return this.transformNodes.filter(function (m) {
  27117. return m.id === id;
  27118. });
  27119. };
  27120. /**
  27121. * Gets a mesh with its auto-generated unique id
  27122. * @param uniqueId defines the unique id to search for
  27123. * @return the found mesh or null if not found at all.
  27124. */
  27125. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  27126. for (var index = 0; index < this.meshes.length; index++) {
  27127. if (this.meshes[index].uniqueId === uniqueId) {
  27128. return this.meshes[index];
  27129. }
  27130. }
  27131. return null;
  27132. };
  27133. /**
  27134. * Gets a the last added mesh using a given id
  27135. * @param id defines the id to search for
  27136. * @return the found mesh or null if not found at all.
  27137. */
  27138. Scene.prototype.getLastMeshByID = function (id) {
  27139. for (var index = this.meshes.length - 1; index >= 0; index--) {
  27140. if (this.meshes[index].id === id) {
  27141. return this.meshes[index];
  27142. }
  27143. }
  27144. return null;
  27145. };
  27146. /**
  27147. * Gets a the last added node (Mesh, Camera, Light) using a given id
  27148. * @param id defines the id to search for
  27149. * @return the found node or null if not found at all
  27150. */
  27151. Scene.prototype.getLastEntryByID = function (id) {
  27152. var index;
  27153. for (index = this.meshes.length - 1; index >= 0; index--) {
  27154. if (this.meshes[index].id === id) {
  27155. return this.meshes[index];
  27156. }
  27157. }
  27158. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  27159. if (this.transformNodes[index].id === id) {
  27160. return this.transformNodes[index];
  27161. }
  27162. }
  27163. for (index = this.cameras.length - 1; index >= 0; index--) {
  27164. if (this.cameras[index].id === id) {
  27165. return this.cameras[index];
  27166. }
  27167. }
  27168. for (index = this.lights.length - 1; index >= 0; index--) {
  27169. if (this.lights[index].id === id) {
  27170. return this.lights[index];
  27171. }
  27172. }
  27173. return null;
  27174. };
  27175. /**
  27176. * Gets a node (Mesh, Camera, Light) using a given id
  27177. * @param id defines the id to search for
  27178. * @return the found node or null if not found at all
  27179. */
  27180. Scene.prototype.getNodeByID = function (id) {
  27181. var mesh = this.getMeshByID(id);
  27182. if (mesh) {
  27183. return mesh;
  27184. }
  27185. var light = this.getLightByID(id);
  27186. if (light) {
  27187. return light;
  27188. }
  27189. var camera = this.getCameraByID(id);
  27190. if (camera) {
  27191. return camera;
  27192. }
  27193. var bone = this.getBoneByID(id);
  27194. return bone;
  27195. };
  27196. /**
  27197. * Gets a node (Mesh, Camera, Light) using a given name
  27198. * @param name defines the name to search for
  27199. * @return the found node or null if not found at all.
  27200. */
  27201. Scene.prototype.getNodeByName = function (name) {
  27202. var mesh = this.getMeshByName(name);
  27203. if (mesh) {
  27204. return mesh;
  27205. }
  27206. var light = this.getLightByName(name);
  27207. if (light) {
  27208. return light;
  27209. }
  27210. var camera = this.getCameraByName(name);
  27211. if (camera) {
  27212. return camera;
  27213. }
  27214. var bone = this.getBoneByName(name);
  27215. return bone;
  27216. };
  27217. /**
  27218. * Gets a mesh using a given name
  27219. * @param name defines the name to search for
  27220. * @return the found mesh or null if not found at all.
  27221. */
  27222. Scene.prototype.getMeshByName = function (name) {
  27223. for (var index = 0; index < this.meshes.length; index++) {
  27224. if (this.meshes[index].name === name) {
  27225. return this.meshes[index];
  27226. }
  27227. }
  27228. return null;
  27229. };
  27230. /**
  27231. * Gets a transform node using a given name
  27232. * @param name defines the name to search for
  27233. * @return the found transform node or null if not found at all.
  27234. */
  27235. Scene.prototype.getTransformNodeByName = function (name) {
  27236. for (var index = 0; index < this.transformNodes.length; index++) {
  27237. if (this.transformNodes[index].name === name) {
  27238. return this.transformNodes[index];
  27239. }
  27240. }
  27241. return null;
  27242. };
  27243. /**
  27244. * Gets a sound using a given name
  27245. * @param name defines the name to search for
  27246. * @return the found sound or null if not found at all.
  27247. */
  27248. Scene.prototype.getSoundByName = function (name) {
  27249. var index;
  27250. if (BABYLON.AudioEngine) {
  27251. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  27252. if (this.mainSoundTrack.soundCollection[index].name === name) {
  27253. return this.mainSoundTrack.soundCollection[index];
  27254. }
  27255. }
  27256. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  27257. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  27258. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  27259. return this.soundTracks[sdIndex].soundCollection[index];
  27260. }
  27261. }
  27262. }
  27263. }
  27264. return null;
  27265. };
  27266. /**
  27267. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  27268. * @param id defines the id to search for
  27269. * @return the found skeleton or null if not found at all.
  27270. */
  27271. Scene.prototype.getLastSkeletonByID = function (id) {
  27272. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  27273. if (this.skeletons[index].id === id) {
  27274. return this.skeletons[index];
  27275. }
  27276. }
  27277. return null;
  27278. };
  27279. /**
  27280. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  27281. * @param id defines the id to search for
  27282. * @return the found skeleton or null if not found at all.
  27283. */
  27284. Scene.prototype.getSkeletonById = function (id) {
  27285. for (var index = 0; index < this.skeletons.length; index++) {
  27286. if (this.skeletons[index].id === id) {
  27287. return this.skeletons[index];
  27288. }
  27289. }
  27290. return null;
  27291. };
  27292. /**
  27293. * Gets a skeleton using a given name
  27294. * @param name defines the name to search for
  27295. * @return the found skeleton or null if not found at all.
  27296. */
  27297. Scene.prototype.getSkeletonByName = function (name) {
  27298. for (var index = 0; index < this.skeletons.length; index++) {
  27299. if (this.skeletons[index].name === name) {
  27300. return this.skeletons[index];
  27301. }
  27302. }
  27303. return null;
  27304. };
  27305. /**
  27306. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  27307. * @param id defines the id to search for
  27308. * @return the found morph target manager or null if not found at all.
  27309. */
  27310. Scene.prototype.getMorphTargetManagerById = function (id) {
  27311. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  27312. if (this.morphTargetManagers[index].uniqueId === id) {
  27313. return this.morphTargetManagers[index];
  27314. }
  27315. }
  27316. return null;
  27317. };
  27318. /**
  27319. * Gets a boolean indicating if the given mesh is active
  27320. * @param mesh defines the mesh to look for
  27321. * @returns true if the mesh is in the active list
  27322. */
  27323. Scene.prototype.isActiveMesh = function (mesh) {
  27324. return (this._activeMeshes.indexOf(mesh) !== -1);
  27325. };
  27326. /**
  27327. * Return a the first highlight layer of the scene with a given name.
  27328. * @param name The name of the highlight layer to look for.
  27329. * @return The highlight layer if found otherwise null.
  27330. */
  27331. Scene.prototype.getHighlightLayerByName = function (name) {
  27332. for (var index = 0; index < this.effectLayers.length; index++) {
  27333. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.HighlightLayer.EffectName) {
  27334. return this.effectLayers[index];
  27335. }
  27336. }
  27337. return null;
  27338. };
  27339. /**
  27340. * Return a the first highlight layer of the scene with a given name.
  27341. * @param name The name of the highlight layer to look for.
  27342. * @return The highlight layer if found otherwise null.
  27343. */
  27344. Scene.prototype.getGlowLayerByName = function (name) {
  27345. for (var index = 0; index < this.effectLayers.length; index++) {
  27346. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.GlowLayer.EffectName) {
  27347. return this.effectLayers[index];
  27348. }
  27349. }
  27350. return null;
  27351. };
  27352. Object.defineProperty(Scene.prototype, "uid", {
  27353. /**
  27354. * Return a unique id as a string which can serve as an identifier for the scene
  27355. */
  27356. get: function () {
  27357. if (!this._uid) {
  27358. this._uid = BABYLON.Tools.RandomId();
  27359. }
  27360. return this._uid;
  27361. },
  27362. enumerable: true,
  27363. configurable: true
  27364. });
  27365. /**
  27366. * Add an externaly attached data from its key.
  27367. * This method call will fail and return false, if such key already exists.
  27368. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  27369. * @param key the unique key that identifies the data
  27370. * @param data the data object to associate to the key for this Engine instance
  27371. * @return true if no such key were already present and the data was added successfully, false otherwise
  27372. */
  27373. Scene.prototype.addExternalData = function (key, data) {
  27374. if (!this._externalData) {
  27375. this._externalData = new BABYLON.StringDictionary();
  27376. }
  27377. return this._externalData.add(key, data);
  27378. };
  27379. /**
  27380. * Get an externaly attached data from its key
  27381. * @param key the unique key that identifies the data
  27382. * @return the associated data, if present (can be null), or undefined if not present
  27383. */
  27384. Scene.prototype.getExternalData = function (key) {
  27385. if (!this._externalData) {
  27386. return null;
  27387. }
  27388. return this._externalData.get(key);
  27389. };
  27390. /**
  27391. * Get an externaly attached data from its key, create it using a factory if it's not already present
  27392. * @param key the unique key that identifies the data
  27393. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  27394. * @return the associated data, can be null if the factory returned null.
  27395. */
  27396. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  27397. if (!this._externalData) {
  27398. this._externalData = new BABYLON.StringDictionary();
  27399. }
  27400. return this._externalData.getOrAddWithFactory(key, factory);
  27401. };
  27402. /**
  27403. * Remove an externaly attached data from the Engine instance
  27404. * @param key the unique key that identifies the data
  27405. * @return true if the data was successfully removed, false if it doesn't exist
  27406. */
  27407. Scene.prototype.removeExternalData = function (key) {
  27408. return this._externalData.remove(key);
  27409. };
  27410. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  27411. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  27412. if (mesh.showSubMeshesBoundingBox) {
  27413. var boundingInfo = subMesh.getBoundingInfo();
  27414. if (boundingInfo !== null && boundingInfo !== undefined) {
  27415. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  27416. }
  27417. }
  27418. var material = subMesh.getMaterial();
  27419. if (material !== null && material !== undefined) {
  27420. // Render targets
  27421. if (material.getRenderTargetTextures !== undefined) {
  27422. if (this._processedMaterials.indexOf(material) === -1) {
  27423. this._processedMaterials.push(material);
  27424. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  27425. }
  27426. }
  27427. // Dispatch
  27428. this._activeIndices.addCount(subMesh.indexCount, false);
  27429. this._renderingManager.dispatch(subMesh, mesh, material);
  27430. }
  27431. }
  27432. };
  27433. /**
  27434. * Clear the processed materials smart array preventing retention point in material dispose.
  27435. */
  27436. Scene.prototype.freeProcessedMaterials = function () {
  27437. this._processedMaterials.dispose();
  27438. };
  27439. /**
  27440. * Clear the active meshes smart array preventing retention point in mesh dispose.
  27441. */
  27442. Scene.prototype.freeActiveMeshes = function () {
  27443. this._activeMeshes.dispose();
  27444. if (this.activeCamera && this.activeCamera._activeMeshes) {
  27445. this.activeCamera._activeMeshes.dispose();
  27446. }
  27447. if (this.activeCameras) {
  27448. for (var i = 0; i < this.activeCameras.length; i++) {
  27449. var activeCamera = this.activeCameras[i];
  27450. if (activeCamera && activeCamera._activeMeshes) {
  27451. activeCamera._activeMeshes.dispose();
  27452. }
  27453. }
  27454. }
  27455. };
  27456. /**
  27457. * Clear the info related to rendering groups preventing retention points during dispose.
  27458. */
  27459. Scene.prototype.freeRenderingGroups = function () {
  27460. if (this._renderingManager) {
  27461. this._renderingManager.freeRenderingGroups();
  27462. }
  27463. if (this.textures) {
  27464. for (var i = 0; i < this.textures.length; i++) {
  27465. var texture = this.textures[i];
  27466. if (texture && texture.renderList) {
  27467. texture.freeRenderingGroups();
  27468. }
  27469. }
  27470. }
  27471. };
  27472. /** @hidden */
  27473. Scene.prototype._isInIntermediateRendering = function () {
  27474. return this._intermediateRendering;
  27475. };
  27476. /**
  27477. * Defines the current active mesh candidate provider
  27478. * @param provider defines the provider to use
  27479. */
  27480. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  27481. this._activeMeshCandidateProvider = provider;
  27482. };
  27483. /**
  27484. * Gets the current active mesh candidate provider
  27485. * @returns the current active mesh candidate provider
  27486. */
  27487. Scene.prototype.getActiveMeshCandidateProvider = function () {
  27488. return this._activeMeshCandidateProvider;
  27489. };
  27490. /**
  27491. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  27492. * @returns the current scene
  27493. */
  27494. Scene.prototype.freezeActiveMeshes = function () {
  27495. if (!this.activeCamera) {
  27496. return this;
  27497. }
  27498. if (!this._frustumPlanes) {
  27499. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27500. }
  27501. this._evaluateActiveMeshes();
  27502. this._activeMeshesFrozen = true;
  27503. return this;
  27504. };
  27505. /**
  27506. * Use this function to restart evaluating active meshes on every frame
  27507. * @returns the current scene
  27508. */
  27509. Scene.prototype.unfreezeActiveMeshes = function () {
  27510. this._activeMeshesFrozen = false;
  27511. return this;
  27512. };
  27513. Scene.prototype._evaluateActiveMeshes = function () {
  27514. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  27515. return;
  27516. }
  27517. if (!this.activeCamera) {
  27518. return;
  27519. }
  27520. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  27521. this.activeCamera._activeMeshes.reset();
  27522. this._activeMeshes.reset();
  27523. this._renderingManager.reset();
  27524. this._processedMaterials.reset();
  27525. this._activeParticleSystems.reset();
  27526. this._activeSkeletons.reset();
  27527. this._softwareSkinnedMeshes.reset();
  27528. if (this._boundingBoxRenderer) {
  27529. this._boundingBoxRenderer.reset();
  27530. }
  27531. // Meshes
  27532. var meshes;
  27533. var len;
  27534. var checkIsEnabled = true;
  27535. // Determine mesh candidates
  27536. if (this._activeMeshCandidateProvider !== undefined) {
  27537. // Use _activeMeshCandidateProvider
  27538. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  27539. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  27540. if (meshes !== undefined) {
  27541. len = meshes.length;
  27542. }
  27543. else {
  27544. len = 0;
  27545. }
  27546. }
  27547. else if (this._selectionOctree !== undefined) {
  27548. // Octree
  27549. var selection = this._selectionOctree.select(this._frustumPlanes);
  27550. meshes = selection.data;
  27551. len = selection.length;
  27552. }
  27553. else {
  27554. // Full scene traversal
  27555. len = this.meshes.length;
  27556. meshes = this.meshes;
  27557. }
  27558. // Check each mesh
  27559. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  27560. mesh = meshes[meshIndex];
  27561. if (mesh.isBlocked) {
  27562. continue;
  27563. }
  27564. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  27565. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  27566. continue;
  27567. }
  27568. mesh.computeWorldMatrix();
  27569. // Intersections
  27570. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  27571. this._meshesForIntersections.pushNoDuplicate(mesh);
  27572. }
  27573. // Switch to current LOD
  27574. meshLOD = mesh.getLOD(this.activeCamera);
  27575. if (meshLOD === undefined || meshLOD === null) {
  27576. continue;
  27577. }
  27578. mesh._preActivate();
  27579. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  27580. this._activeMeshes.push(mesh);
  27581. this.activeCamera._activeMeshes.push(mesh);
  27582. mesh._activate(this._renderId);
  27583. if (meshLOD !== mesh) {
  27584. meshLOD._activate(this._renderId);
  27585. }
  27586. this._activeMesh(mesh, meshLOD);
  27587. }
  27588. }
  27589. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  27590. // Particle systems
  27591. if (this.particlesEnabled) {
  27592. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  27593. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  27594. var particleSystem = this.particleSystems[particleIndex];
  27595. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  27596. continue;
  27597. }
  27598. var emitter = particleSystem.emitter;
  27599. if (!emitter.position || emitter.isEnabled()) {
  27600. this._activeParticleSystems.push(particleSystem);
  27601. particleSystem.animate();
  27602. this._renderingManager.dispatchParticles(particleSystem);
  27603. }
  27604. }
  27605. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  27606. }
  27607. };
  27608. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  27609. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  27610. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  27611. mesh.skeleton.prepare();
  27612. }
  27613. if (!mesh.computeBonesUsingShaders) {
  27614. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  27615. }
  27616. }
  27617. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  27618. var boundingInfo = sourceMesh.getBoundingInfo();
  27619. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  27620. }
  27621. if (mesh !== undefined && mesh !== null
  27622. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  27623. // Submeshes Octrees
  27624. var len;
  27625. var subMeshes;
  27626. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  27627. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  27628. len = intersections.length;
  27629. subMeshes = intersections.data;
  27630. }
  27631. else {
  27632. subMeshes = mesh.subMeshes;
  27633. len = subMeshes.length;
  27634. }
  27635. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  27636. subMesh = subMeshes[subIndex];
  27637. this._evaluateSubMesh(subMesh, mesh);
  27638. }
  27639. }
  27640. };
  27641. /**
  27642. * Update the transform matrix to update from the current active camera
  27643. * @param force defines a boolean used to force the update even if cache is up to date
  27644. */
  27645. Scene.prototype.updateTransformMatrix = function (force) {
  27646. if (!this.activeCamera) {
  27647. return;
  27648. }
  27649. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  27650. };
  27651. /**
  27652. * 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)
  27653. * @param alternateCamera defines the camera to use
  27654. */
  27655. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  27656. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  27657. };
  27658. Scene.prototype._renderForCamera = function (camera, rigParent) {
  27659. if (camera && camera._skipRendering) {
  27660. return;
  27661. }
  27662. var engine = this._engine;
  27663. this.activeCamera = camera;
  27664. if (!this.activeCamera)
  27665. throw new Error("Active camera not set");
  27666. // Viewport
  27667. engine.setViewport(this.activeCamera.viewport);
  27668. // Camera
  27669. this.resetCachedMaterial();
  27670. this._renderId++;
  27671. this.updateTransformMatrix();
  27672. if (camera._alternateCamera) {
  27673. this.updateAlternateTransformMatrix(camera._alternateCamera);
  27674. this._alternateRendering = true;
  27675. }
  27676. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  27677. // Meshes
  27678. this._evaluateActiveMeshes();
  27679. // Software skinning
  27680. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  27681. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  27682. mesh.applySkeleton(mesh.skeleton);
  27683. }
  27684. // Render targets
  27685. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27686. var needsRestoreFrameBuffer = false;
  27687. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  27688. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  27689. }
  27690. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  27691. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  27692. }
  27693. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  27694. this._intermediateRendering = true;
  27695. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27696. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  27697. var renderTarget = this._renderTargets.data[renderIndex];
  27698. if (renderTarget._shouldRender()) {
  27699. this._renderId++;
  27700. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  27701. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  27702. }
  27703. }
  27704. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27705. this._intermediateRendering = false;
  27706. this._renderId++;
  27707. needsRestoreFrameBuffer = true; // Restore back buffer
  27708. }
  27709. // Render EffectLayer Texture
  27710. var stencilState = this._engine.getStencilBuffer();
  27711. var renderEffects = false;
  27712. var needStencil = false;
  27713. if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) {
  27714. this._intermediateRendering = true;
  27715. for (var i = 0; i < this.effectLayers.length; i++) {
  27716. var effectLayer = this.effectLayers[i];
  27717. if (effectLayer.shouldRender() &&
  27718. (!effectLayer.camera ||
  27719. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  27720. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  27721. renderEffects = true;
  27722. needStencil = needStencil || effectLayer.needStencil();
  27723. var renderTarget = effectLayer._mainTexture;
  27724. if (renderTarget._shouldRender()) {
  27725. this._renderId++;
  27726. renderTarget.render(false, false);
  27727. needsRestoreFrameBuffer = true;
  27728. }
  27729. }
  27730. }
  27731. this._intermediateRendering = false;
  27732. this._renderId++;
  27733. }
  27734. if (needsRestoreFrameBuffer) {
  27735. engine.restoreDefaultFramebuffer(); // Restore back buffer
  27736. }
  27737. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27738. // Prepare Frame
  27739. if (this.postProcessManager) {
  27740. this.postProcessManager._prepareFrame();
  27741. }
  27742. // Backgrounds
  27743. var layerIndex;
  27744. var layer;
  27745. if (this.layers.length) {
  27746. engine.setDepthBuffer(false);
  27747. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  27748. layer = this.layers[layerIndex];
  27749. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  27750. layer.render();
  27751. }
  27752. }
  27753. engine.setDepthBuffer(true);
  27754. }
  27755. // Activate effect Layer stencil
  27756. if (needStencil) {
  27757. this._engine.setStencilBuffer(true);
  27758. }
  27759. // Render
  27760. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  27761. this._renderingManager.render(null, null, true, true);
  27762. this.onAfterDrawPhaseObservable.notifyObservers(this);
  27763. // Restore effect Layer stencil
  27764. if (needStencil) {
  27765. this._engine.setStencilBuffer(stencilState);
  27766. }
  27767. // Bounding boxes
  27768. if (this._boundingBoxRenderer) {
  27769. this._boundingBoxRenderer.render();
  27770. }
  27771. // Lens flares
  27772. if (this.lensFlaresEnabled) {
  27773. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  27774. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  27775. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  27776. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  27777. lensFlareSystem.render();
  27778. }
  27779. }
  27780. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  27781. }
  27782. // Effect Layer
  27783. if (renderEffects) {
  27784. engine.setDepthBuffer(false);
  27785. for (var i = 0; i < this.effectLayers.length; i++) {
  27786. if (this.effectLayers[i].shouldRender()) {
  27787. this.effectLayers[i].render();
  27788. }
  27789. }
  27790. engine.setDepthBuffer(true);
  27791. }
  27792. // Foregrounds
  27793. if (this.layers.length) {
  27794. engine.setDepthBuffer(false);
  27795. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  27796. layer = this.layers[layerIndex];
  27797. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  27798. layer.render();
  27799. }
  27800. }
  27801. engine.setDepthBuffer(true);
  27802. }
  27803. // Finalize frame
  27804. if (this.postProcessManager) {
  27805. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  27806. }
  27807. // Reset some special arrays
  27808. this._renderTargets.reset();
  27809. this._alternateRendering = false;
  27810. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  27811. };
  27812. Scene.prototype._processSubCameras = function (camera) {
  27813. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  27814. this._renderForCamera(camera);
  27815. return;
  27816. }
  27817. // rig cameras
  27818. for (var index = 0; index < camera._rigCameras.length; index++) {
  27819. this._renderForCamera(camera._rigCameras[index], camera);
  27820. }
  27821. this.activeCamera = camera;
  27822. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27823. };
  27824. Scene.prototype._checkIntersections = function () {
  27825. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  27826. var sourceMesh = this._meshesForIntersections.data[index];
  27827. if (!sourceMesh.actionManager) {
  27828. continue;
  27829. }
  27830. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  27831. var action = sourceMesh.actionManager.actions[actionIndex];
  27832. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27833. var parameters = action.getTriggerParameter();
  27834. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  27835. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  27836. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  27837. if (areIntersecting && currentIntersectionInProgress === -1) {
  27838. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  27839. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27840. sourceMesh._intersectionsInProgress.push(otherMesh);
  27841. }
  27842. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27843. sourceMesh._intersectionsInProgress.push(otherMesh);
  27844. }
  27845. }
  27846. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  27847. //They intersected, and now they don't.
  27848. //is this trigger an exit trigger? execute an event.
  27849. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27850. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27851. }
  27852. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  27853. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  27854. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  27855. return otherMesh === parameterMesh;
  27856. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27857. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  27858. }
  27859. }
  27860. }
  27861. }
  27862. }
  27863. };
  27864. /**
  27865. * Render the scene
  27866. * @param updateCameras defines a boolean indicating if cameras must update according to their inputs (true by default)
  27867. */
  27868. Scene.prototype.render = function (updateCameras) {
  27869. if (updateCameras === void 0) { updateCameras = true; }
  27870. if (this.isDisposed) {
  27871. return;
  27872. }
  27873. this._activeParticles.fetchNewFrame();
  27874. this._totalVertices.fetchNewFrame();
  27875. this._activeIndices.fetchNewFrame();
  27876. this._activeBones.fetchNewFrame();
  27877. this._meshesForIntersections.reset();
  27878. this.resetCachedMaterial();
  27879. this.onBeforeAnimationsObservable.notifyObservers(this);
  27880. // Actions
  27881. if (this.actionManager) {
  27882. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  27883. }
  27884. //Simplification Queue
  27885. if (this.simplificationQueue && !this.simplificationQueue.running) {
  27886. this.simplificationQueue.executeNext();
  27887. }
  27888. if (this._engine.isDeterministicLockStep()) {
  27889. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  27890. var defaultFPS = (60.0 / 1000.0);
  27891. var defaultFrameTime = 1000 / 60; // frame time in MS
  27892. if (this._physicsEngine) {
  27893. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  27894. }
  27895. var stepsTaken = 0;
  27896. var maxSubSteps = this._engine.getLockstepMaxSteps();
  27897. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  27898. internalSteps = Math.min(internalSteps, maxSubSteps);
  27899. do {
  27900. this.onBeforeStepObservable.notifyObservers(this);
  27901. // Animations
  27902. this._animationRatio = defaultFrameTime * defaultFPS;
  27903. this._animate();
  27904. this.onAfterAnimationsObservable.notifyObservers(this);
  27905. // Physics
  27906. if (this._physicsEngine) {
  27907. this.onBeforePhysicsObservable.notifyObservers(this);
  27908. this._physicsEngine._step(defaultFrameTime / 1000);
  27909. this.onAfterPhysicsObservable.notifyObservers(this);
  27910. }
  27911. this.onAfterStepObservable.notifyObservers(this);
  27912. this._currentStepId++;
  27913. stepsTaken++;
  27914. deltaTime -= defaultFrameTime;
  27915. } while (deltaTime > 0 && stepsTaken < internalSteps);
  27916. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  27917. }
  27918. else {
  27919. // Animations
  27920. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  27921. this._animationRatio = deltaTime * (60.0 / 1000.0);
  27922. this._animate();
  27923. this.onAfterAnimationsObservable.notifyObservers(this);
  27924. // Physics
  27925. if (this._physicsEngine) {
  27926. this.onBeforePhysicsObservable.notifyObservers(this);
  27927. this._physicsEngine._step(deltaTime / 1000.0);
  27928. this.onAfterPhysicsObservable.notifyObservers(this);
  27929. }
  27930. }
  27931. // update gamepad manager
  27932. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  27933. this._gamepadManager._checkGamepadsStatus();
  27934. }
  27935. // Update Cameras
  27936. if (updateCameras) {
  27937. if (this.activeCameras.length > 0) {
  27938. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27939. var camera = this.activeCameras[cameraIndex];
  27940. camera.update();
  27941. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27942. // rig cameras
  27943. for (var index = 0; index < camera._rigCameras.length; index++) {
  27944. camera._rigCameras[index].update();
  27945. }
  27946. }
  27947. }
  27948. }
  27949. else if (this.activeCamera) {
  27950. this.activeCamera.update();
  27951. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27952. // rig cameras
  27953. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  27954. this.activeCamera._rigCameras[index].update();
  27955. }
  27956. }
  27957. }
  27958. }
  27959. // Before render
  27960. this.onBeforeRenderObservable.notifyObservers(this);
  27961. // Customs render targets
  27962. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27963. var engine = this.getEngine();
  27964. var currentActiveCamera = this.activeCamera;
  27965. if (this.renderTargetsEnabled) {
  27966. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27967. this._intermediateRendering = true;
  27968. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  27969. var renderTarget = this.customRenderTargets[customIndex];
  27970. if (renderTarget._shouldRender()) {
  27971. this._renderId++;
  27972. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  27973. if (!this.activeCamera)
  27974. throw new Error("Active camera not set");
  27975. // Viewport
  27976. engine.setViewport(this.activeCamera.viewport);
  27977. // Camera
  27978. this.updateTransformMatrix();
  27979. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  27980. }
  27981. }
  27982. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27983. this._intermediateRendering = false;
  27984. this._renderId++;
  27985. }
  27986. // Restore back buffer
  27987. if (this.customRenderTargets.length > 0) {
  27988. engine.restoreDefaultFramebuffer();
  27989. }
  27990. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27991. this.activeCamera = currentActiveCamera;
  27992. // Procedural textures
  27993. if (this.proceduralTexturesEnabled) {
  27994. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27995. for (var proceduralIndex = 0; proceduralIndex < this.proceduralTextures.length; proceduralIndex++) {
  27996. var proceduralTexture = this.proceduralTextures[proceduralIndex];
  27997. if (proceduralTexture._shouldRender()) {
  27998. proceduralTexture.render();
  27999. }
  28000. }
  28001. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  28002. }
  28003. // Clear
  28004. if (this.autoClearDepthAndStencil || this.autoClear) {
  28005. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  28006. }
  28007. // Shadows
  28008. if (this.shadowsEnabled) {
  28009. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  28010. var light = this.lights[lightIndex];
  28011. var shadowGenerator = light.getShadowGenerator();
  28012. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  28013. var shadowMap = (shadowGenerator.getShadowMap());
  28014. if (this.textures.indexOf(shadowMap) !== -1) {
  28015. this._renderTargets.push(shadowMap);
  28016. }
  28017. }
  28018. }
  28019. }
  28020. // Depth renderer
  28021. for (var key in this._depthRenderer) {
  28022. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  28023. }
  28024. // Geometry renderer
  28025. if (this._geometryBufferRenderer) {
  28026. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  28027. }
  28028. // RenderPipeline
  28029. if (this._postProcessRenderPipelineManager) {
  28030. this._postProcessRenderPipelineManager.update();
  28031. }
  28032. // Multi-cameras?
  28033. if (this.activeCameras.length > 0) {
  28034. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  28035. if (cameraIndex > 0) {
  28036. this._engine.clear(null, false, true, true);
  28037. }
  28038. this._processSubCameras(this.activeCameras[cameraIndex]);
  28039. }
  28040. }
  28041. else {
  28042. if (!this.activeCamera) {
  28043. throw new Error("No camera defined");
  28044. }
  28045. this._processSubCameras(this.activeCamera);
  28046. }
  28047. // Intersection checks
  28048. this._checkIntersections();
  28049. // Update the audio listener attached to the camera
  28050. if (BABYLON.AudioEngine) {
  28051. this._updateAudioParameters();
  28052. }
  28053. // After render
  28054. if (this.afterRender) {
  28055. this.afterRender();
  28056. }
  28057. this.onAfterRenderObservable.notifyObservers(this);
  28058. // Cleaning
  28059. for (var index = 0; index < this._toBeDisposed.length; index++) {
  28060. var data = this._toBeDisposed.data[index];
  28061. if (data) {
  28062. data.dispose();
  28063. }
  28064. this._toBeDisposed[index] = null;
  28065. }
  28066. this._toBeDisposed.reset();
  28067. if (this.dumpNextRenderTargets) {
  28068. this.dumpNextRenderTargets = false;
  28069. }
  28070. this._activeBones.addCount(0, true);
  28071. this._activeIndices.addCount(0, true);
  28072. this._activeParticles.addCount(0, true);
  28073. };
  28074. Scene.prototype._updateAudioParameters = function () {
  28075. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  28076. return;
  28077. }
  28078. var listeningCamera;
  28079. var audioEngine = BABYLON.Engine.audioEngine;
  28080. if (this.activeCameras.length > 0) {
  28081. listeningCamera = this.activeCameras[0];
  28082. }
  28083. else {
  28084. listeningCamera = this.activeCamera;
  28085. }
  28086. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  28087. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  28088. // for VR cameras
  28089. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  28090. listeningCamera = listeningCamera.rigCameras[0];
  28091. }
  28092. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  28093. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  28094. cameraDirection.normalize();
  28095. // To avoid some errors on GearVR
  28096. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  28097. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  28098. }
  28099. var i;
  28100. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  28101. var sound = this.mainSoundTrack.soundCollection[i];
  28102. if (sound.useCustomAttenuation) {
  28103. sound.updateDistanceFromListener();
  28104. }
  28105. }
  28106. for (i = 0; i < this.soundTracks.length; i++) {
  28107. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  28108. sound = this.soundTracks[i].soundCollection[j];
  28109. if (sound.useCustomAttenuation) {
  28110. sound.updateDistanceFromListener();
  28111. }
  28112. }
  28113. }
  28114. }
  28115. };
  28116. Object.defineProperty(Scene.prototype, "audioEnabled", {
  28117. // Audio
  28118. /**
  28119. * Gets or sets if audio support is enabled
  28120. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  28121. */
  28122. get: function () {
  28123. return this._audioEnabled;
  28124. },
  28125. set: function (value) {
  28126. this._audioEnabled = value;
  28127. if (BABYLON.AudioEngine) {
  28128. if (this._audioEnabled) {
  28129. this._enableAudio();
  28130. }
  28131. else {
  28132. this._disableAudio();
  28133. }
  28134. }
  28135. },
  28136. enumerable: true,
  28137. configurable: true
  28138. });
  28139. Scene.prototype._disableAudio = function () {
  28140. var i;
  28141. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  28142. this.mainSoundTrack.soundCollection[i].pause();
  28143. }
  28144. for (i = 0; i < this.soundTracks.length; i++) {
  28145. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  28146. this.soundTracks[i].soundCollection[j].pause();
  28147. }
  28148. }
  28149. };
  28150. Scene.prototype._enableAudio = function () {
  28151. var i;
  28152. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  28153. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  28154. this.mainSoundTrack.soundCollection[i].play();
  28155. }
  28156. }
  28157. for (i = 0; i < this.soundTracks.length; i++) {
  28158. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  28159. if (this.soundTracks[i].soundCollection[j].isPaused) {
  28160. this.soundTracks[i].soundCollection[j].play();
  28161. }
  28162. }
  28163. }
  28164. };
  28165. Object.defineProperty(Scene.prototype, "headphone", {
  28166. /**
  28167. * Gets or sets if audio will be output to headphones
  28168. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  28169. */
  28170. get: function () {
  28171. return this._headphone;
  28172. },
  28173. set: function (value) {
  28174. this._headphone = value;
  28175. if (BABYLON.AudioEngine) {
  28176. if (this._headphone) {
  28177. this._switchAudioModeForHeadphones();
  28178. }
  28179. else {
  28180. this._switchAudioModeForNormalSpeakers();
  28181. }
  28182. }
  28183. },
  28184. enumerable: true,
  28185. configurable: true
  28186. });
  28187. Scene.prototype._switchAudioModeForHeadphones = function () {
  28188. this.mainSoundTrack.switchPanningModelToHRTF();
  28189. for (var i = 0; i < this.soundTracks.length; i++) {
  28190. this.soundTracks[i].switchPanningModelToHRTF();
  28191. }
  28192. };
  28193. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  28194. this.mainSoundTrack.switchPanningModelToEqualPower();
  28195. for (var i = 0; i < this.soundTracks.length; i++) {
  28196. this.soundTracks[i].switchPanningModelToEqualPower();
  28197. }
  28198. };
  28199. /**
  28200. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  28201. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  28202. * @returns the created depth renderer
  28203. */
  28204. Scene.prototype.enableDepthRenderer = function (camera) {
  28205. camera = camera || this.activeCamera;
  28206. if (!camera) {
  28207. throw "No camera available to enable depth renderer";
  28208. }
  28209. if (!this._depthRenderer[camera.id]) {
  28210. var textureType = 0;
  28211. if (this._engine.getCaps().textureHalfFloatRender) {
  28212. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  28213. }
  28214. else if (this._engine.getCaps().textureFloatRender) {
  28215. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  28216. }
  28217. else {
  28218. throw "Depth renderer does not support int texture type";
  28219. }
  28220. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  28221. }
  28222. return this._depthRenderer[camera.id];
  28223. };
  28224. /**
  28225. * Disables a depth renderer for a given camera
  28226. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  28227. */
  28228. Scene.prototype.disableDepthRenderer = function (camera) {
  28229. camera = camera || this.activeCamera;
  28230. if (!camera || !this._depthRenderer[camera.id]) {
  28231. return;
  28232. }
  28233. this._depthRenderer[camera.id].dispose();
  28234. delete this._depthRenderer[camera.id];
  28235. };
  28236. /**
  28237. * Enables a GeometryBufferRender and associates it with the scene
  28238. * @param ratio defines the scaling ratio to apply to the renderer (1 by default which means same resolution)
  28239. * @returns the GeometryBufferRenderer
  28240. */
  28241. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  28242. if (ratio === void 0) { ratio = 1; }
  28243. if (this._geometryBufferRenderer) {
  28244. return this._geometryBufferRenderer;
  28245. }
  28246. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  28247. if (!this._geometryBufferRenderer.isSupported) {
  28248. this._geometryBufferRenderer = null;
  28249. }
  28250. return this._geometryBufferRenderer;
  28251. };
  28252. /**
  28253. * Disables the GeometryBufferRender associated with the scene
  28254. */
  28255. Scene.prototype.disableGeometryBufferRenderer = function () {
  28256. if (!this._geometryBufferRenderer) {
  28257. return;
  28258. }
  28259. this._geometryBufferRenderer.dispose();
  28260. this._geometryBufferRenderer = null;
  28261. };
  28262. /**
  28263. * Freeze all materials
  28264. * A frozen material will not be updatable but should be faster to render
  28265. */
  28266. Scene.prototype.freezeMaterials = function () {
  28267. for (var i = 0; i < this.materials.length; i++) {
  28268. this.materials[i].freeze();
  28269. }
  28270. };
  28271. /**
  28272. * Unfreeze all materials
  28273. * A frozen material will not be updatable but should be faster to render
  28274. */
  28275. Scene.prototype.unfreezeMaterials = function () {
  28276. for (var i = 0; i < this.materials.length; i++) {
  28277. this.materials[i].unfreeze();
  28278. }
  28279. };
  28280. /**
  28281. * Releases all held ressources
  28282. */
  28283. Scene.prototype.dispose = function () {
  28284. this.beforeRender = null;
  28285. this.afterRender = null;
  28286. this.skeletons = [];
  28287. this.morphTargetManagers = [];
  28288. this.importedMeshesFiles = new Array();
  28289. this.stopAllAnimations();
  28290. this.resetCachedMaterial();
  28291. for (var key in this._depthRenderer) {
  28292. this._depthRenderer[key].dispose();
  28293. }
  28294. if (this._gamepadManager) {
  28295. this._gamepadManager.dispose();
  28296. this._gamepadManager = null;
  28297. }
  28298. // Smart arrays
  28299. if (this.activeCamera) {
  28300. this.activeCamera._activeMeshes.dispose();
  28301. this.activeCamera = null;
  28302. }
  28303. this._activeMeshes.dispose();
  28304. this._renderingManager.dispose();
  28305. this._processedMaterials.dispose();
  28306. this._activeParticleSystems.dispose();
  28307. this._activeSkeletons.dispose();
  28308. this._softwareSkinnedMeshes.dispose();
  28309. this._renderTargets.dispose();
  28310. this._registeredForLateAnimationBindings.dispose();
  28311. if (this._boundingBoxRenderer) {
  28312. this._boundingBoxRenderer.dispose();
  28313. }
  28314. this._meshesForIntersections.dispose();
  28315. this._toBeDisposed.dispose();
  28316. // Abort active requests
  28317. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  28318. var request = _a[_i];
  28319. request.abort();
  28320. }
  28321. // Debug layer
  28322. if (this._debugLayer) {
  28323. this._debugLayer.hide();
  28324. }
  28325. // Events
  28326. this.onDisposeObservable.notifyObservers(this);
  28327. this.onDisposeObservable.clear();
  28328. this.onBeforeRenderObservable.clear();
  28329. this.onAfterRenderObservable.clear();
  28330. this.onBeforeRenderTargetsRenderObservable.clear();
  28331. this.onAfterRenderTargetsRenderObservable.clear();
  28332. this.onAfterStepObservable.clear();
  28333. this.onBeforeStepObservable.clear();
  28334. this.onBeforeActiveMeshesEvaluationObservable.clear();
  28335. this.onAfterActiveMeshesEvaluationObservable.clear();
  28336. this.onBeforeParticlesRenderingObservable.clear();
  28337. this.onAfterParticlesRenderingObservable.clear();
  28338. this.onBeforeSpritesRenderingObservable.clear();
  28339. this.onAfterSpritesRenderingObservable.clear();
  28340. this.onBeforeDrawPhaseObservable.clear();
  28341. this.onAfterDrawPhaseObservable.clear();
  28342. this.onBeforePhysicsObservable.clear();
  28343. this.onAfterPhysicsObservable.clear();
  28344. this.onBeforeAnimationsObservable.clear();
  28345. this.onAfterAnimationsObservable.clear();
  28346. this.onDataLoadedObservable.clear();
  28347. this.detachControl();
  28348. // Release sounds & sounds tracks
  28349. if (BABYLON.AudioEngine) {
  28350. this.disposeSounds();
  28351. }
  28352. // VR Helper
  28353. if (this.VRHelper) {
  28354. this.VRHelper.dispose();
  28355. }
  28356. // Detach cameras
  28357. var canvas = this._engine.getRenderingCanvas();
  28358. if (canvas) {
  28359. var index;
  28360. for (index = 0; index < this.cameras.length; index++) {
  28361. this.cameras[index].detachControl(canvas);
  28362. }
  28363. }
  28364. // Release animation groups
  28365. while (this.animationGroups.length) {
  28366. this.animationGroups[0].dispose();
  28367. }
  28368. // Release lights
  28369. while (this.lights.length) {
  28370. this.lights[0].dispose();
  28371. }
  28372. // Release meshes
  28373. while (this.meshes.length) {
  28374. this.meshes[0].dispose(true);
  28375. }
  28376. while (this.transformNodes.length) {
  28377. this.removeTransformNode(this.transformNodes[0]);
  28378. }
  28379. // Release cameras
  28380. while (this.cameras.length) {
  28381. this.cameras[0].dispose();
  28382. }
  28383. // Release materials
  28384. if (this.defaultMaterial) {
  28385. this.defaultMaterial.dispose();
  28386. }
  28387. while (this.multiMaterials.length) {
  28388. this.multiMaterials[0].dispose();
  28389. }
  28390. while (this.materials.length) {
  28391. this.materials[0].dispose();
  28392. }
  28393. // Release particles
  28394. while (this.particleSystems.length) {
  28395. this.particleSystems[0].dispose();
  28396. }
  28397. // Release sprites
  28398. while (this.spriteManagers.length) {
  28399. this.spriteManagers[0].dispose();
  28400. }
  28401. // Release postProcesses
  28402. while (this.postProcesses.length) {
  28403. this.postProcesses[0].dispose();
  28404. }
  28405. // Release layers
  28406. while (this.layers.length) {
  28407. this.layers[0].dispose();
  28408. }
  28409. while (this.effectLayers.length) {
  28410. this.effectLayers[0].dispose();
  28411. }
  28412. // Release textures
  28413. while (this.textures.length) {
  28414. this.textures[0].dispose();
  28415. }
  28416. // Release UBO
  28417. this._sceneUbo.dispose();
  28418. if (this._alternateSceneUbo) {
  28419. this._alternateSceneUbo.dispose();
  28420. }
  28421. // Post-processes
  28422. this.postProcessManager.dispose();
  28423. if (this._postProcessRenderPipelineManager) {
  28424. this._postProcessRenderPipelineManager.dispose();
  28425. }
  28426. // Physics
  28427. if (this._physicsEngine) {
  28428. this.disablePhysicsEngine();
  28429. }
  28430. // Remove from engine
  28431. index = this._engine.scenes.indexOf(this);
  28432. if (index > -1) {
  28433. this._engine.scenes.splice(index, 1);
  28434. }
  28435. this._engine.wipeCaches(true);
  28436. this._isDisposed = true;
  28437. };
  28438. Object.defineProperty(Scene.prototype, "isDisposed", {
  28439. /**
  28440. * Gets if the scene is already disposed
  28441. */
  28442. get: function () {
  28443. return this._isDisposed;
  28444. },
  28445. enumerable: true,
  28446. configurable: true
  28447. });
  28448. /**
  28449. * Releases sounds & soundtracks
  28450. */
  28451. Scene.prototype.disposeSounds = function () {
  28452. if (!this._mainSoundTrack) {
  28453. return;
  28454. }
  28455. this.mainSoundTrack.dispose();
  28456. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  28457. this.soundTracks[scIndex].dispose();
  28458. }
  28459. };
  28460. /**
  28461. * Call this function to reduce memory footprint of the scene.
  28462. * Vertex buffers will not store CPU data anymore (this will prevent picking, collisions or physics to work correctly)
  28463. */
  28464. Scene.prototype.clearCachedVertexData = function () {
  28465. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28466. var mesh = this.meshes[meshIndex];
  28467. var geometry = mesh.geometry;
  28468. if (geometry) {
  28469. geometry._indices = [];
  28470. for (var vbName in geometry._vertexBuffers) {
  28471. if (!geometry._vertexBuffers.hasOwnProperty(vbName)) {
  28472. continue;
  28473. }
  28474. geometry._vertexBuffers[vbName]._buffer._data = null;
  28475. }
  28476. }
  28477. }
  28478. };
  28479. /**
  28480. * This function will remove the local cached buffer data from texture.
  28481. * It will save memory but will prevent the texture from being rebuilt
  28482. */
  28483. Scene.prototype.cleanCachedTextureBuffer = function () {
  28484. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28485. var baseTexture = _a[_i];
  28486. var buffer = baseTexture._buffer;
  28487. if (buffer) {
  28488. baseTexture._buffer = null;
  28489. }
  28490. }
  28491. };
  28492. // Octrees
  28493. /**
  28494. * Get the world extend vectors with an optional filter
  28495. *
  28496. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  28497. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  28498. */
  28499. Scene.prototype.getWorldExtends = function (filterPredicate) {
  28500. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  28501. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  28502. filterPredicate = filterPredicate || (function () { return true; });
  28503. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  28504. mesh.computeWorldMatrix(true);
  28505. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  28506. return;
  28507. }
  28508. var boundingInfo = mesh.getBoundingInfo();
  28509. var minBox = boundingInfo.boundingBox.minimumWorld;
  28510. var maxBox = boundingInfo.boundingBox.maximumWorld;
  28511. BABYLON.Tools.CheckExtends(minBox, min, max);
  28512. BABYLON.Tools.CheckExtends(maxBox, min, max);
  28513. });
  28514. return {
  28515. min: min,
  28516. max: max
  28517. };
  28518. };
  28519. /**
  28520. * Creates or updates the octree used to boost selection (picking)
  28521. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  28522. * @param maxCapacity defines the maximum capacity per leaf
  28523. * @param maxDepth defines the maximum depth of the octree
  28524. * @returns an octree of AbstractMesh
  28525. */
  28526. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  28527. if (maxCapacity === void 0) { maxCapacity = 64; }
  28528. if (maxDepth === void 0) { maxDepth = 2; }
  28529. if (!this._selectionOctree) {
  28530. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  28531. }
  28532. var worldExtends = this.getWorldExtends();
  28533. // Update octree
  28534. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  28535. return this._selectionOctree;
  28536. };
  28537. // Picking
  28538. /**
  28539. * Creates a ray that can be used to pick in the scene
  28540. * @param x defines the x coordinate of the origin (on-screen)
  28541. * @param y defines the y coordinate of the origin (on-screen)
  28542. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28543. * @param camera defines the camera to use for the picking
  28544. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28545. * @returns a Ray
  28546. */
  28547. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  28548. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28549. var result = BABYLON.Ray.Zero();
  28550. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  28551. return result;
  28552. };
  28553. /**
  28554. * Creates a ray that can be used to pick in the scene
  28555. * @param x defines the x coordinate of the origin (on-screen)
  28556. * @param y defines the y coordinate of the origin (on-screen)
  28557. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28558. * @param result defines the ray where to store the picking ray
  28559. * @param camera defines the camera to use for the picking
  28560. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28561. * @returns the current scene
  28562. */
  28563. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  28564. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28565. var engine = this._engine;
  28566. if (!camera) {
  28567. if (!this.activeCamera)
  28568. throw new Error("Active camera not set");
  28569. camera = this.activeCamera;
  28570. }
  28571. var cameraViewport = camera.viewport;
  28572. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28573. // Moving coordinates to local viewport world
  28574. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28575. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28576. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  28577. return this;
  28578. };
  28579. /**
  28580. * Creates a ray that can be used to pick in the scene
  28581. * @param x defines the x coordinate of the origin (on-screen)
  28582. * @param y defines the y coordinate of the origin (on-screen)
  28583. * @param camera defines the camera to use for the picking
  28584. * @returns a Ray
  28585. */
  28586. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  28587. var result = BABYLON.Ray.Zero();
  28588. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  28589. return result;
  28590. };
  28591. /**
  28592. * Creates a ray that can be used to pick in the scene
  28593. * @param x defines the x coordinate of the origin (on-screen)
  28594. * @param y defines the y coordinate of the origin (on-screen)
  28595. * @param result defines the ray where to store the picking ray
  28596. * @param camera defines the camera to use for the picking
  28597. * @returns the current scene
  28598. */
  28599. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  28600. if (!BABYLON.PickingInfo) {
  28601. return this;
  28602. }
  28603. var engine = this._engine;
  28604. if (!camera) {
  28605. if (!this.activeCamera)
  28606. throw new Error("Active camera not set");
  28607. camera = this.activeCamera;
  28608. }
  28609. var cameraViewport = camera.viewport;
  28610. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28611. var identity = BABYLON.Matrix.Identity();
  28612. // Moving coordinates to local viewport world
  28613. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28614. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28615. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  28616. return this;
  28617. };
  28618. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  28619. if (!BABYLON.PickingInfo) {
  28620. return null;
  28621. }
  28622. var pickingInfo = null;
  28623. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28624. var mesh = this.meshes[meshIndex];
  28625. if (predicate) {
  28626. if (!predicate(mesh)) {
  28627. continue;
  28628. }
  28629. }
  28630. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28631. continue;
  28632. }
  28633. var world = mesh.getWorldMatrix();
  28634. var ray = rayFunction(world);
  28635. var result = mesh.intersects(ray, fastCheck);
  28636. if (!result || !result.hit)
  28637. continue;
  28638. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28639. continue;
  28640. pickingInfo = result;
  28641. if (fastCheck) {
  28642. break;
  28643. }
  28644. }
  28645. return pickingInfo || new BABYLON.PickingInfo();
  28646. };
  28647. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  28648. if (!BABYLON.PickingInfo) {
  28649. return null;
  28650. }
  28651. var pickingInfos = new Array();
  28652. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28653. var mesh = this.meshes[meshIndex];
  28654. if (predicate) {
  28655. if (!predicate(mesh)) {
  28656. continue;
  28657. }
  28658. }
  28659. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28660. continue;
  28661. }
  28662. var world = mesh.getWorldMatrix();
  28663. var ray = rayFunction(world);
  28664. var result = mesh.intersects(ray, false);
  28665. if (!result || !result.hit)
  28666. continue;
  28667. pickingInfos.push(result);
  28668. }
  28669. return pickingInfos;
  28670. };
  28671. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  28672. if (!BABYLON.PickingInfo) {
  28673. return null;
  28674. }
  28675. var pickingInfo = null;
  28676. if (!camera) {
  28677. if (!this.activeCamera) {
  28678. return null;
  28679. }
  28680. camera = this.activeCamera;
  28681. }
  28682. if (this.spriteManagers.length > 0) {
  28683. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  28684. var spriteManager = this.spriteManagers[spriteIndex];
  28685. if (!spriteManager.isPickable) {
  28686. continue;
  28687. }
  28688. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  28689. if (!result || !result.hit)
  28690. continue;
  28691. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28692. continue;
  28693. pickingInfo = result;
  28694. if (fastCheck) {
  28695. break;
  28696. }
  28697. }
  28698. }
  28699. return pickingInfo || new BABYLON.PickingInfo();
  28700. };
  28701. /** Launch a ray to try to pick a mesh in the scene
  28702. * @param x position on screen
  28703. * @param y position on screen
  28704. * @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
  28705. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28706. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28707. * @returns a PickingInfo
  28708. */
  28709. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  28710. var _this = this;
  28711. if (!BABYLON.PickingInfo) {
  28712. return null;
  28713. }
  28714. var result = this._internalPick(function (world) {
  28715. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  28716. return _this._tempPickingRay;
  28717. }, predicate, fastCheck);
  28718. if (result) {
  28719. result.ray = this.createPickingRay(x, y, BABYLON.Matrix.Identity(), camera || null);
  28720. }
  28721. return result;
  28722. };
  28723. /** Launch a ray to try to pick a sprite in the scene
  28724. * @param x position on screen
  28725. * @param y position on screen
  28726. * @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
  28727. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28728. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28729. * @returns a PickingInfo
  28730. */
  28731. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  28732. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  28733. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  28734. };
  28735. /** Use the given ray to pick a mesh in the scene
  28736. * @param ray The ray to use to pick meshes
  28737. * @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
  28738. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  28739. * @returns a PickingInfo
  28740. */
  28741. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  28742. var _this = this;
  28743. var result = this._internalPick(function (world) {
  28744. if (!_this._pickWithRayInverseMatrix) {
  28745. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28746. }
  28747. world.invertToRef(_this._pickWithRayInverseMatrix);
  28748. if (!_this._cachedRayForTransform) {
  28749. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28750. }
  28751. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28752. return _this._cachedRayForTransform;
  28753. }, predicate, fastCheck);
  28754. if (result) {
  28755. result.ray = ray;
  28756. }
  28757. return result;
  28758. };
  28759. /**
  28760. * Launch a ray to try to pick a mesh in the scene
  28761. * @param x X position on screen
  28762. * @param y Y position on screen
  28763. * @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
  28764. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28765. * @returns an array of PickingInfo
  28766. */
  28767. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  28768. var _this = this;
  28769. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  28770. };
  28771. /**
  28772. * Launch a ray to try to pick a mesh in the scene
  28773. * @param ray Ray to use
  28774. * @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
  28775. * @returns an array of PickingInfo
  28776. */
  28777. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  28778. var _this = this;
  28779. return this._internalMultiPick(function (world) {
  28780. if (!_this._pickWithRayInverseMatrix) {
  28781. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28782. }
  28783. world.invertToRef(_this._pickWithRayInverseMatrix);
  28784. if (!_this._cachedRayForTransform) {
  28785. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28786. }
  28787. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28788. return _this._cachedRayForTransform;
  28789. }, predicate);
  28790. };
  28791. /**
  28792. * Force the value of meshUnderPointer
  28793. * @param mesh defines the mesh to use
  28794. */
  28795. Scene.prototype.setPointerOverMesh = function (mesh) {
  28796. if (this._pointerOverMesh === mesh) {
  28797. return;
  28798. }
  28799. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28800. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28801. }
  28802. this._pointerOverMesh = mesh;
  28803. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28804. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28805. }
  28806. };
  28807. /**
  28808. * Gets the mesh under the pointer
  28809. * @returns a Mesh or null if no mesh is under the pointer
  28810. */
  28811. Scene.prototype.getPointerOverMesh = function () {
  28812. return this._pointerOverMesh;
  28813. };
  28814. /**
  28815. * Force the sprite under the pointer
  28816. * @param sprite defines the sprite to use
  28817. */
  28818. Scene.prototype.setPointerOverSprite = function (sprite) {
  28819. if (this._pointerOverSprite === sprite) {
  28820. return;
  28821. }
  28822. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28823. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28824. }
  28825. this._pointerOverSprite = sprite;
  28826. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28827. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28828. }
  28829. };
  28830. /**
  28831. * Gets the sprite under the pointer
  28832. * @returns a Sprite or null if no sprite is under the pointer
  28833. */
  28834. Scene.prototype.getPointerOverSprite = function () {
  28835. return this._pointerOverSprite;
  28836. };
  28837. // Physics
  28838. /**
  28839. * Gets the current physics engine
  28840. * @returns a PhysicsEngine or null if none attached
  28841. */
  28842. Scene.prototype.getPhysicsEngine = function () {
  28843. return this._physicsEngine;
  28844. };
  28845. /**
  28846. * Enables physics to the current scene
  28847. * @param gravity defines the scene's gravity for the physics engine
  28848. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  28849. * @return a boolean indicating if the physics engine was initialized
  28850. */
  28851. Scene.prototype.enablePhysics = function (gravity, plugin) {
  28852. if (gravity === void 0) { gravity = null; }
  28853. if (this._physicsEngine) {
  28854. return true;
  28855. }
  28856. try {
  28857. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  28858. return true;
  28859. }
  28860. catch (e) {
  28861. BABYLON.Tools.Error(e.message);
  28862. return false;
  28863. }
  28864. };
  28865. /**
  28866. * Disables and disposes the physics engine associated with the scene
  28867. */
  28868. Scene.prototype.disablePhysicsEngine = function () {
  28869. if (!this._physicsEngine) {
  28870. return;
  28871. }
  28872. this._physicsEngine.dispose();
  28873. this._physicsEngine = null;
  28874. };
  28875. /**
  28876. * Gets a boolean indicating if there is an active physics engine
  28877. * @returns a boolean indicating if there is an active physics engine
  28878. */
  28879. Scene.prototype.isPhysicsEnabled = function () {
  28880. return this._physicsEngine !== undefined;
  28881. };
  28882. /**
  28883. * Deletes a physics compound impostor
  28884. * @param compound defines the compound to delete
  28885. */
  28886. Scene.prototype.deleteCompoundImpostor = function (compound) {
  28887. var mesh = compound.parts[0].mesh;
  28888. if (mesh.physicsImpostor) {
  28889. mesh.physicsImpostor.dispose( /*true*/);
  28890. mesh.physicsImpostor = null;
  28891. }
  28892. };
  28893. // Misc.
  28894. /** @hidden */
  28895. Scene.prototype._rebuildGeometries = function () {
  28896. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  28897. var geometry = _a[_i];
  28898. geometry._rebuild();
  28899. }
  28900. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  28901. var mesh = _c[_b];
  28902. mesh._rebuild();
  28903. }
  28904. if (this.postProcessManager) {
  28905. this.postProcessManager._rebuild();
  28906. }
  28907. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  28908. var layer = _e[_d];
  28909. layer._rebuild();
  28910. }
  28911. for (var _f = 0, _g = this.effectLayers; _f < _g.length; _f++) {
  28912. var effectLayer = _g[_f];
  28913. effectLayer._rebuild();
  28914. }
  28915. if (this._boundingBoxRenderer) {
  28916. this._boundingBoxRenderer._rebuild();
  28917. }
  28918. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  28919. var system = _j[_h];
  28920. system.rebuild();
  28921. }
  28922. if (this._postProcessRenderPipelineManager) {
  28923. this._postProcessRenderPipelineManager._rebuild();
  28924. }
  28925. };
  28926. /** @hidden */
  28927. Scene.prototype._rebuildTextures = function () {
  28928. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28929. var texture = _a[_i];
  28930. texture._rebuild();
  28931. }
  28932. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28933. };
  28934. /**
  28935. * Creates a default light for the scene.
  28936. * @param replace Whether to replace the existing lights in the scene.
  28937. */
  28938. Scene.prototype.createDefaultLight = function (replace) {
  28939. if (replace === void 0) { replace = false; }
  28940. // Dispose existing light in replace mode.
  28941. if (replace) {
  28942. if (this.lights) {
  28943. for (var i = 0; i < this.lights.length; i++) {
  28944. this.lights[i].dispose();
  28945. }
  28946. }
  28947. }
  28948. // Light
  28949. if (this.lights.length === 0) {
  28950. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  28951. }
  28952. };
  28953. /**
  28954. * Creates a default camera for the scene.
  28955. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  28956. * @param replace Whether to replace the existing active camera in the scene.
  28957. * @param attachCameraControls Whether to attach camera controls to the canvas.
  28958. */
  28959. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  28960. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28961. if (replace === void 0) { replace = false; }
  28962. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28963. // Dispose existing camera in replace mode.
  28964. if (replace) {
  28965. if (this.activeCamera) {
  28966. this.activeCamera.dispose();
  28967. this.activeCamera = null;
  28968. }
  28969. }
  28970. // Camera
  28971. if (!this.activeCamera) {
  28972. var worldExtends = this.getWorldExtends();
  28973. var worldSize = worldExtends.max.subtract(worldExtends.min);
  28974. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  28975. var camera;
  28976. var radius = worldSize.length() * 1.5;
  28977. // empty scene scenario!
  28978. if (!isFinite(radius)) {
  28979. radius = 1;
  28980. worldCenter.copyFromFloats(0, 0, 0);
  28981. }
  28982. if (createArcRotateCamera) {
  28983. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  28984. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  28985. arcRotateCamera.wheelPrecision = 100 / radius;
  28986. camera = arcRotateCamera;
  28987. }
  28988. else {
  28989. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  28990. freeCamera.setTarget(worldCenter);
  28991. camera = freeCamera;
  28992. }
  28993. camera.minZ = radius * 0.01;
  28994. camera.maxZ = radius * 1000;
  28995. camera.speed = radius * 0.2;
  28996. this.activeCamera = camera;
  28997. var canvas = this.getEngine().getRenderingCanvas();
  28998. if (attachCameraControls && canvas) {
  28999. camera.attachControl(canvas);
  29000. }
  29001. }
  29002. };
  29003. /**
  29004. * Creates a default camera and a default light
  29005. * @param createArcRotateCamera defines that the camera will be an ArcRotateCamera
  29006. * @param replace defines if the camera and/or light will replace the existing ones
  29007. * @param attachCameraControls defines if attachControl will be called on the new camera
  29008. */
  29009. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  29010. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  29011. if (replace === void 0) { replace = false; }
  29012. if (attachCameraControls === void 0) { attachCameraControls = false; }
  29013. this.createDefaultLight(replace);
  29014. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  29015. };
  29016. /**
  29017. * Creates a new sky box
  29018. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  29019. * @param environmentTexture defines the texture to use as environment texture
  29020. * @param pbr defines if PBRMaterial must be used instead of StandardMaterial
  29021. * @param scale defines the overall scale of the skybox
  29022. * @param blur defines if blurring must be applied to the environment texture (works only with pbr === true)
  29023. * @param setGlobalEnvTexture defines a boolean indicating that scene.environmentTexture must match the current skybox texture (true by default)
  29024. * @returns a new mesh holding the sky box
  29025. */
  29026. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur, setGlobalEnvTexture) {
  29027. if (pbr === void 0) { pbr = false; }
  29028. if (scale === void 0) { scale = 1000; }
  29029. if (blur === void 0) { blur = 0; }
  29030. if (setGlobalEnvTexture === void 0) { setGlobalEnvTexture = true; }
  29031. if (!environmentTexture) {
  29032. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  29033. return null;
  29034. }
  29035. if (setGlobalEnvTexture) {
  29036. if (environmentTexture) {
  29037. this.environmentTexture = environmentTexture;
  29038. }
  29039. }
  29040. // Skybox
  29041. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  29042. if (pbr) {
  29043. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  29044. hdrSkyboxMaterial.backFaceCulling = false;
  29045. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  29046. if (hdrSkyboxMaterial.reflectionTexture) {
  29047. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  29048. }
  29049. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  29050. hdrSkyboxMaterial.disableLighting = true;
  29051. hdrSkyboxMaterial.twoSidedLighting = true;
  29052. hdrSkybox.infiniteDistance = true;
  29053. hdrSkybox.material = hdrSkyboxMaterial;
  29054. }
  29055. else {
  29056. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  29057. skyboxMaterial.backFaceCulling = false;
  29058. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  29059. if (skyboxMaterial.reflectionTexture) {
  29060. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  29061. }
  29062. skyboxMaterial.disableLighting = true;
  29063. hdrSkybox.infiniteDistance = true;
  29064. hdrSkybox.material = skyboxMaterial;
  29065. }
  29066. return hdrSkybox;
  29067. };
  29068. /**
  29069. * Creates a new environment
  29070. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  29071. * @param options defines the options you can use to configure the environment
  29072. * @returns the new EnvironmentHelper
  29073. */
  29074. Scene.prototype.createDefaultEnvironment = function (options) {
  29075. if (BABYLON.EnvironmentHelper) {
  29076. return new BABYLON.EnvironmentHelper(options, this);
  29077. }
  29078. return null;
  29079. };
  29080. /**
  29081. * Creates a new VREXperienceHelper
  29082. * @see http://doc.babylonjs.com/how_to/webvr_helper
  29083. * @param webVROptions defines the options used to create the new VREXperienceHelper
  29084. * @returns a new VREXperienceHelper
  29085. */
  29086. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  29087. if (webVROptions === void 0) { webVROptions = {}; }
  29088. return new BABYLON.VRExperienceHelper(this, webVROptions);
  29089. };
  29090. // Tags
  29091. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  29092. if (tagsQuery === undefined) {
  29093. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  29094. return list;
  29095. }
  29096. var listByTags = [];
  29097. forEach = forEach || (function (item) { return; });
  29098. for (var i in list) {
  29099. var item = list[i];
  29100. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  29101. listByTags.push(item);
  29102. forEach(item);
  29103. }
  29104. }
  29105. return listByTags;
  29106. };
  29107. /**
  29108. * Get a list of meshes by tags
  29109. * @param tagsQuery defines the tags query to use
  29110. * @param forEach defines a predicate used to filter results
  29111. * @returns an array of Mesh
  29112. */
  29113. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  29114. return this._getByTags(this.meshes, tagsQuery, forEach);
  29115. };
  29116. /**
  29117. * Get a list of cameras by tags
  29118. * @param tagsQuery defines the tags query to use
  29119. * @param forEach defines a predicate used to filter results
  29120. * @returns an array of Camera
  29121. */
  29122. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  29123. return this._getByTags(this.cameras, tagsQuery, forEach);
  29124. };
  29125. /**
  29126. * Get a list of lights by tags
  29127. * @param tagsQuery defines the tags query to use
  29128. * @param forEach defines a predicate used to filter results
  29129. * @returns an array of Light
  29130. */
  29131. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  29132. return this._getByTags(this.lights, tagsQuery, forEach);
  29133. };
  29134. /**
  29135. * Get a list of materials by tags
  29136. * @param tagsQuery defines the tags query to use
  29137. * @param forEach defines a predicate used to filter results
  29138. * @returns an array of Material
  29139. */
  29140. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  29141. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  29142. };
  29143. /**
  29144. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  29145. * This allowed control for front to back rendering or reversly depending of the special needs.
  29146. *
  29147. * @param renderingGroupId The rendering group id corresponding to its index
  29148. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  29149. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  29150. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  29151. */
  29152. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  29153. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  29154. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  29155. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  29156. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  29157. };
  29158. /**
  29159. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  29160. *
  29161. * @param renderingGroupId The rendering group id corresponding to its index
  29162. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  29163. * @param depth Automatically clears depth between groups if true and autoClear is true.
  29164. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  29165. */
  29166. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  29167. if (depth === void 0) { depth = true; }
  29168. if (stencil === void 0) { stencil = true; }
  29169. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  29170. };
  29171. /**
  29172. * Will flag all materials as dirty to trigger new shader compilation
  29173. * @param flag defines the flag used to specify which material part must be marked as dirty
  29174. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  29175. */
  29176. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  29177. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  29178. var material = _a[_i];
  29179. if (predicate && !predicate(material)) {
  29180. continue;
  29181. }
  29182. material.markAsDirty(flag);
  29183. }
  29184. };
  29185. /** @hidden */
  29186. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  29187. var _this = this;
  29188. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  29189. this._activeRequests.push(request);
  29190. request.onCompleteObservable.add(function (request) {
  29191. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  29192. });
  29193. return request;
  29194. };
  29195. /** @hidden */
  29196. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  29197. var _this = this;
  29198. return new Promise(function (resolve, reject) {
  29199. _this._loadFile(url, function (data) {
  29200. resolve(data);
  29201. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  29202. reject(exception);
  29203. });
  29204. });
  29205. };
  29206. // Statics
  29207. Scene._FOGMODE_NONE = 0;
  29208. Scene._FOGMODE_EXP = 1;
  29209. Scene._FOGMODE_EXP2 = 2;
  29210. Scene._FOGMODE_LINEAR = 3;
  29211. Scene._uniqueIdCounter = 0;
  29212. /**
  29213. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  29214. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  29215. */
  29216. Scene.MinDeltaTime = 1.0;
  29217. /**
  29218. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  29219. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  29220. */
  29221. Scene.MaxDeltaTime = 1000.0;
  29222. /** The distance in pixel that you have to move to prevent some events */
  29223. Scene.DragMovementThreshold = 10; // in pixels
  29224. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  29225. Scene.LongPressDelay = 500; // in milliseconds
  29226. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  29227. Scene.DoubleClickDelay = 300; // in milliseconds
  29228. /** If you need to check double click without raising a single click at first click, enable this flag */
  29229. Scene.ExclusiveDoubleClickMode = false;
  29230. return Scene;
  29231. }());
  29232. BABYLON.Scene = Scene;
  29233. })(BABYLON || (BABYLON = {}));
  29234. //# sourceMappingURL=babylon.scene.js.map
  29235. var BABYLON;
  29236. (function (BABYLON) {
  29237. /**
  29238. * Set of assets to keep when moving a scene into an asset container.
  29239. */
  29240. var KeepAssets = /** @class */ (function () {
  29241. function KeepAssets() {
  29242. /**
  29243. * Cameras to keep.
  29244. */
  29245. this.cameras = new Array();
  29246. /**
  29247. * Lights to keep.
  29248. */
  29249. this.lights = new Array();
  29250. /**
  29251. * Meshes to keep.
  29252. */
  29253. this.meshes = new Array();
  29254. /**
  29255. * Skeletons to keep.
  29256. */
  29257. this.skeletons = new Array();
  29258. /**
  29259. * ParticleSystems to keep.
  29260. */
  29261. this.particleSystems = new Array();
  29262. /**
  29263. * Animations to keep.
  29264. */
  29265. this.animations = new Array();
  29266. /**
  29267. * AnimationGroups to keep.
  29268. */
  29269. this.animationGroups = new Array();
  29270. /**
  29271. * MultiMaterials to keep.
  29272. */
  29273. this.multiMaterials = new Array();
  29274. /**
  29275. * Materials to keep.
  29276. */
  29277. this.materials = new Array();
  29278. /**
  29279. * MorphTargetManagers to keep.
  29280. */
  29281. this.morphTargetManagers = new Array();
  29282. /**
  29283. * Geometries to keep.
  29284. */
  29285. this.geometries = new Array();
  29286. /**
  29287. * TransformNodes to keep.
  29288. */
  29289. this.transformNodes = new Array();
  29290. /**
  29291. * LensFlareSystems to keep.
  29292. */
  29293. this.lensFlareSystems = new Array();
  29294. /**
  29295. * ShadowGenerators to keep.
  29296. */
  29297. this.shadowGenerators = new Array();
  29298. /**
  29299. * ActionManagers to keep.
  29300. */
  29301. this.actionManagers = new Array();
  29302. /**
  29303. * Sounds to keep.
  29304. */
  29305. this.sounds = new Array();
  29306. /**
  29307. * Textures to keep.
  29308. */
  29309. this.textures = new Array();
  29310. /**
  29311. * Effect layers to keep.
  29312. */
  29313. this.effectLayers = new Array();
  29314. }
  29315. return KeepAssets;
  29316. }());
  29317. BABYLON.KeepAssets = KeepAssets;
  29318. /**
  29319. * Container with a set of assets that can be added or removed from a scene.
  29320. */
  29321. var AssetContainer = /** @class */ (function () {
  29322. /**
  29323. * Instantiates an AssetContainer.
  29324. * @param scene The scene the AssetContainer belongs to.
  29325. */
  29326. function AssetContainer(scene) {
  29327. // Objects
  29328. /**
  29329. * Cameras populated in the container.
  29330. */
  29331. this.cameras = new Array();
  29332. /**
  29333. * Lights populated in the container.
  29334. */
  29335. this.lights = new Array();
  29336. /**
  29337. * Meshes populated in the container.
  29338. */
  29339. this.meshes = new Array();
  29340. /**
  29341. * Skeletons populated in the container.
  29342. */
  29343. this.skeletons = new Array();
  29344. /**
  29345. * ParticleSystems populated in the container.
  29346. */
  29347. this.particleSystems = new Array();
  29348. /**
  29349. * Animations populated in the container.
  29350. */
  29351. this.animations = new Array();
  29352. /**
  29353. * AnimationGroups populated in the container.
  29354. */
  29355. this.animationGroups = new Array();
  29356. /**
  29357. * MultiMaterials populated in the container.
  29358. */
  29359. this.multiMaterials = new Array();
  29360. /**
  29361. * Materials populated in the container.
  29362. */
  29363. this.materials = new Array();
  29364. /**
  29365. * MorphTargetManagers populated in the container.
  29366. */
  29367. this.morphTargetManagers = new Array();
  29368. /**
  29369. * Geometries populated in the container.
  29370. */
  29371. this.geometries = new Array();
  29372. /**
  29373. * TransformNodes populated in the container.
  29374. */
  29375. this.transformNodes = new Array();
  29376. /**
  29377. * LensFlareSystems populated in the container.
  29378. */
  29379. this.lensFlareSystems = new Array();
  29380. /**
  29381. * ShadowGenerators populated in the container.
  29382. */
  29383. this.shadowGenerators = new Array();
  29384. /**
  29385. * ActionManagers populated in the container.
  29386. */
  29387. this.actionManagers = new Array();
  29388. /**
  29389. * Sounds populated in the container.
  29390. */
  29391. this.sounds = new Array();
  29392. /**
  29393. * Textures populated in the container.
  29394. */
  29395. this.textures = new Array();
  29396. /**
  29397. * Effect layers populated in the container.
  29398. */
  29399. this.effectLayers = new Array();
  29400. this.scene = scene;
  29401. }
  29402. /**
  29403. * Adds all the assets from the container to the scene.
  29404. */
  29405. AssetContainer.prototype.addAllToScene = function () {
  29406. var _this = this;
  29407. this.cameras.forEach(function (o) {
  29408. _this.scene.addCamera(o);
  29409. });
  29410. this.lights.forEach(function (o) {
  29411. _this.scene.addLight(o);
  29412. });
  29413. this.meshes.forEach(function (o) {
  29414. _this.scene.addMesh(o);
  29415. });
  29416. this.skeletons.forEach(function (o) {
  29417. _this.scene.addSkeleton(o);
  29418. });
  29419. this.particleSystems.forEach(function (o) {
  29420. _this.scene.addParticleSystem(o);
  29421. });
  29422. this.animations.forEach(function (o) {
  29423. _this.scene.addAnimation(o);
  29424. });
  29425. this.animationGroups.forEach(function (o) {
  29426. _this.scene.addAnimationGroup(o);
  29427. });
  29428. this.multiMaterials.forEach(function (o) {
  29429. _this.scene.addMultiMaterial(o);
  29430. });
  29431. this.materials.forEach(function (o) {
  29432. _this.scene.addMaterial(o);
  29433. });
  29434. this.morphTargetManagers.forEach(function (o) {
  29435. _this.scene.addMorphTargetManager(o);
  29436. });
  29437. this.geometries.forEach(function (o) {
  29438. _this.scene.addGeometry(o);
  29439. });
  29440. this.transformNodes.forEach(function (o) {
  29441. _this.scene.addTransformNode(o);
  29442. });
  29443. this.lensFlareSystems.forEach(function (o) {
  29444. _this.scene.addLensFlareSystem(o);
  29445. });
  29446. this.actionManagers.forEach(function (o) {
  29447. _this.scene.addActionManager(o);
  29448. });
  29449. this.sounds.forEach(function (o) {
  29450. o.play();
  29451. o.autoplay = true;
  29452. _this.scene.mainSoundTrack.AddSound(o);
  29453. });
  29454. this.textures.forEach(function (o) {
  29455. _this.scene.addTexture(o);
  29456. });
  29457. this.effectLayers.forEach(function (o) {
  29458. _this.scene.addEffectLayer(o);
  29459. });
  29460. };
  29461. /**
  29462. * Removes all the assets in the container from the scene
  29463. */
  29464. AssetContainer.prototype.removeAllFromScene = function () {
  29465. var _this = this;
  29466. this.cameras.forEach(function (o) {
  29467. _this.scene.removeCamera(o);
  29468. });
  29469. this.lights.forEach(function (o) {
  29470. _this.scene.removeLight(o);
  29471. });
  29472. this.meshes.forEach(function (o) {
  29473. _this.scene.removeMesh(o);
  29474. });
  29475. this.skeletons.forEach(function (o) {
  29476. _this.scene.removeSkeleton(o);
  29477. });
  29478. this.particleSystems.forEach(function (o) {
  29479. _this.scene.removeParticleSystem(o);
  29480. });
  29481. this.animations.forEach(function (o) {
  29482. _this.scene.removeAnimation(o);
  29483. });
  29484. this.animationGroups.forEach(function (o) {
  29485. _this.scene.removeAnimationGroup(o);
  29486. });
  29487. this.multiMaterials.forEach(function (o) {
  29488. _this.scene.removeMultiMaterial(o);
  29489. });
  29490. this.materials.forEach(function (o) {
  29491. _this.scene.removeMaterial(o);
  29492. });
  29493. this.morphTargetManagers.forEach(function (o) {
  29494. _this.scene.removeMorphTargetManager(o);
  29495. });
  29496. this.geometries.forEach(function (o) {
  29497. _this.scene.removeGeometry(o);
  29498. });
  29499. this.transformNodes.forEach(function (o) {
  29500. _this.scene.removeTransformNode(o);
  29501. });
  29502. this.lensFlareSystems.forEach(function (o) {
  29503. _this.scene.removeLensFlareSystem(o);
  29504. });
  29505. this.actionManagers.forEach(function (o) {
  29506. _this.scene.removeActionManager(o);
  29507. });
  29508. this.sounds.forEach(function (o) {
  29509. o.stop();
  29510. o.autoplay = false;
  29511. _this.scene.mainSoundTrack.RemoveSound(o);
  29512. });
  29513. this.textures.forEach(function (o) {
  29514. _this.scene.removeTexture(o);
  29515. });
  29516. this.effectLayers.forEach(function (o) {
  29517. _this.scene.removeEffectLayer(o);
  29518. });
  29519. };
  29520. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  29521. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  29522. var asset = sourceAssets_1[_i];
  29523. var move = true;
  29524. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  29525. var keepAsset = keepAssets_1[_a];
  29526. if (asset === keepAsset) {
  29527. move = false;
  29528. break;
  29529. }
  29530. }
  29531. if (move) {
  29532. targetAssets.push(asset);
  29533. }
  29534. }
  29535. };
  29536. /**
  29537. * Removes all the assets contained in the scene and adds them to the container.
  29538. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  29539. */
  29540. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  29541. if (keepAssets === undefined) {
  29542. keepAssets = new KeepAssets();
  29543. }
  29544. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  29545. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  29546. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  29547. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  29548. this._moveAssets(this.scene._actionManagers, this.actionManagers, keepAssets.actionManagers);
  29549. this._moveAssets(this.scene.animations, this.animations, keepAssets.animations);
  29550. this._moveAssets(this.scene.animationGroups, this.animationGroups, keepAssets.animationGroups);
  29551. this._moveAssets(this.scene.lensFlareSystems, this.lensFlareSystems, keepAssets.lensFlareSystems);
  29552. this._moveAssets(this.scene.lights, this.lights, keepAssets.lights);
  29553. this._moveAssets(this.scene.morphTargetManagers, this.morphTargetManagers, keepAssets.morphTargetManagers);
  29554. this._moveAssets(this.scene.multiMaterials, this.multiMaterials, keepAssets.multiMaterials);
  29555. this._moveAssets(this.scene.skeletons, this.skeletons, keepAssets.skeletons);
  29556. this._moveAssets(this.scene.particleSystems, this.particleSystems, keepAssets.particleSystems);
  29557. this._moveAssets(this.scene.mainSoundTrack.soundCollection, this.sounds, keepAssets.sounds);
  29558. this._moveAssets(this.scene.transformNodes, this.transformNodes, keepAssets.transformNodes);
  29559. this._moveAssets(this.scene.textures, this.textures, keepAssets.textures);
  29560. this._moveAssets(this.scene.effectLayers, this.effectLayers, keepAssets.effectLayers);
  29561. this.removeAllFromScene();
  29562. };
  29563. /**
  29564. * 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.
  29565. * @returns the root mesh
  29566. */
  29567. AssetContainer.prototype.createRootMesh = function () {
  29568. var rootMesh = new BABYLON.Mesh("assetContainerRootMesh", this.scene);
  29569. this.meshes.forEach(function (m) {
  29570. if (!m.parent) {
  29571. rootMesh.addChild(m);
  29572. }
  29573. });
  29574. this.meshes.unshift(rootMesh);
  29575. return rootMesh;
  29576. };
  29577. return AssetContainer;
  29578. }());
  29579. BABYLON.AssetContainer = AssetContainer;
  29580. })(BABYLON || (BABYLON = {}));
  29581. //# sourceMappingURL=babylon.assetContainer.js.map
  29582. var BABYLON;
  29583. (function (BABYLON) {
  29584. var Buffer = /** @class */ (function () {
  29585. /**
  29586. * Constructor
  29587. * @param engine the engine
  29588. * @param data the data to use for this buffer
  29589. * @param updatable whether the data is updatable
  29590. * @param stride the stride (optional)
  29591. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29592. * @param instanced whether the buffer is instanced (optional)
  29593. * @param useBytes set to true if the stride in in bytes (optional)
  29594. */
  29595. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  29596. if (stride === void 0) { stride = 0; }
  29597. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  29598. if (instanced === void 0) { instanced = false; }
  29599. if (useBytes === void 0) { useBytes = false; }
  29600. if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'
  29601. this._engine = engine.getScene().getEngine();
  29602. }
  29603. else {
  29604. this._engine = engine;
  29605. }
  29606. this._updatable = updatable;
  29607. this._instanced = instanced;
  29608. this._data = data;
  29609. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  29610. if (!postponeInternalCreation) { // by default
  29611. this.create();
  29612. }
  29613. }
  29614. /**
  29615. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  29616. * @param kind defines the vertex buffer kind (position, normal, etc.)
  29617. * @param offset defines offset in the buffer (0 by default)
  29618. * @param size defines the size in floats of attributes (position is 3 for instance)
  29619. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  29620. * @param instanced defines if the vertex buffer contains indexed data
  29621. * @param useBytes defines if the offset and stride are in bytes
  29622. * @returns the new vertex buffer
  29623. */
  29624. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  29625. if (useBytes === void 0) { useBytes = false; }
  29626. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  29627. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  29628. // a lot of these parameters are ignored as they are overriden by the buffer
  29629. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  29630. };
  29631. // Properties
  29632. Buffer.prototype.isUpdatable = function () {
  29633. return this._updatable;
  29634. };
  29635. Buffer.prototype.getData = function () {
  29636. return this._data;
  29637. };
  29638. Buffer.prototype.getBuffer = function () {
  29639. return this._buffer;
  29640. };
  29641. /**
  29642. * Gets the stride in float32 units (i.e. byte stride / 4).
  29643. * May not be an integer if the byte stride is not divisible by 4.
  29644. * DEPRECATED. Use byteStride instead.
  29645. * @returns the stride in float32 units
  29646. */
  29647. Buffer.prototype.getStrideSize = function () {
  29648. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  29649. };
  29650. // Methods
  29651. Buffer.prototype.create = function (data) {
  29652. if (data === void 0) { data = null; }
  29653. if (!data && this._buffer) {
  29654. return; // nothing to do
  29655. }
  29656. data = data || this._data;
  29657. if (!data) {
  29658. return;
  29659. }
  29660. if (!this._buffer) { // create buffer
  29661. if (this._updatable) {
  29662. this._buffer = this._engine.createDynamicVertexBuffer(data);
  29663. this._data = data;
  29664. }
  29665. else {
  29666. this._buffer = this._engine.createVertexBuffer(data);
  29667. }
  29668. }
  29669. else if (this._updatable) { // update buffer
  29670. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  29671. this._data = data;
  29672. }
  29673. };
  29674. Buffer.prototype._rebuild = function () {
  29675. this._buffer = null;
  29676. this.create(this._data);
  29677. };
  29678. Buffer.prototype.update = function (data) {
  29679. this.create(data);
  29680. };
  29681. /**
  29682. * Updates the data directly.
  29683. * @param data the new data
  29684. * @param offset the new offset
  29685. * @param vertexCount the vertex count (optional)
  29686. * @param useBytes set to true if the offset is in bytes
  29687. */
  29688. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  29689. if (useBytes === void 0) { useBytes = false; }
  29690. if (!this._buffer) {
  29691. return;
  29692. }
  29693. if (this._updatable) { // update buffer
  29694. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  29695. this._data = null;
  29696. }
  29697. };
  29698. Buffer.prototype.dispose = function () {
  29699. if (!this._buffer) {
  29700. return;
  29701. }
  29702. if (this._engine._releaseBuffer(this._buffer)) {
  29703. this._buffer = null;
  29704. }
  29705. };
  29706. return Buffer;
  29707. }());
  29708. BABYLON.Buffer = Buffer;
  29709. })(BABYLON || (BABYLON = {}));
  29710. //# sourceMappingURL=babylon.buffer.js.map
  29711. var BABYLON;
  29712. (function (BABYLON) {
  29713. var VertexBuffer = /** @class */ (function () {
  29714. /**
  29715. * Constructor
  29716. * @param engine the engine
  29717. * @param data the data to use for this vertex buffer
  29718. * @param kind the vertex buffer kind
  29719. * @param updatable whether the data is updatable
  29720. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29721. * @param stride the stride (optional)
  29722. * @param instanced whether the buffer is instanced (optional)
  29723. * @param offset the offset of the data (optional)
  29724. * @param size the number of components (optional)
  29725. * @param type the type of the component (optional)
  29726. * @param normalized whether the data contains normalized data (optional)
  29727. * @param useBytes set to true if stride and offset are in bytes (optional)
  29728. */
  29729. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  29730. if (normalized === void 0) { normalized = false; }
  29731. if (useBytes === void 0) { useBytes = false; }
  29732. if (data instanceof BABYLON.Buffer) {
  29733. this._buffer = data;
  29734. this._ownsBuffer = false;
  29735. }
  29736. else {
  29737. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  29738. this._ownsBuffer = true;
  29739. }
  29740. this._kind = kind;
  29741. if (type == undefined) {
  29742. var data_1 = this.getData();
  29743. this.type = VertexBuffer.FLOAT;
  29744. if (data_1 instanceof Int8Array)
  29745. this.type = VertexBuffer.BYTE;
  29746. else if (data_1 instanceof Uint8Array)
  29747. this.type = VertexBuffer.UNSIGNED_BYTE;
  29748. else if (data_1 instanceof Int16Array)
  29749. this.type = VertexBuffer.SHORT;
  29750. else if (data_1 instanceof Uint16Array)
  29751. this.type = VertexBuffer.UNSIGNED_SHORT;
  29752. else if (data_1 instanceof Int32Array)
  29753. this.type = VertexBuffer.INT;
  29754. else if (data_1 instanceof Uint32Array)
  29755. this.type = VertexBuffer.UNSIGNED_INT;
  29756. }
  29757. else {
  29758. this.type = type;
  29759. }
  29760. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  29761. if (useBytes) {
  29762. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  29763. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  29764. this.byteOffset = offset || 0;
  29765. }
  29766. else {
  29767. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  29768. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  29769. this.byteOffset = (offset || 0) * typeByteLength;
  29770. }
  29771. this.normalized = normalized;
  29772. this._instanced = instanced !== undefined ? instanced : false;
  29773. this._instanceDivisor = instanced ? 1 : 0;
  29774. }
  29775. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  29776. /**
  29777. * Gets or sets the instance divisor when in instanced mode
  29778. */
  29779. get: function () {
  29780. return this._instanceDivisor;
  29781. },
  29782. set: function (value) {
  29783. this._instanceDivisor = value;
  29784. if (value == 0) {
  29785. this._instanced = false;
  29786. }
  29787. else {
  29788. this._instanced = true;
  29789. }
  29790. },
  29791. enumerable: true,
  29792. configurable: true
  29793. });
  29794. VertexBuffer.prototype._rebuild = function () {
  29795. if (!this._buffer) {
  29796. return;
  29797. }
  29798. this._buffer._rebuild();
  29799. };
  29800. /**
  29801. * Returns the kind of the VertexBuffer (string).
  29802. */
  29803. VertexBuffer.prototype.getKind = function () {
  29804. return this._kind;
  29805. };
  29806. // Properties
  29807. /**
  29808. * Boolean : is the VertexBuffer updatable ?
  29809. */
  29810. VertexBuffer.prototype.isUpdatable = function () {
  29811. return this._buffer.isUpdatable();
  29812. };
  29813. /**
  29814. * Returns an array of numbers or a typed array containing the VertexBuffer data.
  29815. */
  29816. VertexBuffer.prototype.getData = function () {
  29817. return this._buffer.getData();
  29818. };
  29819. /**
  29820. * Returns the WebGLBuffer associated to the VertexBuffer.
  29821. */
  29822. VertexBuffer.prototype.getBuffer = function () {
  29823. return this._buffer.getBuffer();
  29824. };
  29825. /**
  29826. * Returns the stride as a multiple of the type byte length.
  29827. * DEPRECATED. Use byteStride instead.
  29828. */
  29829. VertexBuffer.prototype.getStrideSize = function () {
  29830. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  29831. };
  29832. /**
  29833. * Returns the offset as a multiple of the type byte length.
  29834. * DEPRECATED. Use byteOffset instead.
  29835. */
  29836. VertexBuffer.prototype.getOffset = function () {
  29837. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  29838. };
  29839. /**
  29840. * Returns the number of components per vertex attribute (integer).
  29841. */
  29842. VertexBuffer.prototype.getSize = function () {
  29843. return this._size;
  29844. };
  29845. /**
  29846. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  29847. */
  29848. VertexBuffer.prototype.getIsInstanced = function () {
  29849. return this._instanced;
  29850. };
  29851. /**
  29852. * Returns the instancing divisor, zero for non-instanced (integer).
  29853. */
  29854. VertexBuffer.prototype.getInstanceDivisor = function () {
  29855. return this._instanceDivisor;
  29856. };
  29857. // Methods
  29858. /**
  29859. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  29860. * Returns the created WebGLBuffer.
  29861. */
  29862. VertexBuffer.prototype.create = function (data) {
  29863. return this._buffer.create(data);
  29864. };
  29865. /**
  29866. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29867. * This function will create a new buffer if the current one is not updatable
  29868. * Returns the updated WebGLBuffer.
  29869. */
  29870. VertexBuffer.prototype.update = function (data) {
  29871. return this._buffer.update(data);
  29872. };
  29873. /**
  29874. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29875. * Returns the directly updated WebGLBuffer.
  29876. * @param data the new data
  29877. * @param offset the new offset
  29878. * @param useBytes set to true if the offset is in bytes
  29879. */
  29880. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  29881. if (useBytes === void 0) { useBytes = false; }
  29882. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  29883. };
  29884. /**
  29885. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  29886. */
  29887. VertexBuffer.prototype.dispose = function () {
  29888. if (this._ownsBuffer) {
  29889. this._buffer.dispose();
  29890. }
  29891. };
  29892. /**
  29893. * Enumerates each value of this vertex buffer as numbers.
  29894. * @param count the number of values to enumerate
  29895. * @param callback the callback function called for each value
  29896. */
  29897. VertexBuffer.prototype.forEach = function (count, callback) {
  29898. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  29899. };
  29900. Object.defineProperty(VertexBuffer, "PositionKind", {
  29901. get: function () {
  29902. return VertexBuffer._PositionKind;
  29903. },
  29904. enumerable: true,
  29905. configurable: true
  29906. });
  29907. Object.defineProperty(VertexBuffer, "NormalKind", {
  29908. get: function () {
  29909. return VertexBuffer._NormalKind;
  29910. },
  29911. enumerable: true,
  29912. configurable: true
  29913. });
  29914. Object.defineProperty(VertexBuffer, "TangentKind", {
  29915. get: function () {
  29916. return VertexBuffer._TangentKind;
  29917. },
  29918. enumerable: true,
  29919. configurable: true
  29920. });
  29921. Object.defineProperty(VertexBuffer, "UVKind", {
  29922. get: function () {
  29923. return VertexBuffer._UVKind;
  29924. },
  29925. enumerable: true,
  29926. configurable: true
  29927. });
  29928. Object.defineProperty(VertexBuffer, "UV2Kind", {
  29929. get: function () {
  29930. return VertexBuffer._UV2Kind;
  29931. },
  29932. enumerable: true,
  29933. configurable: true
  29934. });
  29935. Object.defineProperty(VertexBuffer, "UV3Kind", {
  29936. get: function () {
  29937. return VertexBuffer._UV3Kind;
  29938. },
  29939. enumerable: true,
  29940. configurable: true
  29941. });
  29942. Object.defineProperty(VertexBuffer, "UV4Kind", {
  29943. get: function () {
  29944. return VertexBuffer._UV4Kind;
  29945. },
  29946. enumerable: true,
  29947. configurable: true
  29948. });
  29949. Object.defineProperty(VertexBuffer, "UV5Kind", {
  29950. get: function () {
  29951. return VertexBuffer._UV5Kind;
  29952. },
  29953. enumerable: true,
  29954. configurable: true
  29955. });
  29956. Object.defineProperty(VertexBuffer, "UV6Kind", {
  29957. get: function () {
  29958. return VertexBuffer._UV6Kind;
  29959. },
  29960. enumerable: true,
  29961. configurable: true
  29962. });
  29963. Object.defineProperty(VertexBuffer, "ColorKind", {
  29964. get: function () {
  29965. return VertexBuffer._ColorKind;
  29966. },
  29967. enumerable: true,
  29968. configurable: true
  29969. });
  29970. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  29971. get: function () {
  29972. return VertexBuffer._MatricesIndicesKind;
  29973. },
  29974. enumerable: true,
  29975. configurable: true
  29976. });
  29977. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  29978. get: function () {
  29979. return VertexBuffer._MatricesWeightsKind;
  29980. },
  29981. enumerable: true,
  29982. configurable: true
  29983. });
  29984. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  29985. get: function () {
  29986. return VertexBuffer._MatricesIndicesExtraKind;
  29987. },
  29988. enumerable: true,
  29989. configurable: true
  29990. });
  29991. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  29992. get: function () {
  29993. return VertexBuffer._MatricesWeightsExtraKind;
  29994. },
  29995. enumerable: true,
  29996. configurable: true
  29997. });
  29998. /**
  29999. * Deduces the stride given a kind.
  30000. * @param kind The kind string to deduce
  30001. * @returns The deduced stride
  30002. */
  30003. VertexBuffer.DeduceStride = function (kind) {
  30004. switch (kind) {
  30005. case VertexBuffer.UVKind:
  30006. case VertexBuffer.UV2Kind:
  30007. case VertexBuffer.UV3Kind:
  30008. case VertexBuffer.UV4Kind:
  30009. case VertexBuffer.UV5Kind:
  30010. case VertexBuffer.UV6Kind:
  30011. return 2;
  30012. case VertexBuffer.NormalKind:
  30013. case VertexBuffer.PositionKind:
  30014. return 3;
  30015. case VertexBuffer.ColorKind:
  30016. case VertexBuffer.MatricesIndicesKind:
  30017. case VertexBuffer.MatricesIndicesExtraKind:
  30018. case VertexBuffer.MatricesWeightsKind:
  30019. case VertexBuffer.MatricesWeightsExtraKind:
  30020. case VertexBuffer.TangentKind:
  30021. return 4;
  30022. default:
  30023. throw new Error("Invalid kind '" + kind + "'");
  30024. }
  30025. };
  30026. /**
  30027. * Gets the byte length of the given type.
  30028. * @param type the type
  30029. * @returns the number of bytes
  30030. */
  30031. VertexBuffer.GetTypeByteLength = function (type) {
  30032. switch (type) {
  30033. case VertexBuffer.BYTE:
  30034. case VertexBuffer.UNSIGNED_BYTE:
  30035. return 1;
  30036. case VertexBuffer.SHORT:
  30037. case VertexBuffer.UNSIGNED_SHORT:
  30038. return 2;
  30039. case VertexBuffer.INT:
  30040. case VertexBuffer.FLOAT:
  30041. return 4;
  30042. default:
  30043. throw new Error("Invalid type '" + type + "'");
  30044. }
  30045. };
  30046. /**
  30047. * Enumerates each value of the given parameters as numbers.
  30048. * @param data the data to enumerate
  30049. * @param byteOffset the byte offset of the data
  30050. * @param byteStride the byte stride of the data
  30051. * @param componentCount the number of components per element
  30052. * @param componentType the type of the component
  30053. * @param count the total number of components
  30054. * @param normalized whether the data is normalized
  30055. * @param callback the callback function called for each value
  30056. */
  30057. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  30058. if (data instanceof Array) {
  30059. var offset = byteOffset / 4;
  30060. var stride = byteStride / 4;
  30061. for (var index = 0; index < count; index += componentCount) {
  30062. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  30063. callback(data[offset + componentIndex], index + componentIndex);
  30064. }
  30065. offset += stride;
  30066. }
  30067. }
  30068. else {
  30069. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  30070. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  30071. for (var index = 0; index < count; index += componentCount) {
  30072. var componentByteOffset = byteOffset;
  30073. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  30074. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  30075. callback(value, index + componentIndex);
  30076. componentByteOffset += componentByteLength;
  30077. }
  30078. byteOffset += byteStride;
  30079. }
  30080. }
  30081. };
  30082. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  30083. switch (type) {
  30084. case VertexBuffer.BYTE: {
  30085. var value = dataView.getInt8(byteOffset);
  30086. if (normalized) {
  30087. value = Math.max(value / 127, -1);
  30088. }
  30089. return value;
  30090. }
  30091. case VertexBuffer.UNSIGNED_BYTE: {
  30092. var value = dataView.getUint8(byteOffset);
  30093. if (normalized) {
  30094. value = value / 255;
  30095. }
  30096. return value;
  30097. }
  30098. case VertexBuffer.SHORT: {
  30099. var value = dataView.getInt16(byteOffset, true);
  30100. if (normalized) {
  30101. value = Math.max(value / 16383, -1);
  30102. }
  30103. return value;
  30104. }
  30105. case VertexBuffer.UNSIGNED_SHORT: {
  30106. var value = dataView.getUint16(byteOffset, true);
  30107. if (normalized) {
  30108. value = value / 65535;
  30109. }
  30110. return value;
  30111. }
  30112. case VertexBuffer.FLOAT: {
  30113. return dataView.getFloat32(byteOffset, true);
  30114. }
  30115. default: {
  30116. throw new Error("Invalid component type " + type);
  30117. }
  30118. }
  30119. };
  30120. /**
  30121. * The byte type.
  30122. */
  30123. VertexBuffer.BYTE = 5120;
  30124. /**
  30125. * The unsigned byte type.
  30126. */
  30127. VertexBuffer.UNSIGNED_BYTE = 5121;
  30128. /**
  30129. * The short type.
  30130. */
  30131. VertexBuffer.SHORT = 5122;
  30132. /**
  30133. * The unsigned short type.
  30134. */
  30135. VertexBuffer.UNSIGNED_SHORT = 5123;
  30136. /**
  30137. * The integer type.
  30138. */
  30139. VertexBuffer.INT = 5124;
  30140. /**
  30141. * The unsigned integer type.
  30142. */
  30143. VertexBuffer.UNSIGNED_INT = 5125;
  30144. /**
  30145. * The float type.
  30146. */
  30147. VertexBuffer.FLOAT = 5126;
  30148. // Enums
  30149. VertexBuffer._PositionKind = "position";
  30150. VertexBuffer._NormalKind = "normal";
  30151. VertexBuffer._TangentKind = "tangent";
  30152. VertexBuffer._UVKind = "uv";
  30153. VertexBuffer._UV2Kind = "uv2";
  30154. VertexBuffer._UV3Kind = "uv3";
  30155. VertexBuffer._UV4Kind = "uv4";
  30156. VertexBuffer._UV5Kind = "uv5";
  30157. VertexBuffer._UV6Kind = "uv6";
  30158. VertexBuffer._ColorKind = "color";
  30159. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  30160. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  30161. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  30162. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  30163. return VertexBuffer;
  30164. }());
  30165. BABYLON.VertexBuffer = VertexBuffer;
  30166. })(BABYLON || (BABYLON = {}));
  30167. //# sourceMappingURL=babylon.vertexBuffer.js.map
  30168. var BABYLON;
  30169. (function (BABYLON) {
  30170. /**
  30171. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  30172. */
  30173. var DummyInternalTextureTracker = /** @class */ (function () {
  30174. function DummyInternalTextureTracker() {
  30175. /**
  30176. * Gets or set the previous tracker in the list
  30177. */
  30178. this.previous = null;
  30179. /**
  30180. * Gets or set the next tracker in the list
  30181. */
  30182. this.next = null;
  30183. }
  30184. return DummyInternalTextureTracker;
  30185. }());
  30186. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  30187. })(BABYLON || (BABYLON = {}));
  30188. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  30189. var BABYLON;
  30190. (function (BABYLON) {
  30191. /**
  30192. * Class used to store data associated with WebGL texture data for the engine
  30193. * This class should not be used directly
  30194. */
  30195. var InternalTexture = /** @class */ (function () {
  30196. /**
  30197. * Creates a new InternalTexture
  30198. * @param engine defines the engine to use
  30199. * @param dataSource defines the type of data that will be used
  30200. */
  30201. function InternalTexture(engine, dataSource) {
  30202. /**
  30203. * Observable called when the texture is loaded
  30204. */
  30205. this.onLoadedObservable = new BABYLON.Observable();
  30206. /**
  30207. * Gets or set the previous tracker in the list
  30208. */
  30209. this.previous = null;
  30210. /**
  30211. * Gets or set the next tracker in the list
  30212. */
  30213. this.next = null;
  30214. // Private
  30215. /** @hidden */
  30216. this._initialSlot = -1;
  30217. /** @hidden */
  30218. this._designatedSlot = -1;
  30219. /** @hidden */
  30220. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  30221. /** @hidden */
  30222. this._comparisonFunction = 0;
  30223. /** @hidden */
  30224. this._isRGBD = false;
  30225. /** @hidden */
  30226. this._references = 1;
  30227. this._engine = engine;
  30228. this._dataSource = dataSource;
  30229. this._webGLTexture = engine._createTexture();
  30230. }
  30231. /**
  30232. * Gets the Engine the texture belongs to.
  30233. * @returns The babylon engine
  30234. */
  30235. InternalTexture.prototype.getEngine = function () {
  30236. return this._engine;
  30237. };
  30238. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  30239. /**
  30240. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  30241. */
  30242. get: function () {
  30243. return this._dataSource;
  30244. },
  30245. enumerable: true,
  30246. configurable: true
  30247. });
  30248. /**
  30249. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  30250. */
  30251. InternalTexture.prototype.incrementReferences = function () {
  30252. this._references++;
  30253. };
  30254. /**
  30255. * Change the size of the texture (not the size of the content)
  30256. * @param width defines the new width
  30257. * @param height defines the new height
  30258. * @param depth defines the new depth (1 by default)
  30259. */
  30260. InternalTexture.prototype.updateSize = function (width, height, depth) {
  30261. if (depth === void 0) { depth = 1; }
  30262. this.width = width;
  30263. this.height = height;
  30264. this.depth = depth;
  30265. this.baseWidth = width;
  30266. this.baseHeight = height;
  30267. this.baseDepth = depth;
  30268. this._size = width * height * depth;
  30269. };
  30270. /** @hidden */
  30271. InternalTexture.prototype._rebuild = function () {
  30272. var _this = this;
  30273. var proxy;
  30274. this.isReady = false;
  30275. this._cachedCoordinatesMode = null;
  30276. this._cachedWrapU = null;
  30277. this._cachedWrapV = null;
  30278. this._cachedAnisotropicFilteringLevel = null;
  30279. switch (this._dataSource) {
  30280. case InternalTexture.DATASOURCE_TEMP:
  30281. return;
  30282. case InternalTexture.DATASOURCE_URL:
  30283. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  30284. _this.isReady = true;
  30285. }, null, this._buffer, undefined, this.format);
  30286. proxy._swapAndDie(this);
  30287. return;
  30288. case InternalTexture.DATASOURCE_RAW:
  30289. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30290. proxy._swapAndDie(this);
  30291. this.isReady = true;
  30292. return;
  30293. case InternalTexture.DATASOURCE_RAW3D:
  30294. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30295. proxy._swapAndDie(this);
  30296. this.isReady = true;
  30297. return;
  30298. case InternalTexture.DATASOURCE_DYNAMIC:
  30299. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  30300. proxy._swapAndDie(this);
  30301. // The engine will make sure to update content so no need to flag it as isReady = true
  30302. return;
  30303. case InternalTexture.DATASOURCE_RENDERTARGET:
  30304. var options = new BABYLON.RenderTargetCreationOptions();
  30305. options.generateDepthBuffer = this._generateDepthBuffer;
  30306. options.generateMipMaps = this.generateMipMaps;
  30307. options.generateStencilBuffer = this._generateStencilBuffer;
  30308. options.samplingMode = this.samplingMode;
  30309. options.type = this.type;
  30310. if (this.isCube) {
  30311. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  30312. }
  30313. else {
  30314. var size = {
  30315. width: this.width,
  30316. height: this.height
  30317. };
  30318. proxy = this._engine.createRenderTargetTexture(size, options);
  30319. }
  30320. proxy._swapAndDie(this);
  30321. this.isReady = true;
  30322. return;
  30323. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  30324. var depthTextureOptions = {
  30325. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  30326. comparisonFunction: this._comparisonFunction,
  30327. generateStencil: this._generateStencilBuffer,
  30328. isCube: this.isCube
  30329. };
  30330. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  30331. proxy._swapAndDie(this);
  30332. this.isReady = true;
  30333. return;
  30334. case InternalTexture.DATASOURCE_CUBE:
  30335. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  30336. _this.isReady = true;
  30337. }, null, this.format, this._extension);
  30338. proxy._swapAndDie(this);
  30339. return;
  30340. case InternalTexture.DATASOURCE_CUBERAW:
  30341. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30342. proxy._swapAndDie(this);
  30343. this.isReady = true;
  30344. return;
  30345. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  30346. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  30347. if (proxy) {
  30348. proxy._swapAndDie(_this);
  30349. }
  30350. _this.isReady = true;
  30351. }, null, this.format, this._extension);
  30352. proxy._sphericalPolynomial = this._sphericalPolynomial;
  30353. return;
  30354. }
  30355. };
  30356. InternalTexture.prototype._swapAndDie = function (target) {
  30357. target._webGLTexture = this._webGLTexture;
  30358. if (this._framebuffer) {
  30359. target._framebuffer = this._framebuffer;
  30360. }
  30361. if (this._depthStencilBuffer) {
  30362. target._depthStencilBuffer = this._depthStencilBuffer;
  30363. }
  30364. if (this._lodTextureHigh) {
  30365. if (target._lodTextureHigh) {
  30366. target._lodTextureHigh.dispose();
  30367. }
  30368. target._lodTextureHigh = this._lodTextureHigh;
  30369. }
  30370. if (this._lodTextureMid) {
  30371. if (target._lodTextureMid) {
  30372. target._lodTextureMid.dispose();
  30373. }
  30374. target._lodTextureMid = this._lodTextureMid;
  30375. }
  30376. if (this._lodTextureLow) {
  30377. if (target._lodTextureLow) {
  30378. target._lodTextureLow.dispose();
  30379. }
  30380. target._lodTextureLow = this._lodTextureLow;
  30381. }
  30382. var cache = this._engine.getLoadedTexturesCache();
  30383. var index = cache.indexOf(this);
  30384. if (index !== -1) {
  30385. cache.splice(index, 1);
  30386. }
  30387. };
  30388. /**
  30389. * Dispose the current allocated resources
  30390. */
  30391. InternalTexture.prototype.dispose = function () {
  30392. if (!this._webGLTexture) {
  30393. return;
  30394. }
  30395. this._references--;
  30396. if (this._references === 0) {
  30397. this._engine._releaseTexture(this);
  30398. this._webGLTexture = null;
  30399. this.previous = null;
  30400. this.next = null;
  30401. }
  30402. };
  30403. /**
  30404. * The source of the texture data is unknown
  30405. */
  30406. InternalTexture.DATASOURCE_UNKNOWN = 0;
  30407. /**
  30408. * Texture data comes from an URL
  30409. */
  30410. InternalTexture.DATASOURCE_URL = 1;
  30411. /**
  30412. * Texture data is only used for temporary storage
  30413. */
  30414. InternalTexture.DATASOURCE_TEMP = 2;
  30415. /**
  30416. * Texture data comes from raw data (ArrayBuffer)
  30417. */
  30418. InternalTexture.DATASOURCE_RAW = 3;
  30419. /**
  30420. * Texture content is dynamic (video or dynamic texture)
  30421. */
  30422. InternalTexture.DATASOURCE_DYNAMIC = 4;
  30423. /**
  30424. * Texture content is generated by rendering to it
  30425. */
  30426. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  30427. /**
  30428. * Texture content is part of a multi render target process
  30429. */
  30430. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  30431. /**
  30432. * Texture data comes from a cube data file
  30433. */
  30434. InternalTexture.DATASOURCE_CUBE = 7;
  30435. /**
  30436. * Texture data comes from a raw cube data
  30437. */
  30438. InternalTexture.DATASOURCE_CUBERAW = 8;
  30439. /**
  30440. * Texture data come from a prefiltered cube data file
  30441. */
  30442. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  30443. /**
  30444. * Texture content is raw 3D data
  30445. */
  30446. InternalTexture.DATASOURCE_RAW3D = 10;
  30447. /**
  30448. * Texture content is a depth texture
  30449. */
  30450. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  30451. return InternalTexture;
  30452. }());
  30453. BABYLON.InternalTexture = InternalTexture;
  30454. })(BABYLON || (BABYLON = {}));
  30455. //# sourceMappingURL=babylon.internalTexture.js.map
  30456. var BABYLON;
  30457. (function (BABYLON) {
  30458. var BaseTexture = /** @class */ (function () {
  30459. function BaseTexture(scene) {
  30460. this._hasAlpha = false;
  30461. this.getAlphaFromRGB = false;
  30462. this.level = 1;
  30463. this.coordinatesIndex = 0;
  30464. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  30465. /**
  30466. * | Value | Type | Description |
  30467. * | ----- | ------------------ | ----------- |
  30468. * | 0 | CLAMP_ADDRESSMODE | |
  30469. * | 1 | WRAP_ADDRESSMODE | |
  30470. * | 2 | MIRROR_ADDRESSMODE | |
  30471. */
  30472. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  30473. /**
  30474. * | Value | Type | Description |
  30475. * | ----- | ------------------ | ----------- |
  30476. * | 0 | CLAMP_ADDRESSMODE | |
  30477. * | 1 | WRAP_ADDRESSMODE | |
  30478. * | 2 | MIRROR_ADDRESSMODE | |
  30479. */
  30480. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  30481. /**
  30482. * | Value | Type | Description |
  30483. * | ----- | ------------------ | ----------- |
  30484. * | 0 | CLAMP_ADDRESSMODE | |
  30485. * | 1 | WRAP_ADDRESSMODE | |
  30486. * | 2 | MIRROR_ADDRESSMODE | |
  30487. */
  30488. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  30489. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  30490. this.isCube = false;
  30491. this.is3D = false;
  30492. this.gammaSpace = true;
  30493. this.invertZ = false;
  30494. this.lodLevelInAlpha = false;
  30495. this.isRenderTarget = false;
  30496. this.animations = new Array();
  30497. /**
  30498. * An event triggered when the texture is disposed.
  30499. */
  30500. this.onDisposeObservable = new BABYLON.Observable();
  30501. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30502. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  30503. if (this._scene) {
  30504. this._scene.textures.push(this);
  30505. }
  30506. this._uid = null;
  30507. }
  30508. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  30509. get: function () {
  30510. return this._hasAlpha;
  30511. },
  30512. set: function (value) {
  30513. if (this._hasAlpha === value) {
  30514. return;
  30515. }
  30516. this._hasAlpha = value;
  30517. if (this._scene) {
  30518. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  30519. }
  30520. },
  30521. enumerable: true,
  30522. configurable: true
  30523. });
  30524. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  30525. get: function () {
  30526. return this._coordinatesMode;
  30527. },
  30528. /**
  30529. * How a texture is mapped.
  30530. *
  30531. * | Value | Type | Description |
  30532. * | ----- | ----------------------------------- | ----------- |
  30533. * | 0 | EXPLICIT_MODE | |
  30534. * | 1 | SPHERICAL_MODE | |
  30535. * | 2 | PLANAR_MODE | |
  30536. * | 3 | CUBIC_MODE | |
  30537. * | 4 | PROJECTION_MODE | |
  30538. * | 5 | SKYBOX_MODE | |
  30539. * | 6 | INVCUBIC_MODE | |
  30540. * | 7 | EQUIRECTANGULAR_MODE | |
  30541. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  30542. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  30543. */
  30544. set: function (value) {
  30545. if (this._coordinatesMode === value) {
  30546. return;
  30547. }
  30548. this._coordinatesMode = value;
  30549. if (this._scene) {
  30550. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30551. }
  30552. },
  30553. enumerable: true,
  30554. configurable: true
  30555. });
  30556. Object.defineProperty(BaseTexture.prototype, "isRGBD", {
  30557. /**
  30558. * Gets whether or not the texture contains RGBD data.
  30559. */
  30560. get: function () {
  30561. return this._texture != null && this._texture._isRGBD;
  30562. },
  30563. enumerable: true,
  30564. configurable: true
  30565. });
  30566. Object.defineProperty(BaseTexture.prototype, "lodGenerationOffset", {
  30567. get: function () {
  30568. if (this._texture)
  30569. return this._texture._lodGenerationOffset;
  30570. return 0.0;
  30571. },
  30572. set: function (value) {
  30573. if (this._texture)
  30574. this._texture._lodGenerationOffset = value;
  30575. },
  30576. enumerable: true,
  30577. configurable: true
  30578. });
  30579. Object.defineProperty(BaseTexture.prototype, "lodGenerationScale", {
  30580. get: function () {
  30581. if (this._texture)
  30582. return this._texture._lodGenerationScale;
  30583. return 0.0;
  30584. },
  30585. set: function (value) {
  30586. if (this._texture)
  30587. this._texture._lodGenerationScale = value;
  30588. },
  30589. enumerable: true,
  30590. configurable: true
  30591. });
  30592. Object.defineProperty(BaseTexture.prototype, "uid", {
  30593. get: function () {
  30594. if (!this._uid) {
  30595. this._uid = BABYLON.Tools.RandomId();
  30596. }
  30597. return this._uid;
  30598. },
  30599. enumerable: true,
  30600. configurable: true
  30601. });
  30602. BaseTexture.prototype.toString = function () {
  30603. return this.name;
  30604. };
  30605. BaseTexture.prototype.getClassName = function () {
  30606. return "BaseTexture";
  30607. };
  30608. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  30609. set: function (callback) {
  30610. if (this._onDisposeObserver) {
  30611. this.onDisposeObservable.remove(this._onDisposeObserver);
  30612. }
  30613. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  30614. },
  30615. enumerable: true,
  30616. configurable: true
  30617. });
  30618. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  30619. get: function () {
  30620. return true;
  30621. },
  30622. enumerable: true,
  30623. configurable: true
  30624. });
  30625. BaseTexture.prototype.getScene = function () {
  30626. return this._scene;
  30627. };
  30628. BaseTexture.prototype.getTextureMatrix = function () {
  30629. return BABYLON.Matrix.IdentityReadOnly;
  30630. };
  30631. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  30632. return BABYLON.Matrix.IdentityReadOnly;
  30633. };
  30634. BaseTexture.prototype.getInternalTexture = function () {
  30635. return this._texture;
  30636. };
  30637. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  30638. return !this.isBlocking || this.isReady();
  30639. };
  30640. BaseTexture.prototype.isReady = function () {
  30641. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30642. this.delayLoad();
  30643. return false;
  30644. }
  30645. if (this._texture) {
  30646. return this._texture.isReady;
  30647. }
  30648. return false;
  30649. };
  30650. BaseTexture.prototype.getSize = function () {
  30651. if (this._texture && this._texture.width) {
  30652. return new BABYLON.Size(this._texture.width, this._texture.height);
  30653. }
  30654. if (this._texture && this._texture._size) {
  30655. return new BABYLON.Size(this._texture._size, this._texture._size);
  30656. }
  30657. return BABYLON.Size.Zero();
  30658. };
  30659. BaseTexture.prototype.getBaseSize = function () {
  30660. if (!this.isReady() || !this._texture)
  30661. return BABYLON.Size.Zero();
  30662. if (this._texture._size) {
  30663. return new BABYLON.Size(this._texture._size, this._texture._size);
  30664. }
  30665. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  30666. };
  30667. BaseTexture.prototype.scale = function (ratio) {
  30668. };
  30669. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  30670. get: function () {
  30671. return false;
  30672. },
  30673. enumerable: true,
  30674. configurable: true
  30675. });
  30676. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  30677. if (!this._scene) {
  30678. return null;
  30679. }
  30680. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  30681. for (var index = 0; index < texturesCache.length; index++) {
  30682. var texturesCacheEntry = texturesCache[index];
  30683. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  30684. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  30685. texturesCacheEntry.incrementReferences();
  30686. return texturesCacheEntry;
  30687. }
  30688. }
  30689. }
  30690. return null;
  30691. };
  30692. BaseTexture.prototype._rebuild = function () {
  30693. };
  30694. BaseTexture.prototype.delayLoad = function () {
  30695. };
  30696. BaseTexture.prototype.clone = function () {
  30697. return null;
  30698. };
  30699. Object.defineProperty(BaseTexture.prototype, "textureType", {
  30700. get: function () {
  30701. if (!this._texture) {
  30702. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30703. }
  30704. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30705. },
  30706. enumerable: true,
  30707. configurable: true
  30708. });
  30709. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  30710. get: function () {
  30711. if (!this._texture) {
  30712. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30713. }
  30714. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30715. },
  30716. enumerable: true,
  30717. configurable: true
  30718. });
  30719. /**
  30720. * Reads the pixels stored in the webgl texture and returns them as an ArrayBuffer.
  30721. * This will returns an RGBA array buffer containing either in values (0-255) or
  30722. * float values (0-1) depending of the underlying buffer type.
  30723. * @param faceIndex The face of the texture to read (in case of cube texture)
  30724. * @param level The LOD level of the texture to read (in case of Mip Maps)
  30725. * @returns The Array buffer containing the pixels data.
  30726. */
  30727. BaseTexture.prototype.readPixels = function (faceIndex, level) {
  30728. if (faceIndex === void 0) { faceIndex = 0; }
  30729. if (level === void 0) { level = 0; }
  30730. if (!this._texture) {
  30731. return null;
  30732. }
  30733. var size = this.getSize();
  30734. var width = size.width;
  30735. var height = size.height;
  30736. var scene = this.getScene();
  30737. if (!scene) {
  30738. return null;
  30739. }
  30740. var engine = scene.getEngine();
  30741. if (level != 0) {
  30742. width = width / Math.pow(2, level);
  30743. height = height / Math.pow(2, level);
  30744. width = Math.round(width);
  30745. height = Math.round(height);
  30746. }
  30747. if (this._texture.isCube) {
  30748. return engine._readTexturePixels(this._texture, width, height, faceIndex, level);
  30749. }
  30750. return engine._readTexturePixels(this._texture, width, height, -1, level);
  30751. };
  30752. BaseTexture.prototype.releaseInternalTexture = function () {
  30753. if (this._texture) {
  30754. this._texture.dispose();
  30755. this._texture = null;
  30756. }
  30757. };
  30758. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  30759. get: function () {
  30760. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  30761. return null;
  30762. }
  30763. if (!this._texture._sphericalPolynomial) {
  30764. this._texture._sphericalPolynomial =
  30765. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  30766. }
  30767. return this._texture._sphericalPolynomial;
  30768. },
  30769. set: function (value) {
  30770. if (this._texture) {
  30771. this._texture._sphericalPolynomial = value;
  30772. }
  30773. },
  30774. enumerable: true,
  30775. configurable: true
  30776. });
  30777. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  30778. get: function () {
  30779. if (this._texture) {
  30780. return this._texture._lodTextureHigh;
  30781. }
  30782. return null;
  30783. },
  30784. enumerable: true,
  30785. configurable: true
  30786. });
  30787. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  30788. get: function () {
  30789. if (this._texture) {
  30790. return this._texture._lodTextureMid;
  30791. }
  30792. return null;
  30793. },
  30794. enumerable: true,
  30795. configurable: true
  30796. });
  30797. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  30798. get: function () {
  30799. if (this._texture) {
  30800. return this._texture._lodTextureLow;
  30801. }
  30802. return null;
  30803. },
  30804. enumerable: true,
  30805. configurable: true
  30806. });
  30807. BaseTexture.prototype.dispose = function () {
  30808. if (!this._scene) {
  30809. return;
  30810. }
  30811. // Animations
  30812. this._scene.stopAnimation(this);
  30813. // Remove from scene
  30814. this._scene._removePendingData(this);
  30815. var index = this._scene.textures.indexOf(this);
  30816. if (index >= 0) {
  30817. this._scene.textures.splice(index, 1);
  30818. }
  30819. if (this._texture === undefined) {
  30820. return;
  30821. }
  30822. // Release
  30823. this.releaseInternalTexture();
  30824. // Callback
  30825. this.onDisposeObservable.notifyObservers(this);
  30826. this.onDisposeObservable.clear();
  30827. };
  30828. BaseTexture.prototype.serialize = function () {
  30829. if (!this.name) {
  30830. return null;
  30831. }
  30832. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  30833. // Animations
  30834. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  30835. return serializationObject;
  30836. };
  30837. BaseTexture.WhenAllReady = function (textures, callback) {
  30838. var numRemaining = textures.length;
  30839. if (numRemaining === 0) {
  30840. callback();
  30841. return;
  30842. }
  30843. var _loop_1 = function () {
  30844. texture = textures[i];
  30845. if (texture.isReady()) {
  30846. if (--numRemaining === 0) {
  30847. callback();
  30848. }
  30849. }
  30850. else {
  30851. onLoadObservable = texture.onLoadObservable;
  30852. var onLoadCallback_1 = function () {
  30853. onLoadObservable.removeCallback(onLoadCallback_1);
  30854. if (--numRemaining === 0) {
  30855. callback();
  30856. }
  30857. };
  30858. onLoadObservable.add(onLoadCallback_1);
  30859. }
  30860. };
  30861. var texture, onLoadObservable;
  30862. for (var i = 0; i < textures.length; i++) {
  30863. _loop_1();
  30864. }
  30865. };
  30866. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  30867. __decorate([
  30868. BABYLON.serialize()
  30869. ], BaseTexture.prototype, "name", void 0);
  30870. __decorate([
  30871. BABYLON.serialize("hasAlpha")
  30872. ], BaseTexture.prototype, "_hasAlpha", void 0);
  30873. __decorate([
  30874. BABYLON.serialize()
  30875. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  30876. __decorate([
  30877. BABYLON.serialize()
  30878. ], BaseTexture.prototype, "level", void 0);
  30879. __decorate([
  30880. BABYLON.serialize()
  30881. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  30882. __decorate([
  30883. BABYLON.serialize("coordinatesMode")
  30884. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  30885. __decorate([
  30886. BABYLON.serialize()
  30887. ], BaseTexture.prototype, "wrapU", void 0);
  30888. __decorate([
  30889. BABYLON.serialize()
  30890. ], BaseTexture.prototype, "wrapV", void 0);
  30891. __decorate([
  30892. BABYLON.serialize()
  30893. ], BaseTexture.prototype, "wrapR", void 0);
  30894. __decorate([
  30895. BABYLON.serialize()
  30896. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  30897. __decorate([
  30898. BABYLON.serialize()
  30899. ], BaseTexture.prototype, "isCube", void 0);
  30900. __decorate([
  30901. BABYLON.serialize()
  30902. ], BaseTexture.prototype, "is3D", void 0);
  30903. __decorate([
  30904. BABYLON.serialize()
  30905. ], BaseTexture.prototype, "gammaSpace", void 0);
  30906. __decorate([
  30907. BABYLON.serialize()
  30908. ], BaseTexture.prototype, "invertZ", void 0);
  30909. __decorate([
  30910. BABYLON.serialize()
  30911. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  30912. __decorate([
  30913. BABYLON.serialize()
  30914. ], BaseTexture.prototype, "lodGenerationOffset", null);
  30915. __decorate([
  30916. BABYLON.serialize()
  30917. ], BaseTexture.prototype, "lodGenerationScale", null);
  30918. __decorate([
  30919. BABYLON.serialize()
  30920. ], BaseTexture.prototype, "isRenderTarget", void 0);
  30921. return BaseTexture;
  30922. }());
  30923. BABYLON.BaseTexture = BaseTexture;
  30924. })(BABYLON || (BABYLON = {}));
  30925. //# sourceMappingURL=babylon.baseTexture.js.map
  30926. var BABYLON;
  30927. (function (BABYLON) {
  30928. var Texture = /** @class */ (function (_super) {
  30929. __extends(Texture, _super);
  30930. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  30931. if (noMipmap === void 0) { noMipmap = false; }
  30932. if (invertY === void 0) { invertY = true; }
  30933. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30934. if (onLoad === void 0) { onLoad = null; }
  30935. if (onError === void 0) { onError = null; }
  30936. if (buffer === void 0) { buffer = null; }
  30937. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30938. var _this = _super.call(this, scene) || this;
  30939. _this.uOffset = 0;
  30940. _this.vOffset = 0;
  30941. _this.uScale = 1.0;
  30942. _this.vScale = 1.0;
  30943. _this.uAng = 0;
  30944. _this.vAng = 0;
  30945. _this.wAng = 0;
  30946. /**
  30947. * Defines the center of rotation (U)
  30948. */
  30949. _this.uRotationCenter = 0.5;
  30950. /**
  30951. * Defines the center of rotation (V)
  30952. */
  30953. _this.vRotationCenter = 0.5;
  30954. /**
  30955. * Defines the center of rotation (W)
  30956. */
  30957. _this.wRotationCenter = 0.5;
  30958. _this._isBlocking = true;
  30959. _this.name = url || "";
  30960. _this.url = url;
  30961. _this._noMipmap = noMipmap;
  30962. _this._invertY = invertY;
  30963. _this._samplingMode = samplingMode;
  30964. _this._buffer = buffer;
  30965. _this._deleteBuffer = deleteBuffer;
  30966. if (format) {
  30967. _this._format = format;
  30968. }
  30969. scene = _this.getScene();
  30970. if (!scene) {
  30971. return _this;
  30972. }
  30973. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  30974. var load = function () {
  30975. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  30976. _this.onLoadObservable.notifyObservers(_this);
  30977. }
  30978. if (onLoad) {
  30979. onLoad();
  30980. }
  30981. if (!_this.isBlocking && scene) {
  30982. scene.resetCachedMaterial();
  30983. }
  30984. };
  30985. if (!_this.url) {
  30986. _this._delayedOnLoad = load;
  30987. _this._delayedOnError = onError;
  30988. return _this;
  30989. }
  30990. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  30991. if (!_this._texture) {
  30992. if (!scene.useDelayedTextureLoading) {
  30993. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  30994. if (deleteBuffer) {
  30995. delete _this._buffer;
  30996. }
  30997. }
  30998. else {
  30999. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  31000. _this._delayedOnLoad = load;
  31001. _this._delayedOnError = onError;
  31002. }
  31003. }
  31004. else {
  31005. if (_this._texture.isReady) {
  31006. BABYLON.Tools.SetImmediate(function () { return load(); });
  31007. }
  31008. else {
  31009. _this._texture.onLoadedObservable.add(load);
  31010. }
  31011. }
  31012. return _this;
  31013. }
  31014. Object.defineProperty(Texture.prototype, "noMipmap", {
  31015. get: function () {
  31016. return this._noMipmap;
  31017. },
  31018. enumerable: true,
  31019. configurable: true
  31020. });
  31021. Object.defineProperty(Texture.prototype, "isBlocking", {
  31022. get: function () {
  31023. return this._isBlocking;
  31024. },
  31025. set: function (value) {
  31026. this._isBlocking = value;
  31027. },
  31028. enumerable: true,
  31029. configurable: true
  31030. });
  31031. Object.defineProperty(Texture.prototype, "samplingMode", {
  31032. get: function () {
  31033. return this._samplingMode;
  31034. },
  31035. enumerable: true,
  31036. configurable: true
  31037. });
  31038. /**
  31039. * Update the url (and optional buffer) of this texture if url was null during construction.
  31040. * @param url the url of the texture
  31041. * @param buffer the buffer of the texture (defaults to null)
  31042. */
  31043. Texture.prototype.updateURL = function (url, buffer) {
  31044. if (buffer === void 0) { buffer = null; }
  31045. if (this.url) {
  31046. throw new Error("URL is already set");
  31047. }
  31048. this.url = url;
  31049. this._buffer = buffer;
  31050. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  31051. this.delayLoad();
  31052. };
  31053. Texture.prototype.delayLoad = function () {
  31054. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  31055. return;
  31056. }
  31057. var scene = this.getScene();
  31058. if (!scene) {
  31059. return;
  31060. }
  31061. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  31062. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  31063. if (!this._texture) {
  31064. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  31065. if (this._deleteBuffer) {
  31066. delete this._buffer;
  31067. }
  31068. }
  31069. else {
  31070. if (this._delayedOnLoad) {
  31071. if (this._texture.isReady) {
  31072. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  31073. }
  31074. else {
  31075. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  31076. }
  31077. }
  31078. }
  31079. this._delayedOnLoad = null;
  31080. this._delayedOnError = null;
  31081. };
  31082. Texture.prototype.updateSamplingMode = function (samplingMode) {
  31083. if (!this._texture) {
  31084. return;
  31085. }
  31086. var scene = this.getScene();
  31087. if (!scene) {
  31088. return;
  31089. }
  31090. this._samplingMode = samplingMode;
  31091. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  31092. };
  31093. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  31094. x *= this.uScale;
  31095. y *= this.vScale;
  31096. x -= this.uRotationCenter * this.uScale;
  31097. y -= this.vRotationCenter * this.vScale;
  31098. z -= this.wRotationCenter;
  31099. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  31100. t.x += this.uRotationCenter * this.uScale + this.uOffset;
  31101. t.y += this.vRotationCenter * this.vScale + this.vOffset;
  31102. t.z += this.wRotationCenter;
  31103. };
  31104. Texture.prototype.getTextureMatrix = function () {
  31105. var _this = this;
  31106. if (this.uOffset === this._cachedUOffset &&
  31107. this.vOffset === this._cachedVOffset &&
  31108. this.uScale === this._cachedUScale &&
  31109. this.vScale === this._cachedVScale &&
  31110. this.uAng === this._cachedUAng &&
  31111. this.vAng === this._cachedVAng &&
  31112. this.wAng === this._cachedWAng) {
  31113. return this._cachedTextureMatrix;
  31114. }
  31115. this._cachedUOffset = this.uOffset;
  31116. this._cachedVOffset = this.vOffset;
  31117. this._cachedUScale = this.uScale;
  31118. this._cachedVScale = this.vScale;
  31119. this._cachedUAng = this.uAng;
  31120. this._cachedVAng = this.vAng;
  31121. this._cachedWAng = this.wAng;
  31122. if (!this._cachedTextureMatrix) {
  31123. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  31124. this._rowGenerationMatrix = new BABYLON.Matrix();
  31125. this._t0 = BABYLON.Vector3.Zero();
  31126. this._t1 = BABYLON.Vector3.Zero();
  31127. this._t2 = BABYLON.Vector3.Zero();
  31128. }
  31129. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  31130. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  31131. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  31132. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  31133. this._t1.subtractInPlace(this._t0);
  31134. this._t2.subtractInPlace(this._t0);
  31135. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31136. this._cachedTextureMatrix.m[0] = this._t1.x;
  31137. this._cachedTextureMatrix.m[1] = this._t1.y;
  31138. this._cachedTextureMatrix.m[2] = this._t1.z;
  31139. this._cachedTextureMatrix.m[4] = this._t2.x;
  31140. this._cachedTextureMatrix.m[5] = this._t2.y;
  31141. this._cachedTextureMatrix.m[6] = this._t2.z;
  31142. this._cachedTextureMatrix.m[8] = this._t0.x;
  31143. this._cachedTextureMatrix.m[9] = this._t0.y;
  31144. this._cachedTextureMatrix.m[10] = this._t0.z;
  31145. var scene = this.getScene();
  31146. if (!scene) {
  31147. return this._cachedTextureMatrix;
  31148. }
  31149. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  31150. return mat.hasTexture(_this);
  31151. });
  31152. return this._cachedTextureMatrix;
  31153. };
  31154. Texture.prototype.getReflectionTextureMatrix = function () {
  31155. var _this = this;
  31156. var scene = this.getScene();
  31157. if (!scene) {
  31158. return this._cachedTextureMatrix;
  31159. }
  31160. if (this.uOffset === this._cachedUOffset &&
  31161. this.vOffset === this._cachedVOffset &&
  31162. this.uScale === this._cachedUScale &&
  31163. this.vScale === this._cachedVScale &&
  31164. this.coordinatesMode === this._cachedCoordinatesMode) {
  31165. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  31166. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  31167. return this._cachedTextureMatrix;
  31168. }
  31169. }
  31170. else {
  31171. return this._cachedTextureMatrix;
  31172. }
  31173. }
  31174. if (!this._cachedTextureMatrix) {
  31175. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  31176. }
  31177. if (!this._projectionModeMatrix) {
  31178. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  31179. }
  31180. this._cachedUOffset = this.uOffset;
  31181. this._cachedVOffset = this.vOffset;
  31182. this._cachedUScale = this.uScale;
  31183. this._cachedVScale = this.vScale;
  31184. this._cachedCoordinatesMode = this.coordinatesMode;
  31185. switch (this.coordinatesMode) {
  31186. case Texture.PLANAR_MODE:
  31187. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31188. this._cachedTextureMatrix[0] = this.uScale;
  31189. this._cachedTextureMatrix[5] = this.vScale;
  31190. this._cachedTextureMatrix[12] = this.uOffset;
  31191. this._cachedTextureMatrix[13] = this.vOffset;
  31192. break;
  31193. case Texture.PROJECTION_MODE:
  31194. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  31195. this._projectionModeMatrix.m[0] = 0.5;
  31196. this._projectionModeMatrix.m[5] = -0.5;
  31197. this._projectionModeMatrix.m[10] = 0.0;
  31198. this._projectionModeMatrix.m[12] = 0.5;
  31199. this._projectionModeMatrix.m[13] = 0.5;
  31200. this._projectionModeMatrix.m[14] = 1.0;
  31201. this._projectionModeMatrix.m[15] = 1.0;
  31202. var projectionMatrix = scene.getProjectionMatrix();
  31203. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  31204. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  31205. break;
  31206. default:
  31207. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31208. break;
  31209. }
  31210. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  31211. return (mat.getActiveTextures().indexOf(_this) !== -1);
  31212. });
  31213. return this._cachedTextureMatrix;
  31214. };
  31215. Texture.prototype.clone = function () {
  31216. var _this = this;
  31217. return BABYLON.SerializationHelper.Clone(function () {
  31218. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  31219. }, this);
  31220. };
  31221. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  31222. get: function () {
  31223. if (!this._onLoadObservable) {
  31224. this._onLoadObservable = new BABYLON.Observable();
  31225. }
  31226. return this._onLoadObservable;
  31227. },
  31228. enumerable: true,
  31229. configurable: true
  31230. });
  31231. Texture.prototype.serialize = function () {
  31232. var serializationObject = _super.prototype.serialize.call(this);
  31233. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  31234. serializationObject.base64String = this._buffer;
  31235. serializationObject.name = serializationObject.name.replace("data:", "");
  31236. }
  31237. serializationObject.invertY = this._invertY;
  31238. serializationObject.samplingMode = this.samplingMode;
  31239. return serializationObject;
  31240. };
  31241. Texture.prototype.getClassName = function () {
  31242. return "Texture";
  31243. };
  31244. Texture.prototype.dispose = function () {
  31245. _super.prototype.dispose.call(this);
  31246. if (this.onLoadObservable) {
  31247. this.onLoadObservable.clear();
  31248. this._onLoadObservable = null;
  31249. }
  31250. this._delayedOnLoad = null;
  31251. this._delayedOnError = null;
  31252. };
  31253. // Statics
  31254. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  31255. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  31256. if (onLoad === void 0) { onLoad = null; }
  31257. if (onError === void 0) { onError = null; }
  31258. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  31259. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  31260. };
  31261. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  31262. if (parsedTexture.customType) {
  31263. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  31264. // Update Sampling Mode
  31265. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  31266. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  31267. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  31268. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  31269. }
  31270. }
  31271. return parsedCustomTexture;
  31272. }
  31273. if (parsedTexture.isCube) {
  31274. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  31275. }
  31276. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  31277. return null;
  31278. }
  31279. var texture = BABYLON.SerializationHelper.Parse(function () {
  31280. var generateMipMaps = true;
  31281. if (parsedTexture.noMipmap) {
  31282. generateMipMaps = false;
  31283. }
  31284. if (parsedTexture.mirrorPlane) {
  31285. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  31286. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  31287. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  31288. return mirrorTexture;
  31289. }
  31290. else if (parsedTexture.isRenderTarget) {
  31291. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  31292. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  31293. return renderTargetTexture;
  31294. }
  31295. else {
  31296. var texture;
  31297. if (parsedTexture.base64String) {
  31298. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  31299. }
  31300. else {
  31301. var url = rootUrl + parsedTexture.name;
  31302. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  31303. url = parsedTexture.url;
  31304. }
  31305. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  31306. }
  31307. return texture;
  31308. }
  31309. }, parsedTexture, scene);
  31310. // Update Sampling Mode
  31311. if (parsedTexture.samplingMode) {
  31312. var sampling = parsedTexture.samplingMode;
  31313. if (texture._samplingMode !== sampling) {
  31314. texture.updateSamplingMode(sampling);
  31315. }
  31316. }
  31317. // Animations
  31318. if (parsedTexture.animations) {
  31319. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  31320. var parsedAnimation = parsedTexture.animations[animationIndex];
  31321. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  31322. }
  31323. }
  31324. return texture;
  31325. };
  31326. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  31327. if (deleteBuffer === void 0) { deleteBuffer = false; }
  31328. if (noMipmap === void 0) { noMipmap = false; }
  31329. if (invertY === void 0) { invertY = true; }
  31330. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  31331. if (onLoad === void 0) { onLoad = null; }
  31332. if (onError === void 0) { onError = null; }
  31333. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  31334. if (name.substr(0, 5) !== "data:") {
  31335. name = "data:" + name;
  31336. }
  31337. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  31338. };
  31339. // Constants
  31340. Texture.NEAREST_SAMPLINGMODE = 1;
  31341. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  31342. Texture.BILINEAR_SAMPLINGMODE = 2;
  31343. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  31344. Texture.TRILINEAR_SAMPLINGMODE = 3;
  31345. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  31346. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  31347. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  31348. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  31349. Texture.NEAREST_LINEAR = 7;
  31350. Texture.NEAREST_NEAREST = 8;
  31351. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  31352. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  31353. Texture.LINEAR_LINEAR = 11;
  31354. Texture.LINEAR_NEAREST = 12;
  31355. Texture.EXPLICIT_MODE = 0;
  31356. Texture.SPHERICAL_MODE = 1;
  31357. Texture.PLANAR_MODE = 2;
  31358. Texture.CUBIC_MODE = 3;
  31359. Texture.PROJECTION_MODE = 4;
  31360. Texture.SKYBOX_MODE = 5;
  31361. Texture.INVCUBIC_MODE = 6;
  31362. Texture.EQUIRECTANGULAR_MODE = 7;
  31363. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  31364. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  31365. Texture.CLAMP_ADDRESSMODE = 0;
  31366. Texture.WRAP_ADDRESSMODE = 1;
  31367. Texture.MIRROR_ADDRESSMODE = 2;
  31368. /**
  31369. * 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
  31370. */
  31371. Texture.UseSerializedUrlIfAny = false;
  31372. __decorate([
  31373. BABYLON.serialize()
  31374. ], Texture.prototype, "url", void 0);
  31375. __decorate([
  31376. BABYLON.serialize()
  31377. ], Texture.prototype, "uOffset", void 0);
  31378. __decorate([
  31379. BABYLON.serialize()
  31380. ], Texture.prototype, "vOffset", void 0);
  31381. __decorate([
  31382. BABYLON.serialize()
  31383. ], Texture.prototype, "uScale", void 0);
  31384. __decorate([
  31385. BABYLON.serialize()
  31386. ], Texture.prototype, "vScale", void 0);
  31387. __decorate([
  31388. BABYLON.serialize()
  31389. ], Texture.prototype, "uAng", void 0);
  31390. __decorate([
  31391. BABYLON.serialize()
  31392. ], Texture.prototype, "vAng", void 0);
  31393. __decorate([
  31394. BABYLON.serialize()
  31395. ], Texture.prototype, "wAng", void 0);
  31396. __decorate([
  31397. BABYLON.serialize()
  31398. ], Texture.prototype, "uRotationCenter", void 0);
  31399. __decorate([
  31400. BABYLON.serialize()
  31401. ], Texture.prototype, "vRotationCenter", void 0);
  31402. __decorate([
  31403. BABYLON.serialize()
  31404. ], Texture.prototype, "wRotationCenter", void 0);
  31405. __decorate([
  31406. BABYLON.serialize()
  31407. ], Texture.prototype, "isBlocking", null);
  31408. return Texture;
  31409. }(BABYLON.BaseTexture));
  31410. BABYLON.Texture = Texture;
  31411. })(BABYLON || (BABYLON = {}));
  31412. //# sourceMappingURL=babylon.texture.js.map
  31413. var BABYLON;
  31414. (function (BABYLON) {
  31415. /**
  31416. * @hidden
  31417. **/
  31418. var _InstancesBatch = /** @class */ (function () {
  31419. function _InstancesBatch() {
  31420. this.mustReturn = false;
  31421. this.visibleInstances = new Array();
  31422. this.renderSelf = new Array();
  31423. }
  31424. return _InstancesBatch;
  31425. }());
  31426. BABYLON._InstancesBatch = _InstancesBatch;
  31427. var Mesh = /** @class */ (function (_super) {
  31428. __extends(Mesh, _super);
  31429. /**
  31430. * @constructor
  31431. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  31432. * @param {Scene} scene The scene to add this mesh to.
  31433. * @param {Node} parent The parent of this mesh, if it has one
  31434. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  31435. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  31436. * When false, achieved by calling a clone(), also passing False.
  31437. * This will make creation of children, recursive.
  31438. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  31439. */
  31440. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  31441. if (scene === void 0) { scene = null; }
  31442. if (parent === void 0) { parent = null; }
  31443. if (source === void 0) { source = null; }
  31444. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  31445. var _this = _super.call(this, name, scene) || this;
  31446. // Events
  31447. /**
  31448. * An event triggered before rendering the mesh
  31449. */
  31450. _this.onBeforeRenderObservable = new BABYLON.Observable();
  31451. /**
  31452. * An event triggered after rendering the mesh
  31453. */
  31454. _this.onAfterRenderObservable = new BABYLON.Observable();
  31455. /**
  31456. * An event triggered before drawing the mesh
  31457. */
  31458. _this.onBeforeDrawObservable = new BABYLON.Observable();
  31459. // Members
  31460. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  31461. _this.instances = new Array();
  31462. _this._LODLevels = new Array();
  31463. _this._visibleInstances = {};
  31464. _this._renderIdForInstances = new Array();
  31465. _this._batchCache = new _InstancesBatch();
  31466. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  31467. // Use by builder only to know what orientation were the mesh build in.
  31468. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  31469. _this.overrideMaterialSideOrientation = null;
  31470. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  31471. // Will be used to save a source mesh reference, If any
  31472. _this._source = null;
  31473. scene = _this.getScene();
  31474. if (source) {
  31475. // Geometry
  31476. if (source._geometry) {
  31477. source._geometry.applyToMesh(_this);
  31478. }
  31479. // Deep copy
  31480. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  31481. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen"], ["_poseMatrix"]);
  31482. // Source mesh
  31483. _this._source = source;
  31484. // Metadata
  31485. if (source.metadata && source.metadata.clone) {
  31486. _this.metadata = source.metadata.clone();
  31487. }
  31488. else {
  31489. _this.metadata = source.metadata;
  31490. }
  31491. // Tags
  31492. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  31493. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  31494. }
  31495. // Parent
  31496. _this.parent = source.parent;
  31497. // Pivot
  31498. _this.setPivotMatrix(source.getPivotMatrix());
  31499. _this.id = name + "." + source.id;
  31500. // Material
  31501. _this.material = source.material;
  31502. var index;
  31503. if (!doNotCloneChildren) {
  31504. // Children
  31505. var directDescendants = source.getDescendants(true);
  31506. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  31507. var child = directDescendants[index_1];
  31508. if (child.clone) {
  31509. child.clone(name + "." + child.name, _this);
  31510. }
  31511. }
  31512. }
  31513. // Physics clone
  31514. var physicsEngine = _this.getScene().getPhysicsEngine();
  31515. if (clonePhysicsImpostor && physicsEngine) {
  31516. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  31517. if (impostor) {
  31518. _this.physicsImpostor = impostor.clone(_this);
  31519. }
  31520. }
  31521. // Particles
  31522. for (index = 0; index < scene.particleSystems.length; index++) {
  31523. var system = scene.particleSystems[index];
  31524. if (system.emitter === source) {
  31525. system.clone(system.name, _this);
  31526. }
  31527. }
  31528. _this.computeWorldMatrix(true);
  31529. }
  31530. // Parent
  31531. if (parent !== null) {
  31532. _this.parent = parent;
  31533. }
  31534. return _this;
  31535. }
  31536. Object.defineProperty(Mesh, "FRONTSIDE", {
  31537. /**
  31538. * Mesh side orientation : usually the external or front surface
  31539. */
  31540. get: function () {
  31541. return Mesh._FRONTSIDE;
  31542. },
  31543. enumerable: true,
  31544. configurable: true
  31545. });
  31546. Object.defineProperty(Mesh, "BACKSIDE", {
  31547. /**
  31548. * Mesh side orientation : usually the internal or back surface
  31549. */
  31550. get: function () {
  31551. return Mesh._BACKSIDE;
  31552. },
  31553. enumerable: true,
  31554. configurable: true
  31555. });
  31556. Object.defineProperty(Mesh, "DOUBLESIDE", {
  31557. /**
  31558. * Mesh side orientation : both internal and external or front and back surfaces
  31559. */
  31560. get: function () {
  31561. return Mesh._DOUBLESIDE;
  31562. },
  31563. enumerable: true,
  31564. configurable: true
  31565. });
  31566. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  31567. /**
  31568. * Mesh side orientation : by default, `FRONTSIDE`
  31569. */
  31570. get: function () {
  31571. return Mesh._DEFAULTSIDE;
  31572. },
  31573. enumerable: true,
  31574. configurable: true
  31575. });
  31576. Object.defineProperty(Mesh, "NO_CAP", {
  31577. /**
  31578. * Mesh cap setting : no cap
  31579. */
  31580. get: function () {
  31581. return Mesh._NO_CAP;
  31582. },
  31583. enumerable: true,
  31584. configurable: true
  31585. });
  31586. Object.defineProperty(Mesh, "CAP_START", {
  31587. /**
  31588. * Mesh cap setting : one cap at the beginning of the mesh
  31589. */
  31590. get: function () {
  31591. return Mesh._CAP_START;
  31592. },
  31593. enumerable: true,
  31594. configurable: true
  31595. });
  31596. Object.defineProperty(Mesh, "CAP_END", {
  31597. /**
  31598. * Mesh cap setting : one cap at the end of the mesh
  31599. */
  31600. get: function () {
  31601. return Mesh._CAP_END;
  31602. },
  31603. enumerable: true,
  31604. configurable: true
  31605. });
  31606. Object.defineProperty(Mesh, "CAP_ALL", {
  31607. /**
  31608. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  31609. */
  31610. get: function () {
  31611. return Mesh._CAP_ALL;
  31612. },
  31613. enumerable: true,
  31614. configurable: true
  31615. });
  31616. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  31617. set: function (callback) {
  31618. if (this._onBeforeDrawObserver) {
  31619. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  31620. }
  31621. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  31622. },
  31623. enumerable: true,
  31624. configurable: true
  31625. });
  31626. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  31627. get: function () {
  31628. return this._morphTargetManager;
  31629. },
  31630. set: function (value) {
  31631. if (this._morphTargetManager === value) {
  31632. return;
  31633. }
  31634. this._morphTargetManager = value;
  31635. this._syncGeometryWithMorphTargetManager();
  31636. },
  31637. enumerable: true,
  31638. configurable: true
  31639. });
  31640. Object.defineProperty(Mesh.prototype, "source", {
  31641. get: function () {
  31642. return this._source;
  31643. },
  31644. enumerable: true,
  31645. configurable: true
  31646. });
  31647. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  31648. get: function () {
  31649. return this._unIndexed;
  31650. },
  31651. set: function (value) {
  31652. if (this._unIndexed !== value) {
  31653. this._unIndexed = value;
  31654. this._markSubMeshesAsAttributesDirty();
  31655. }
  31656. },
  31657. enumerable: true,
  31658. configurable: true
  31659. });
  31660. // Methods
  31661. /**
  31662. * Returns the string "Mesh".
  31663. */
  31664. Mesh.prototype.getClassName = function () {
  31665. return "Mesh";
  31666. };
  31667. /**
  31668. * Returns a string.
  31669. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31670. */
  31671. Mesh.prototype.toString = function (fullDetails) {
  31672. var ret = _super.prototype.toString.call(this, fullDetails);
  31673. ret += ", n vertices: " + this.getTotalVertices();
  31674. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  31675. if (this.animations) {
  31676. for (var i = 0; i < this.animations.length; i++) {
  31677. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  31678. }
  31679. }
  31680. if (fullDetails) {
  31681. if (this._geometry) {
  31682. var ib = this.getIndices();
  31683. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31684. if (vb && ib) {
  31685. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  31686. }
  31687. }
  31688. else {
  31689. ret += ", flat shading: UNKNOWN";
  31690. }
  31691. }
  31692. return ret;
  31693. };
  31694. Mesh.prototype._unBindEffect = function () {
  31695. _super.prototype._unBindEffect.call(this);
  31696. for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {
  31697. var instance = _a[_i];
  31698. instance._unBindEffect();
  31699. }
  31700. };
  31701. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  31702. /**
  31703. * True if the mesh has some Levels Of Details (LOD).
  31704. * Returns a boolean.
  31705. */
  31706. get: function () {
  31707. return this._LODLevels.length > 0;
  31708. },
  31709. enumerable: true,
  31710. configurable: true
  31711. });
  31712. /**
  31713. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  31714. * @returns an array of {BABYLON.MeshLODLevel}
  31715. */
  31716. Mesh.prototype.getLODLevels = function () {
  31717. return this._LODLevels;
  31718. };
  31719. Mesh.prototype._sortLODLevels = function () {
  31720. this._LODLevels.sort(function (a, b) {
  31721. if (a.distance < b.distance) {
  31722. return 1;
  31723. }
  31724. if (a.distance > b.distance) {
  31725. return -1;
  31726. }
  31727. return 0;
  31728. });
  31729. };
  31730. /**
  31731. * Add a mesh as LOD level triggered at the given distance.
  31732. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31733. * @param distance The distance from the center of the object to show this level
  31734. * @param mesh The mesh to be added as LOD level (can be null)
  31735. * @return This mesh (for chaining)
  31736. */
  31737. Mesh.prototype.addLODLevel = function (distance, mesh) {
  31738. if (mesh && mesh._masterMesh) {
  31739. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  31740. return this;
  31741. }
  31742. var level = new BABYLON.MeshLODLevel(distance, mesh);
  31743. this._LODLevels.push(level);
  31744. if (mesh) {
  31745. mesh._masterMesh = this;
  31746. }
  31747. this._sortLODLevels();
  31748. return this;
  31749. };
  31750. /**
  31751. * Returns the LOD level mesh at the passed distance or null if not found.
  31752. * It is related to the method `addLODLevel(distance, mesh)`.
  31753. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31754. * Returns an object Mesh or `null`.
  31755. */
  31756. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  31757. for (var index = 0; index < this._LODLevels.length; index++) {
  31758. var level = this._LODLevels[index];
  31759. if (level.distance === distance) {
  31760. return level.mesh;
  31761. }
  31762. }
  31763. return null;
  31764. };
  31765. /**
  31766. * Remove a mesh from the LOD array
  31767. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31768. * @param {Mesh} mesh The mesh to be removed.
  31769. * @return {Mesh} This mesh (for chaining)
  31770. */
  31771. Mesh.prototype.removeLODLevel = function (mesh) {
  31772. for (var index = 0; index < this._LODLevels.length; index++) {
  31773. if (this._LODLevels[index].mesh === mesh) {
  31774. this._LODLevels.splice(index, 1);
  31775. if (mesh) {
  31776. mesh._masterMesh = null;
  31777. }
  31778. }
  31779. }
  31780. this._sortLODLevels();
  31781. return this;
  31782. };
  31783. /**
  31784. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  31785. * tuto : http://doc.babylonjs.com/how_to/how_to_use_lod
  31786. */
  31787. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  31788. if (!this._LODLevels || this._LODLevels.length === 0) {
  31789. return this;
  31790. }
  31791. var bSphere;
  31792. if (boundingSphere) {
  31793. bSphere = boundingSphere;
  31794. }
  31795. else {
  31796. var boundingInfo = this.getBoundingInfo();
  31797. bSphere = boundingInfo.boundingSphere;
  31798. }
  31799. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  31800. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  31801. if (this.onLODLevelSelection) {
  31802. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  31803. }
  31804. return this;
  31805. }
  31806. for (var index = 0; index < this._LODLevels.length; index++) {
  31807. var level = this._LODLevels[index];
  31808. if (level.distance < distanceToCamera) {
  31809. if (level.mesh) {
  31810. level.mesh._preActivate();
  31811. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  31812. }
  31813. if (this.onLODLevelSelection) {
  31814. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  31815. }
  31816. return level.mesh;
  31817. }
  31818. }
  31819. if (this.onLODLevelSelection) {
  31820. this.onLODLevelSelection(distanceToCamera, this, this);
  31821. }
  31822. return this;
  31823. };
  31824. Object.defineProperty(Mesh.prototype, "geometry", {
  31825. /**
  31826. * Returns the mesh internal Geometry object.
  31827. */
  31828. get: function () {
  31829. return this._geometry;
  31830. },
  31831. enumerable: true,
  31832. configurable: true
  31833. });
  31834. /**
  31835. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  31836. */
  31837. Mesh.prototype.getTotalVertices = function () {
  31838. if (this._geometry === null || this._geometry === undefined) {
  31839. return 0;
  31840. }
  31841. return this._geometry.getTotalVertices();
  31842. };
  31843. /**
  31844. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  31845. * 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.
  31846. * You can force the copy with forceCopy === true
  31847. * Returns null if the mesh has no geometry or no vertex buffer.
  31848. * Possible `kind` values :
  31849. * - BABYLON.VertexBuffer.PositionKind
  31850. * - BABYLON.VertexBuffer.UVKind
  31851. * - BABYLON.VertexBuffer.UV2Kind
  31852. * - BABYLON.VertexBuffer.UV3Kind
  31853. * - BABYLON.VertexBuffer.UV4Kind
  31854. * - BABYLON.VertexBuffer.UV5Kind
  31855. * - BABYLON.VertexBuffer.UV6Kind
  31856. * - BABYLON.VertexBuffer.ColorKind
  31857. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31858. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31859. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31860. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31861. */
  31862. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  31863. if (!this._geometry) {
  31864. return null;
  31865. }
  31866. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  31867. };
  31868. /**
  31869. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  31870. * Returns `null` if the mesh has no geometry.
  31871. * Possible `kind` values :
  31872. * - BABYLON.VertexBuffer.PositionKind
  31873. * - BABYLON.VertexBuffer.UVKind
  31874. * - BABYLON.VertexBuffer.UV2Kind
  31875. * - BABYLON.VertexBuffer.UV3Kind
  31876. * - BABYLON.VertexBuffer.UV4Kind
  31877. * - BABYLON.VertexBuffer.UV5Kind
  31878. * - BABYLON.VertexBuffer.UV6Kind
  31879. * - BABYLON.VertexBuffer.ColorKind
  31880. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31881. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31882. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31883. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31884. */
  31885. Mesh.prototype.getVertexBuffer = function (kind) {
  31886. if (!this._geometry) {
  31887. return null;
  31888. }
  31889. return this._geometry.getVertexBuffer(kind);
  31890. };
  31891. Mesh.prototype.isVerticesDataPresent = function (kind) {
  31892. if (!this._geometry) {
  31893. if (this._delayInfo) {
  31894. return this._delayInfo.indexOf(kind) !== -1;
  31895. }
  31896. return false;
  31897. }
  31898. return this._geometry.isVerticesDataPresent(kind);
  31899. };
  31900. /**
  31901. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  31902. * Possible `kind` values :
  31903. * - BABYLON.VertexBuffer.PositionKind
  31904. * - BABYLON.VertexBuffer.UVKind
  31905. * - BABYLON.VertexBuffer.UV2Kind
  31906. * - BABYLON.VertexBuffer.UV3Kind
  31907. * - BABYLON.VertexBuffer.UV4Kind
  31908. * - BABYLON.VertexBuffer.UV5Kind
  31909. * - BABYLON.VertexBuffer.UV6Kind
  31910. * - BABYLON.VertexBuffer.ColorKind
  31911. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31912. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31913. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31914. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31915. */
  31916. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  31917. if (!this._geometry) {
  31918. if (this._delayInfo) {
  31919. return this._delayInfo.indexOf(kind) !== -1;
  31920. }
  31921. return false;
  31922. }
  31923. return this._geometry.isVertexBufferUpdatable(kind);
  31924. };
  31925. /**
  31926. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  31927. * Possible `kind` values :
  31928. * - BABYLON.VertexBuffer.PositionKind
  31929. * - BABYLON.VertexBuffer.UVKind
  31930. * - BABYLON.VertexBuffer.UV2Kind
  31931. * - BABYLON.VertexBuffer.UV3Kind
  31932. * - BABYLON.VertexBuffer.UV4Kind
  31933. * - BABYLON.VertexBuffer.UV5Kind
  31934. * - BABYLON.VertexBuffer.UV6Kind
  31935. * - BABYLON.VertexBuffer.ColorKind
  31936. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31937. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31938. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31939. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31940. */
  31941. Mesh.prototype.getVerticesDataKinds = function () {
  31942. if (!this._geometry) {
  31943. var result = new Array();
  31944. if (this._delayInfo) {
  31945. this._delayInfo.forEach(function (kind, index, array) {
  31946. result.push(kind);
  31947. });
  31948. }
  31949. return result;
  31950. }
  31951. return this._geometry.getVerticesDataKinds();
  31952. };
  31953. /**
  31954. * Returns a positive integer : the total number of indices in this mesh geometry.
  31955. * Returns zero if the mesh has no geometry.
  31956. */
  31957. Mesh.prototype.getTotalIndices = function () {
  31958. if (!this._geometry) {
  31959. return 0;
  31960. }
  31961. return this._geometry.getTotalIndices();
  31962. };
  31963. /**
  31964. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  31965. * 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.
  31966. * Returns an empty array if the mesh has no geometry.
  31967. */
  31968. Mesh.prototype.getIndices = function (copyWhenShared) {
  31969. if (!this._geometry) {
  31970. return [];
  31971. }
  31972. return this._geometry.getIndices(copyWhenShared);
  31973. };
  31974. Object.defineProperty(Mesh.prototype, "isBlocked", {
  31975. get: function () {
  31976. return this._masterMesh !== null && this._masterMesh !== undefined;
  31977. },
  31978. enumerable: true,
  31979. configurable: true
  31980. });
  31981. /**
  31982. * Determine if the current mesh is ready to be rendered
  31983. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  31984. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  31985. * @returns true if all associated assets are ready (material, textures, shaders)
  31986. */
  31987. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  31988. if (completeCheck === void 0) { completeCheck = false; }
  31989. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  31990. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31991. return false;
  31992. }
  31993. if (!_super.prototype.isReady.call(this, completeCheck)) {
  31994. return false;
  31995. }
  31996. if (!this.subMeshes || this.subMeshes.length === 0) {
  31997. return true;
  31998. }
  31999. if (!completeCheck) {
  32000. return true;
  32001. }
  32002. var engine = this.getEngine();
  32003. var scene = this.getScene();
  32004. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  32005. this.computeWorldMatrix();
  32006. var mat = this.material || scene.defaultMaterial;
  32007. if (mat) {
  32008. if (mat.storeEffectOnSubMeshes) {
  32009. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  32010. var subMesh = _a[_i];
  32011. var effectiveMaterial = subMesh.getMaterial();
  32012. if (effectiveMaterial) {
  32013. if (effectiveMaterial.storeEffectOnSubMeshes) {
  32014. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  32015. return false;
  32016. }
  32017. }
  32018. else {
  32019. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  32020. return false;
  32021. }
  32022. }
  32023. }
  32024. }
  32025. }
  32026. else {
  32027. if (!mat.isReady(this, hardwareInstancedRendering)) {
  32028. return false;
  32029. }
  32030. }
  32031. }
  32032. // Shadows
  32033. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  32034. var light = _c[_b];
  32035. var generator = light.getShadowGenerator();
  32036. if (generator) {
  32037. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  32038. var subMesh = _e[_d];
  32039. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  32040. return false;
  32041. }
  32042. }
  32043. }
  32044. }
  32045. // LOD
  32046. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  32047. var lod = _g[_f];
  32048. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  32049. return false;
  32050. }
  32051. }
  32052. return true;
  32053. };
  32054. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  32055. /**
  32056. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  32057. * This property is pertinent only for updatable parametric shapes.
  32058. */
  32059. get: function () {
  32060. return this._areNormalsFrozen;
  32061. },
  32062. enumerable: true,
  32063. configurable: true
  32064. });
  32065. /**
  32066. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  32067. * It has no effect at all on other shapes.
  32068. * It prevents the mesh normals from being recomputed on next `positions` array update.
  32069. * Returns the Mesh.
  32070. */
  32071. Mesh.prototype.freezeNormals = function () {
  32072. this._areNormalsFrozen = true;
  32073. return this;
  32074. };
  32075. /**
  32076. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  32077. * It has no effect at all on other shapes.
  32078. * It reactivates the mesh normals computation if it was previously frozen.
  32079. * Returns the Mesh.
  32080. */
  32081. Mesh.prototype.unfreezeNormals = function () {
  32082. this._areNormalsFrozen = false;
  32083. return this;
  32084. };
  32085. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  32086. /**
  32087. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  32088. */
  32089. set: function (count) {
  32090. this._overridenInstanceCount = count;
  32091. },
  32092. enumerable: true,
  32093. configurable: true
  32094. });
  32095. // Methods
  32096. Mesh.prototype._preActivate = function () {
  32097. var sceneRenderId = this.getScene().getRenderId();
  32098. if (this._preActivateId === sceneRenderId) {
  32099. return this;
  32100. }
  32101. this._preActivateId = sceneRenderId;
  32102. this._visibleInstances = null;
  32103. return this;
  32104. };
  32105. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  32106. if (this._visibleInstances) {
  32107. this._visibleInstances.intermediateDefaultRenderId = renderId;
  32108. }
  32109. return this;
  32110. };
  32111. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  32112. if (!this._visibleInstances) {
  32113. this._visibleInstances = {};
  32114. this._visibleInstances.defaultRenderId = renderId;
  32115. this._visibleInstances.selfDefaultRenderId = this._renderId;
  32116. }
  32117. if (!this._visibleInstances[renderId]) {
  32118. this._visibleInstances[renderId] = new Array();
  32119. }
  32120. this._visibleInstances[renderId].push(instance);
  32121. return this;
  32122. };
  32123. /**
  32124. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  32125. * This means the mesh underlying bounding box and sphere are recomputed.
  32126. * Returns the Mesh.
  32127. */
  32128. Mesh.prototype.refreshBoundingInfo = function () {
  32129. return this._refreshBoundingInfo(false);
  32130. };
  32131. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  32132. if (this._boundingInfo && this._boundingInfo.isLocked) {
  32133. return this;
  32134. }
  32135. var data = this._getPositionData(applySkeleton);
  32136. if (data) {
  32137. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  32138. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  32139. }
  32140. if (this.subMeshes) {
  32141. for (var index = 0; index < this.subMeshes.length; index++) {
  32142. this.subMeshes[index].refreshBoundingInfo();
  32143. }
  32144. }
  32145. this._updateBoundingInfo();
  32146. return this;
  32147. };
  32148. Mesh.prototype._getPositionData = function (applySkeleton) {
  32149. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32150. if (data && applySkeleton && this.skeleton) {
  32151. data = BABYLON.Tools.Slice(data);
  32152. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32153. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32154. if (matricesWeightsData && matricesIndicesData) {
  32155. var needExtras = this.numBoneInfluencers > 4;
  32156. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  32157. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  32158. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  32159. var tempVector = BABYLON.Tmp.Vector3[0];
  32160. var finalMatrix = BABYLON.Tmp.Matrix[0];
  32161. var tempMatrix = BABYLON.Tmp.Matrix[1];
  32162. var matWeightIdx = 0;
  32163. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  32164. finalMatrix.reset();
  32165. var inf;
  32166. var weight;
  32167. for (inf = 0; inf < 4; inf++) {
  32168. weight = matricesWeightsData[matWeightIdx + inf];
  32169. if (weight <= 0)
  32170. break;
  32171. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  32172. finalMatrix.addToSelf(tempMatrix);
  32173. }
  32174. if (needExtras) {
  32175. for (inf = 0; inf < 4; inf++) {
  32176. weight = matricesWeightsExtraData[matWeightIdx + inf];
  32177. if (weight <= 0)
  32178. break;
  32179. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  32180. finalMatrix.addToSelf(tempMatrix);
  32181. }
  32182. }
  32183. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  32184. tempVector.toArray(data, index);
  32185. }
  32186. }
  32187. }
  32188. return data;
  32189. };
  32190. Mesh.prototype._createGlobalSubMesh = function (force) {
  32191. var totalVertices = this.getTotalVertices();
  32192. if (!totalVertices || !this.getIndices()) {
  32193. return null;
  32194. }
  32195. // Check if we need to recreate the submeshes
  32196. if (this.subMeshes && this.subMeshes.length > 0) {
  32197. var ib = this.getIndices();
  32198. if (!ib) {
  32199. return null;
  32200. }
  32201. var totalIndices = ib.length;
  32202. var needToRecreate = false;
  32203. if (force) {
  32204. needToRecreate = true;
  32205. }
  32206. else {
  32207. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  32208. var submesh = _a[_i];
  32209. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  32210. needToRecreate = true;
  32211. break;
  32212. }
  32213. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  32214. needToRecreate = true;
  32215. break;
  32216. }
  32217. }
  32218. }
  32219. if (!needToRecreate) {
  32220. return this.subMeshes[0];
  32221. }
  32222. }
  32223. this.releaseSubMeshes();
  32224. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  32225. };
  32226. Mesh.prototype.subdivide = function (count) {
  32227. if (count < 1) {
  32228. return;
  32229. }
  32230. var totalIndices = this.getTotalIndices();
  32231. var subdivisionSize = (totalIndices / count) | 0;
  32232. var offset = 0;
  32233. // Ensure that subdivisionSize is a multiple of 3
  32234. while (subdivisionSize % 3 !== 0) {
  32235. subdivisionSize++;
  32236. }
  32237. this.releaseSubMeshes();
  32238. for (var index = 0; index < count; index++) {
  32239. if (offset >= totalIndices) {
  32240. break;
  32241. }
  32242. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  32243. offset += subdivisionSize;
  32244. }
  32245. this.synchronizeInstances();
  32246. };
  32247. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  32248. if (updatable === void 0) { updatable = false; }
  32249. if (!this._geometry) {
  32250. var vertexData = new BABYLON.VertexData();
  32251. vertexData.set(data, kind);
  32252. var scene = this.getScene();
  32253. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  32254. }
  32255. else {
  32256. this._geometry.setVerticesData(kind, data, updatable, stride);
  32257. }
  32258. return this;
  32259. };
  32260. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  32261. if (updatable === void 0) { updatable = true; }
  32262. var vb = this.getVertexBuffer(kind);
  32263. if (!vb || vb.isUpdatable() === updatable) {
  32264. return;
  32265. }
  32266. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  32267. };
  32268. /**
  32269. * Sets the mesh VertexBuffer.
  32270. * Returns the Mesh.
  32271. */
  32272. Mesh.prototype.setVerticesBuffer = function (buffer) {
  32273. if (!this._geometry) {
  32274. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  32275. }
  32276. this._geometry.setVerticesBuffer(buffer);
  32277. return this;
  32278. };
  32279. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  32280. if (!this._geometry) {
  32281. return this;
  32282. }
  32283. if (!makeItUnique) {
  32284. this._geometry.updateVerticesData(kind, data, updateExtends);
  32285. }
  32286. else {
  32287. this.makeGeometryUnique();
  32288. this.updateVerticesData(kind, data, updateExtends, false);
  32289. }
  32290. return this;
  32291. };
  32292. /**
  32293. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  32294. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  32295. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  32296. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  32297. * Returns the Mesh.
  32298. */
  32299. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  32300. if (computeNormals === void 0) { computeNormals = true; }
  32301. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32302. if (!positions) {
  32303. return this;
  32304. }
  32305. positionFunction(positions);
  32306. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  32307. if (computeNormals) {
  32308. var indices = this.getIndices();
  32309. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32310. if (!normals) {
  32311. return this;
  32312. }
  32313. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  32314. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  32315. }
  32316. return this;
  32317. };
  32318. /**
  32319. * Creates a un-shared specific occurence of the geometry for the mesh.
  32320. * Returns the Mesh.
  32321. */
  32322. Mesh.prototype.makeGeometryUnique = function () {
  32323. if (!this._geometry) {
  32324. return this;
  32325. }
  32326. var oldGeometry = this._geometry;
  32327. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  32328. oldGeometry.releaseForMesh(this, true);
  32329. geometry.applyToMesh(this);
  32330. return this;
  32331. };
  32332. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  32333. if (totalVertices === void 0) { totalVertices = null; }
  32334. if (updatable === void 0) { updatable = false; }
  32335. if (!this._geometry) {
  32336. var vertexData = new BABYLON.VertexData();
  32337. vertexData.indices = indices;
  32338. var scene = this.getScene();
  32339. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  32340. }
  32341. else {
  32342. this._geometry.setIndices(indices, totalVertices, updatable);
  32343. }
  32344. return this;
  32345. };
  32346. /**
  32347. * Update the current index buffer
  32348. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  32349. * Returns the Mesh.
  32350. */
  32351. Mesh.prototype.updateIndices = function (indices, offset) {
  32352. if (!this._geometry) {
  32353. return this;
  32354. }
  32355. this._geometry.updateIndices(indices, offset);
  32356. return this;
  32357. };
  32358. /**
  32359. * Invert the geometry to move from a right handed system to a left handed one.
  32360. * Returns the Mesh.
  32361. */
  32362. Mesh.prototype.toLeftHanded = function () {
  32363. if (!this._geometry) {
  32364. return this;
  32365. }
  32366. this._geometry.toLeftHanded();
  32367. return this;
  32368. };
  32369. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  32370. if (!this._geometry) {
  32371. return this;
  32372. }
  32373. var engine = this.getScene().getEngine();
  32374. // Wireframe
  32375. var indexToBind;
  32376. if (this._unIndexed) {
  32377. indexToBind = null;
  32378. }
  32379. else {
  32380. switch (fillMode) {
  32381. case BABYLON.Material.PointFillMode:
  32382. indexToBind = null;
  32383. break;
  32384. case BABYLON.Material.WireFrameFillMode:
  32385. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  32386. break;
  32387. default:
  32388. case BABYLON.Material.TriangleFillMode:
  32389. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  32390. break;
  32391. }
  32392. }
  32393. // VBOs
  32394. this._geometry._bind(effect, indexToBind);
  32395. return this;
  32396. };
  32397. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  32398. if (alternate === void 0) { alternate = false; }
  32399. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32400. return this;
  32401. }
  32402. this.onBeforeDrawObservable.notifyObservers(this);
  32403. var scene = this.getScene();
  32404. var engine = scene.getEngine();
  32405. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  32406. // or triangles as points
  32407. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  32408. }
  32409. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  32410. // Triangles as wireframe
  32411. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  32412. }
  32413. else {
  32414. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  32415. }
  32416. if (scene._isAlternateRenderingEnabled && !alternate) {
  32417. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  32418. if (!effect || !scene.activeCamera) {
  32419. return this;
  32420. }
  32421. scene._switchToAlternateCameraConfiguration(true);
  32422. this._effectiveMaterial.bindView(effect);
  32423. this._effectiveMaterial.bindViewProjection(effect);
  32424. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  32425. this._draw(subMesh, fillMode, instancesCount, true);
  32426. engine.setViewport(scene.activeCamera.viewport);
  32427. scene._switchToAlternateCameraConfiguration(false);
  32428. this._effectiveMaterial.bindView(effect);
  32429. this._effectiveMaterial.bindViewProjection(effect);
  32430. }
  32431. return this;
  32432. };
  32433. /**
  32434. * Registers for this mesh a javascript function called just before the rendering process.
  32435. * This function is passed the current mesh.
  32436. * Return the Mesh.
  32437. */
  32438. Mesh.prototype.registerBeforeRender = function (func) {
  32439. this.onBeforeRenderObservable.add(func);
  32440. return this;
  32441. };
  32442. /**
  32443. * Disposes a previously registered javascript function called before the rendering.
  32444. * This function is passed the current mesh.
  32445. * Returns the Mesh.
  32446. */
  32447. Mesh.prototype.unregisterBeforeRender = function (func) {
  32448. this.onBeforeRenderObservable.removeCallback(func);
  32449. return this;
  32450. };
  32451. /**
  32452. * Registers for this mesh a javascript function called just after the rendering is complete.
  32453. * This function is passed the current mesh.
  32454. * Returns the Mesh.
  32455. */
  32456. Mesh.prototype.registerAfterRender = function (func) {
  32457. this.onAfterRenderObservable.add(func);
  32458. return this;
  32459. };
  32460. /**
  32461. * Disposes a previously registered javascript function called after the rendering.
  32462. * This function is passed the current mesh.
  32463. * Return the Mesh.
  32464. */
  32465. Mesh.prototype.unregisterAfterRender = function (func) {
  32466. this.onAfterRenderObservable.removeCallback(func);
  32467. return this;
  32468. };
  32469. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  32470. var scene = this.getScene();
  32471. this._batchCache.mustReturn = false;
  32472. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  32473. this._batchCache.visibleInstances[subMeshId] = null;
  32474. if (this._visibleInstances) {
  32475. var currentRenderId = scene.getRenderId();
  32476. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  32477. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  32478. var selfRenderId = this._renderId;
  32479. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  32480. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  32481. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  32482. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  32483. }
  32484. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  32485. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  32486. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  32487. this._batchCache.mustReturn = true;
  32488. return this._batchCache;
  32489. }
  32490. if (currentRenderId !== selfRenderId) {
  32491. this._batchCache.renderSelf[subMeshId] = false;
  32492. }
  32493. }
  32494. this._renderIdForInstances[subMeshId] = currentRenderId;
  32495. }
  32496. return this._batchCache;
  32497. };
  32498. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  32499. var visibleInstances = batch.visibleInstances[subMesh._id];
  32500. if (!visibleInstances) {
  32501. return this;
  32502. }
  32503. var matricesCount = visibleInstances.length + 1;
  32504. var bufferSize = matricesCount * 16 * 4;
  32505. var currentInstancesBufferSize = this._instancesBufferSize;
  32506. var instancesBuffer = this._instancesBuffer;
  32507. while (this._instancesBufferSize < bufferSize) {
  32508. this._instancesBufferSize *= 2;
  32509. }
  32510. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  32511. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  32512. }
  32513. var offset = 0;
  32514. var instancesCount = 0;
  32515. var world = this.getWorldMatrix();
  32516. if (batch.renderSelf[subMesh._id]) {
  32517. world.copyToArray(this._instancesData, offset);
  32518. offset += 16;
  32519. instancesCount++;
  32520. }
  32521. if (visibleInstances) {
  32522. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  32523. var instance = visibleInstances[instanceIndex];
  32524. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  32525. offset += 16;
  32526. instancesCount++;
  32527. }
  32528. }
  32529. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  32530. if (instancesBuffer) {
  32531. instancesBuffer.dispose();
  32532. }
  32533. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  32534. this._instancesBuffer = instancesBuffer;
  32535. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  32536. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  32537. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  32538. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  32539. }
  32540. else {
  32541. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  32542. }
  32543. this._bind(subMesh, effect, fillMode);
  32544. this._draw(subMesh, fillMode, instancesCount);
  32545. engine.unbindInstanceAttributes();
  32546. return this;
  32547. };
  32548. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  32549. var scene = this.getScene();
  32550. var engine = scene.getEngine();
  32551. if (hardwareInstancedRendering) {
  32552. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  32553. }
  32554. else {
  32555. if (batch.renderSelf[subMesh._id]) {
  32556. // Draw
  32557. if (onBeforeDraw) {
  32558. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  32559. }
  32560. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  32561. }
  32562. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  32563. if (visibleInstancesForSubMesh) {
  32564. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  32565. var instance = visibleInstancesForSubMesh[instanceIndex];
  32566. // World
  32567. var world = instance.getWorldMatrix();
  32568. if (onBeforeDraw) {
  32569. onBeforeDraw(true, world, effectiveMaterial);
  32570. }
  32571. // Draw
  32572. this._draw(subMesh, fillMode);
  32573. }
  32574. }
  32575. }
  32576. return this;
  32577. };
  32578. /**
  32579. * Triggers the draw call for the mesh.
  32580. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  32581. * Returns the Mesh.
  32582. */
  32583. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  32584. this._checkOcclusionQuery();
  32585. if (this._isOccluded) {
  32586. return this;
  32587. }
  32588. var scene = this.getScene();
  32589. // Managing instances
  32590. var batch = this._getInstancesRenderList(subMesh._id);
  32591. if (batch.mustReturn) {
  32592. return this;
  32593. }
  32594. // Checking geometry state
  32595. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32596. return this;
  32597. }
  32598. this.onBeforeRenderObservable.notifyObservers(this);
  32599. var engine = scene.getEngine();
  32600. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  32601. // Material
  32602. var material = subMesh.getMaterial();
  32603. if (!material) {
  32604. return this;
  32605. }
  32606. this._effectiveMaterial = material;
  32607. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32608. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  32609. return this;
  32610. }
  32611. }
  32612. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  32613. return this;
  32614. }
  32615. // Alpha mode
  32616. if (enableAlphaMode) {
  32617. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  32618. }
  32619. // Outline - step 1
  32620. var savedDepthWrite = engine.getDepthWrite();
  32621. if (this.renderOutline) {
  32622. engine.setDepthWrite(false);
  32623. scene.getOutlineRenderer().render(subMesh, batch);
  32624. engine.setDepthWrite(savedDepthWrite);
  32625. }
  32626. var effect;
  32627. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32628. effect = subMesh.effect;
  32629. }
  32630. else {
  32631. effect = this._effectiveMaterial.getEffect();
  32632. }
  32633. if (!effect) {
  32634. return this;
  32635. }
  32636. var sideOrientation = this.overrideMaterialSideOrientation;
  32637. if (sideOrientation == null) {
  32638. sideOrientation = this._effectiveMaterial.sideOrientation;
  32639. if (this._getWorldMatrixDeterminant() < 0) {
  32640. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  32641. }
  32642. }
  32643. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  32644. if (this._effectiveMaterial.forceDepthWrite) {
  32645. engine.setDepthWrite(true);
  32646. }
  32647. // Bind
  32648. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  32649. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  32650. this._bind(subMesh, effect, fillMode);
  32651. }
  32652. var world = this.getWorldMatrix();
  32653. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32654. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  32655. }
  32656. else {
  32657. this._effectiveMaterial.bind(world, this);
  32658. }
  32659. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  32660. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  32661. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32662. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  32663. }
  32664. // Draw
  32665. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32666. // Unbind
  32667. this._effectiveMaterial.unbind();
  32668. // Outline - step 2
  32669. if (this.renderOutline && savedDepthWrite) {
  32670. engine.setDepthWrite(true);
  32671. engine.setColorWrite(false);
  32672. scene.getOutlineRenderer().render(subMesh, batch);
  32673. engine.setColorWrite(true);
  32674. }
  32675. // Overlay
  32676. if (this.renderOverlay) {
  32677. var currentMode = engine.getAlphaMode();
  32678. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  32679. scene.getOutlineRenderer().render(subMesh, batch, true);
  32680. engine.setAlphaMode(currentMode);
  32681. }
  32682. this.onAfterRenderObservable.notifyObservers(this);
  32683. return this;
  32684. };
  32685. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  32686. if (isInstance && effectiveMaterial) {
  32687. effectiveMaterial.bindOnlyWorldMatrix(world);
  32688. }
  32689. };
  32690. /**
  32691. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  32692. */
  32693. Mesh.prototype.getEmittedParticleSystems = function () {
  32694. var results = new Array();
  32695. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32696. var particleSystem = this.getScene().particleSystems[index];
  32697. if (particleSystem.emitter === this) {
  32698. results.push(particleSystem);
  32699. }
  32700. }
  32701. return results;
  32702. };
  32703. /**
  32704. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  32705. */
  32706. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  32707. var results = new Array();
  32708. var descendants = this.getDescendants();
  32709. descendants.push(this);
  32710. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32711. var particleSystem = this.getScene().particleSystems[index];
  32712. var emitter = particleSystem.emitter;
  32713. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  32714. results.push(particleSystem);
  32715. }
  32716. }
  32717. return results;
  32718. };
  32719. /**
  32720. * Normalize matrix weights so that all vertices have a total weight set to 1
  32721. */
  32722. Mesh.prototype.cleanMatrixWeights = function () {
  32723. var epsilon = 1e-3;
  32724. var noInfluenceBoneIndex = 0.0;
  32725. if (this.skeleton) {
  32726. noInfluenceBoneIndex = this.skeleton.bones.length;
  32727. }
  32728. else {
  32729. return;
  32730. }
  32731. var matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32732. var matricesIndicesExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  32733. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32734. var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  32735. var influencers = this.numBoneInfluencers;
  32736. var size = matricesWeights.length;
  32737. for (var i = 0; i < size; i += 4) {
  32738. var weight = 0.0;
  32739. var firstZeroWeight = -1;
  32740. for (var j = 0; j < 4; j++) {
  32741. var w = matricesWeights[i + j];
  32742. weight += w;
  32743. if (w < epsilon && firstZeroWeight < 0) {
  32744. firstZeroWeight = j;
  32745. }
  32746. }
  32747. if (matricesWeightsExtra) {
  32748. for (var j = 0; j < 4; j++) {
  32749. var w = matricesWeightsExtra[i + j];
  32750. weight += w;
  32751. if (w < epsilon && firstZeroWeight < 0) {
  32752. firstZeroWeight = j + 4;
  32753. }
  32754. }
  32755. }
  32756. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  32757. firstZeroWeight = influencers - 1;
  32758. }
  32759. if (weight > epsilon) {
  32760. var mweight = 1.0 / weight;
  32761. for (var j = 0; j < 4; j++) {
  32762. matricesWeights[i + j] *= mweight;
  32763. }
  32764. if (matricesWeightsExtra) {
  32765. for (var j = 0; j < 4; j++) {
  32766. matricesWeightsExtra[i + j] *= mweight;
  32767. }
  32768. }
  32769. }
  32770. else {
  32771. if (firstZeroWeight >= 4) {
  32772. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  32773. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  32774. }
  32775. else {
  32776. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  32777. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  32778. }
  32779. }
  32780. }
  32781. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  32782. if (matricesIndicesExtra) {
  32783. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  32784. }
  32785. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights);
  32786. if (matricesWeightsExtra) {
  32787. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, matricesWeightsExtra);
  32788. }
  32789. };
  32790. Mesh.prototype._checkDelayState = function () {
  32791. var scene = this.getScene();
  32792. if (this._geometry) {
  32793. this._geometry.load(scene);
  32794. }
  32795. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  32796. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  32797. this._queueLoad(scene);
  32798. }
  32799. return this;
  32800. };
  32801. Mesh.prototype._queueLoad = function (scene) {
  32802. var _this = this;
  32803. scene._addPendingData(this);
  32804. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  32805. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  32806. if (data instanceof ArrayBuffer) {
  32807. _this._delayLoadingFunction(data, _this);
  32808. }
  32809. else {
  32810. _this._delayLoadingFunction(JSON.parse(data), _this);
  32811. }
  32812. _this.instances.forEach(function (instance) {
  32813. instance._syncSubMeshes();
  32814. });
  32815. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32816. scene._removePendingData(_this);
  32817. }, function () { }, scene.database, getBinaryData);
  32818. return this;
  32819. };
  32820. /**
  32821. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  32822. */
  32823. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  32824. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32825. return false;
  32826. }
  32827. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  32828. return false;
  32829. }
  32830. this._checkDelayState();
  32831. return true;
  32832. };
  32833. /**
  32834. * Sets the mesh material by the material or multiMaterial `id` property.
  32835. * The material `id` is a string identifying the material or the multiMaterial.
  32836. * This method returns the Mesh.
  32837. */
  32838. Mesh.prototype.setMaterialByID = function (id) {
  32839. var materials = this.getScene().materials;
  32840. var index;
  32841. for (index = materials.length - 1; index > -1; index--) {
  32842. if (materials[index].id === id) {
  32843. this.material = materials[index];
  32844. return this;
  32845. }
  32846. }
  32847. // Multi
  32848. var multiMaterials = this.getScene().multiMaterials;
  32849. for (index = multiMaterials.length - 1; index > -1; index--) {
  32850. if (multiMaterials[index].id === id) {
  32851. this.material = multiMaterials[index];
  32852. return this;
  32853. }
  32854. }
  32855. return this;
  32856. };
  32857. /**
  32858. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  32859. */
  32860. Mesh.prototype.getAnimatables = function () {
  32861. var results = new Array();
  32862. if (this.material) {
  32863. results.push(this.material);
  32864. }
  32865. if (this.skeleton) {
  32866. results.push(this.skeleton);
  32867. }
  32868. return results;
  32869. };
  32870. /**
  32871. * Modifies the mesh geometry according to the passed transformation matrix.
  32872. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  32873. * The mesh normals are modified accordingly the same transformation.
  32874. * tuto : http://doc.babylonjs.com/resources/baking_transformations
  32875. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32876. * Returns the Mesh.
  32877. */
  32878. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  32879. // Position
  32880. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32881. return this;
  32882. }
  32883. var submeshes = this.subMeshes.splice(0);
  32884. this._resetPointsArrayCache();
  32885. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32886. var temp = new Array();
  32887. var index;
  32888. for (index = 0; index < data.length; index += 3) {
  32889. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  32890. }
  32891. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  32892. // Normals
  32893. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32894. return this;
  32895. }
  32896. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32897. temp = [];
  32898. for (index = 0; index < data.length; index += 3) {
  32899. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  32900. }
  32901. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  32902. // flip faces?
  32903. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  32904. this.flipFaces();
  32905. }
  32906. // Restore submeshes
  32907. this.releaseSubMeshes();
  32908. this.subMeshes = submeshes;
  32909. return this;
  32910. };
  32911. /**
  32912. * Modifies the mesh geometry according to its own current World Matrix.
  32913. * The mesh World Matrix is then reset.
  32914. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  32915. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  32916. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32917. * Returns the Mesh.
  32918. */
  32919. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  32920. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  32921. this.scaling.copyFromFloats(1, 1, 1);
  32922. this.position.copyFromFloats(0, 0, 0);
  32923. this.rotation.copyFromFloats(0, 0, 0);
  32924. //only if quaternion is already set
  32925. if (this.rotationQuaternion) {
  32926. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  32927. }
  32928. this._worldMatrix = BABYLON.Matrix.Identity();
  32929. return this;
  32930. };
  32931. Object.defineProperty(Mesh.prototype, "_positions", {
  32932. // Cache
  32933. get: function () {
  32934. if (this._geometry) {
  32935. return this._geometry._positions;
  32936. }
  32937. return null;
  32938. },
  32939. enumerable: true,
  32940. configurable: true
  32941. });
  32942. Mesh.prototype._resetPointsArrayCache = function () {
  32943. if (this._geometry) {
  32944. this._geometry._resetPointsArrayCache();
  32945. }
  32946. return this;
  32947. };
  32948. Mesh.prototype._generatePointsArray = function () {
  32949. if (this._geometry) {
  32950. return this._geometry._generatePointsArray();
  32951. }
  32952. return false;
  32953. };
  32954. /**
  32955. * Returns a new Mesh object generated from the current mesh properties.
  32956. * This method must not get confused with createInstance().
  32957. * The parameter `name` is a string, the name given to the new mesh.
  32958. * The optional parameter `newParent` can be any Node object (default `null`).
  32959. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  32960. * 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.
  32961. */
  32962. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  32963. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  32964. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  32965. };
  32966. /**
  32967. * Releases resources associated with this mesh.
  32968. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  32969. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  32970. */
  32971. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  32972. var _this = this;
  32973. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  32974. this.morphTargetManager = null;
  32975. if (this._geometry) {
  32976. this._geometry.releaseForMesh(this, true);
  32977. }
  32978. // Sources
  32979. var meshes = this.getScene().meshes;
  32980. meshes.forEach(function (abstractMesh) {
  32981. var mesh = abstractMesh;
  32982. if (mesh._source && mesh._source === _this) {
  32983. mesh._source = null;
  32984. }
  32985. });
  32986. this._source = null;
  32987. // Instances
  32988. if (this._instancesBuffer) {
  32989. this._instancesBuffer.dispose();
  32990. this._instancesBuffer = null;
  32991. }
  32992. while (this.instances.length) {
  32993. this.instances[0].dispose();
  32994. }
  32995. // Effect layers.
  32996. var effectLayers = this.getScene().effectLayers;
  32997. for (var i = 0; i < effectLayers.length; i++) {
  32998. var effectLayer = effectLayers[i];
  32999. if (effectLayer) {
  33000. effectLayer._disposeMesh(this);
  33001. }
  33002. }
  33003. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  33004. };
  33005. /**
  33006. * Modifies the mesh geometry according to a displacement map.
  33007. * 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.
  33008. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  33009. * This method returns nothing.
  33010. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  33011. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  33012. * 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.
  33013. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  33014. * The parameter `uvScale` is an optional vector2 used to scale UV.
  33015. *
  33016. * Returns the Mesh.
  33017. */
  33018. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  33019. var _this = this;
  33020. var scene = this.getScene();
  33021. var onload = function (img) {
  33022. // Getting height map data
  33023. var canvas = document.createElement("canvas");
  33024. var context = canvas.getContext("2d");
  33025. var heightMapWidth = img.width;
  33026. var heightMapHeight = img.height;
  33027. canvas.width = heightMapWidth;
  33028. canvas.height = heightMapHeight;
  33029. context.drawImage(img, 0, 0);
  33030. // Create VertexData from map data
  33031. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  33032. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  33033. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  33034. //execute success callback, if set
  33035. if (onSuccess) {
  33036. onSuccess(_this);
  33037. }
  33038. };
  33039. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  33040. return this;
  33041. };
  33042. /**
  33043. * Modifies the mesh geometry according to a displacementMap buffer.
  33044. * 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.
  33045. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  33046. * This method returns nothing.
  33047. * 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.
  33048. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  33049. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  33050. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  33051. * The parameter `uvScale` is an optional vector2 used to scale UV.
  33052. *
  33053. * Returns the Mesh.
  33054. */
  33055. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  33056. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  33057. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  33058. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  33059. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  33060. return this;
  33061. }
  33062. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33063. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33064. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  33065. var position = BABYLON.Vector3.Zero();
  33066. var normal = BABYLON.Vector3.Zero();
  33067. var uv = BABYLON.Vector2.Zero();
  33068. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  33069. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  33070. for (var index = 0; index < positions.length; index += 3) {
  33071. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  33072. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  33073. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  33074. // Compute height
  33075. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  33076. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  33077. var pos = (u + v * heightMapWidth) * 4;
  33078. var r = buffer[pos] / 255.0;
  33079. var g = buffer[pos + 1] / 255.0;
  33080. var b = buffer[pos + 2] / 255.0;
  33081. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  33082. normal.normalize();
  33083. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  33084. position = position.add(normal);
  33085. position.toArray(positions, index);
  33086. }
  33087. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  33088. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  33089. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  33090. return this;
  33091. };
  33092. /**
  33093. * Modify the mesh to get a flat shading rendering.
  33094. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  33095. * This method returns the Mesh.
  33096. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  33097. */
  33098. Mesh.prototype.convertToFlatShadedMesh = function () {
  33099. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  33100. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  33101. var kinds = this.getVerticesDataKinds();
  33102. var vbs = {};
  33103. var data = {};
  33104. var newdata = {};
  33105. var updatableNormals = false;
  33106. var kindIndex;
  33107. var kind;
  33108. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33109. kind = kinds[kindIndex];
  33110. var vertexBuffer = this.getVertexBuffer(kind);
  33111. if (kind === BABYLON.VertexBuffer.NormalKind) {
  33112. updatableNormals = vertexBuffer.isUpdatable();
  33113. kinds.splice(kindIndex, 1);
  33114. kindIndex--;
  33115. continue;
  33116. }
  33117. vbs[kind] = vertexBuffer;
  33118. data[kind] = vbs[kind].getData();
  33119. newdata[kind] = [];
  33120. }
  33121. // Save previous submeshes
  33122. var previousSubmeshes = this.subMeshes.slice(0);
  33123. var indices = this.getIndices();
  33124. var totalIndices = this.getTotalIndices();
  33125. // Generating unique vertices per face
  33126. var index;
  33127. for (index = 0; index < totalIndices; index++) {
  33128. var vertexIndex = indices[index];
  33129. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33130. kind = kinds[kindIndex];
  33131. var stride = vbs[kind].getStrideSize();
  33132. for (var offset = 0; offset < stride; offset++) {
  33133. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  33134. }
  33135. }
  33136. }
  33137. // Updating faces & normal
  33138. var normals = [];
  33139. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  33140. for (index = 0; index < totalIndices; index += 3) {
  33141. indices[index] = index;
  33142. indices[index + 1] = index + 1;
  33143. indices[index + 2] = index + 2;
  33144. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  33145. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  33146. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  33147. var p1p2 = p1.subtract(p2);
  33148. var p3p2 = p3.subtract(p2);
  33149. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  33150. // Store same normals for every vertex
  33151. for (var localIndex = 0; localIndex < 3; localIndex++) {
  33152. normals.push(normal.x);
  33153. normals.push(normal.y);
  33154. normals.push(normal.z);
  33155. }
  33156. }
  33157. this.setIndices(indices);
  33158. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  33159. // Updating vertex buffers
  33160. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33161. kind = kinds[kindIndex];
  33162. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  33163. }
  33164. // Updating submeshes
  33165. this.releaseSubMeshes();
  33166. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  33167. var previousOne = previousSubmeshes[submeshIndex];
  33168. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  33169. }
  33170. this.synchronizeInstances();
  33171. return this;
  33172. };
  33173. /**
  33174. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  33175. * In other words, more vertices, no more indices and a single bigger VBO.
  33176. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  33177. * Returns the Mesh.
  33178. */
  33179. Mesh.prototype.convertToUnIndexedMesh = function () {
  33180. /// <summary>Remove indices by unfolding faces into buffers</summary>
  33181. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  33182. var kinds = this.getVerticesDataKinds();
  33183. var vbs = {};
  33184. var data = {};
  33185. var newdata = {};
  33186. var kindIndex;
  33187. var kind;
  33188. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33189. kind = kinds[kindIndex];
  33190. var vertexBuffer = this.getVertexBuffer(kind);
  33191. vbs[kind] = vertexBuffer;
  33192. data[kind] = vbs[kind].getData();
  33193. newdata[kind] = [];
  33194. }
  33195. // Save previous submeshes
  33196. var previousSubmeshes = this.subMeshes.slice(0);
  33197. var indices = this.getIndices();
  33198. var totalIndices = this.getTotalIndices();
  33199. // Generating unique vertices per face
  33200. var index;
  33201. for (index = 0; index < totalIndices; index++) {
  33202. var vertexIndex = indices[index];
  33203. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33204. kind = kinds[kindIndex];
  33205. var stride = vbs[kind].getStrideSize();
  33206. for (var offset = 0; offset < stride; offset++) {
  33207. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  33208. }
  33209. }
  33210. }
  33211. // Updating indices
  33212. for (index = 0; index < totalIndices; index += 3) {
  33213. indices[index] = index;
  33214. indices[index + 1] = index + 1;
  33215. indices[index + 2] = index + 2;
  33216. }
  33217. this.setIndices(indices);
  33218. // Updating vertex buffers
  33219. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33220. kind = kinds[kindIndex];
  33221. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  33222. }
  33223. // Updating submeshes
  33224. this.releaseSubMeshes();
  33225. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  33226. var previousOne = previousSubmeshes[submeshIndex];
  33227. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  33228. }
  33229. this._unIndexed = true;
  33230. this.synchronizeInstances();
  33231. return this;
  33232. };
  33233. /**
  33234. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  33235. * This method returns the Mesh.
  33236. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  33237. */
  33238. Mesh.prototype.flipFaces = function (flipNormals) {
  33239. if (flipNormals === void 0) { flipNormals = false; }
  33240. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  33241. var i;
  33242. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  33243. for (i = 0; i < vertex_data.normals.length; i++) {
  33244. vertex_data.normals[i] *= -1;
  33245. }
  33246. }
  33247. if (vertex_data.indices) {
  33248. var temp;
  33249. for (i = 0; i < vertex_data.indices.length; i += 3) {
  33250. // reassign indices
  33251. temp = vertex_data.indices[i + 1];
  33252. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  33253. vertex_data.indices[i + 2] = temp;
  33254. }
  33255. }
  33256. vertex_data.applyToMesh(this);
  33257. return this;
  33258. };
  33259. // Instances
  33260. /**
  33261. * Creates a new InstancedMesh object from the mesh model.
  33262. * An instance shares the same properties and the same material than its model.
  33263. * Only these properties of each instance can then be set individually :
  33264. * - position
  33265. * - rotation
  33266. * - rotationQuaternion
  33267. * - setPivotMatrix
  33268. * - scaling
  33269. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  33270. * Warning : this method is not supported for Line mesh and LineSystem
  33271. */
  33272. Mesh.prototype.createInstance = function (name) {
  33273. return new BABYLON.InstancedMesh(name, this);
  33274. };
  33275. /**
  33276. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  33277. * After this call, all the mesh instances have the same submeshes than the current mesh.
  33278. * This method returns the Mesh.
  33279. */
  33280. Mesh.prototype.synchronizeInstances = function () {
  33281. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  33282. var instance = this.instances[instanceIndex];
  33283. instance._syncSubMeshes();
  33284. }
  33285. return this;
  33286. };
  33287. /**
  33288. * Simplify the mesh according to the given array of settings.
  33289. * Function will return immediately and will simplify async. It returns the Mesh.
  33290. * @param settings a collection of simplification settings.
  33291. * @param parallelProcessing should all levels calculate parallel or one after the other.
  33292. * @param type the type of simplification to run.
  33293. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  33294. */
  33295. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  33296. if (parallelProcessing === void 0) { parallelProcessing = true; }
  33297. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  33298. this.getScene().simplificationQueue.addTask({
  33299. settings: settings,
  33300. parallelProcessing: parallelProcessing,
  33301. mesh: this,
  33302. simplificationType: simplificationType,
  33303. successCallback: successCallback
  33304. });
  33305. return this;
  33306. };
  33307. /**
  33308. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  33309. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  33310. * This should be used together with the simplification to avoid disappearing triangles.
  33311. * Returns the Mesh.
  33312. * @param successCallback an optional success callback to be called after the optimization finished.
  33313. */
  33314. Mesh.prototype.optimizeIndices = function (successCallback) {
  33315. var _this = this;
  33316. var indices = this.getIndices();
  33317. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33318. if (!positions || !indices) {
  33319. return this;
  33320. }
  33321. var vectorPositions = new Array();
  33322. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  33323. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  33324. }
  33325. var dupes = new Array();
  33326. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  33327. var realPos = vectorPositions.length - 1 - iteration;
  33328. var testedPosition = vectorPositions[realPos];
  33329. for (var j = 0; j < realPos; ++j) {
  33330. var againstPosition = vectorPositions[j];
  33331. if (testedPosition.equals(againstPosition)) {
  33332. dupes[realPos] = j;
  33333. break;
  33334. }
  33335. }
  33336. }, function () {
  33337. for (var i = 0; i < indices.length; ++i) {
  33338. indices[i] = dupes[indices[i]] || indices[i];
  33339. }
  33340. //indices are now reordered
  33341. var originalSubMeshes = _this.subMeshes.slice(0);
  33342. _this.setIndices(indices);
  33343. _this.subMeshes = originalSubMeshes;
  33344. if (successCallback) {
  33345. successCallback(_this);
  33346. }
  33347. });
  33348. return this;
  33349. };
  33350. Mesh.prototype.serialize = function (serializationObject) {
  33351. serializationObject.name = this.name;
  33352. serializationObject.id = this.id;
  33353. serializationObject.type = this.getClassName();
  33354. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  33355. serializationObject.tags = BABYLON.Tags.GetTags(this);
  33356. }
  33357. serializationObject.position = this.position.asArray();
  33358. if (this.rotationQuaternion) {
  33359. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  33360. }
  33361. else if (this.rotation) {
  33362. serializationObject.rotation = this.rotation.asArray();
  33363. }
  33364. serializationObject.scaling = this.scaling.asArray();
  33365. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  33366. serializationObject.isEnabled = this.isEnabled(false);
  33367. serializationObject.isVisible = this.isVisible;
  33368. serializationObject.infiniteDistance = this.infiniteDistance;
  33369. serializationObject.pickable = this.isPickable;
  33370. serializationObject.receiveShadows = this.receiveShadows;
  33371. serializationObject.billboardMode = this.billboardMode;
  33372. serializationObject.visibility = this.visibility;
  33373. serializationObject.checkCollisions = this.checkCollisions;
  33374. serializationObject.isBlocker = this.isBlocker;
  33375. // Parent
  33376. if (this.parent) {
  33377. serializationObject.parentId = this.parent.id;
  33378. }
  33379. // Geometry
  33380. serializationObject.isUnIndexed = this.isUnIndexed;
  33381. var geometry = this._geometry;
  33382. if (geometry) {
  33383. var geometryId = geometry.id;
  33384. serializationObject.geometryId = geometryId;
  33385. // SubMeshes
  33386. serializationObject.subMeshes = [];
  33387. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  33388. var subMesh = this.subMeshes[subIndex];
  33389. serializationObject.subMeshes.push({
  33390. materialIndex: subMesh.materialIndex,
  33391. verticesStart: subMesh.verticesStart,
  33392. verticesCount: subMesh.verticesCount,
  33393. indexStart: subMesh.indexStart,
  33394. indexCount: subMesh.indexCount
  33395. });
  33396. }
  33397. }
  33398. // Material
  33399. if (this.material) {
  33400. serializationObject.materialId = this.material.id;
  33401. }
  33402. else {
  33403. this.material = null;
  33404. }
  33405. // Morph targets
  33406. if (this.morphTargetManager) {
  33407. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  33408. }
  33409. // Skeleton
  33410. if (this.skeleton) {
  33411. serializationObject.skeletonId = this.skeleton.id;
  33412. }
  33413. // Physics
  33414. //TODO implement correct serialization for physics impostors.
  33415. var impostor = this.getPhysicsImpostor();
  33416. if (impostor) {
  33417. serializationObject.physicsMass = impostor.getParam("mass");
  33418. serializationObject.physicsFriction = impostor.getParam("friction");
  33419. serializationObject.physicsRestitution = impostor.getParam("mass");
  33420. serializationObject.physicsImpostor = impostor.type;
  33421. }
  33422. // Metadata
  33423. if (this.metadata) {
  33424. serializationObject.metadata = this.metadata;
  33425. }
  33426. // Instances
  33427. serializationObject.instances = [];
  33428. for (var index = 0; index < this.instances.length; index++) {
  33429. var instance = this.instances[index];
  33430. var serializationInstance = {
  33431. name: instance.name,
  33432. id: instance.id,
  33433. position: instance.position.asArray(),
  33434. scaling: instance.scaling.asArray()
  33435. };
  33436. if (instance.rotationQuaternion) {
  33437. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  33438. }
  33439. else if (instance.rotation) {
  33440. serializationInstance.rotation = instance.rotation.asArray();
  33441. }
  33442. serializationObject.instances.push(serializationInstance);
  33443. // Animations
  33444. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  33445. serializationInstance.ranges = instance.serializeAnimationRanges();
  33446. }
  33447. //
  33448. // Animations
  33449. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  33450. serializationObject.ranges = this.serializeAnimationRanges();
  33451. // Layer mask
  33452. serializationObject.layerMask = this.layerMask;
  33453. // Alpha
  33454. serializationObject.alphaIndex = this.alphaIndex;
  33455. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  33456. // Overlay
  33457. serializationObject.overlayAlpha = this.overlayAlpha;
  33458. serializationObject.overlayColor = this.overlayColor.asArray();
  33459. serializationObject.renderOverlay = this.renderOverlay;
  33460. // Fog
  33461. serializationObject.applyFog = this.applyFog;
  33462. // Action Manager
  33463. if (this.actionManager) {
  33464. serializationObject.actions = this.actionManager.serialize(this.name);
  33465. }
  33466. };
  33467. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  33468. if (!this.geometry) {
  33469. return;
  33470. }
  33471. this._markSubMeshesAsAttributesDirty();
  33472. var morphTargetManager = this._morphTargetManager;
  33473. if (morphTargetManager && morphTargetManager.vertexCount) {
  33474. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  33475. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  33476. this.morphTargetManager = null;
  33477. return;
  33478. }
  33479. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  33480. var morphTarget = morphTargetManager.getActiveTarget(index);
  33481. var positions = morphTarget.getPositions();
  33482. if (!positions) {
  33483. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  33484. return;
  33485. }
  33486. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  33487. var normals = morphTarget.getNormals();
  33488. if (normals) {
  33489. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  33490. }
  33491. var tangents = morphTarget.getTangents();
  33492. if (tangents) {
  33493. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  33494. }
  33495. }
  33496. }
  33497. else {
  33498. var index = 0;
  33499. // Positions
  33500. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  33501. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  33502. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  33503. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  33504. }
  33505. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  33506. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  33507. }
  33508. index++;
  33509. }
  33510. }
  33511. };
  33512. // Statics
  33513. /**
  33514. * Returns a new Mesh object parsed from the source provided.
  33515. * The parameter `parsedMesh` is the source.
  33516. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  33517. */
  33518. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  33519. var mesh;
  33520. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  33521. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  33522. }
  33523. else {
  33524. mesh = new Mesh(parsedMesh.name, scene);
  33525. }
  33526. mesh.id = parsedMesh.id;
  33527. if (BABYLON.Tags) {
  33528. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  33529. }
  33530. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  33531. if (parsedMesh.metadata !== undefined) {
  33532. mesh.metadata = parsedMesh.metadata;
  33533. }
  33534. if (parsedMesh.rotationQuaternion) {
  33535. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  33536. }
  33537. else if (parsedMesh.rotation) {
  33538. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  33539. }
  33540. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  33541. if (parsedMesh.localMatrix) {
  33542. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  33543. }
  33544. else if (parsedMesh.pivotMatrix) {
  33545. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  33546. }
  33547. mesh.setEnabled(parsedMesh.isEnabled);
  33548. mesh.isVisible = parsedMesh.isVisible;
  33549. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  33550. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  33551. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  33552. if (parsedMesh.applyFog !== undefined) {
  33553. mesh.applyFog = parsedMesh.applyFog;
  33554. }
  33555. if (parsedMesh.pickable !== undefined) {
  33556. mesh.isPickable = parsedMesh.pickable;
  33557. }
  33558. if (parsedMesh.alphaIndex !== undefined) {
  33559. mesh.alphaIndex = parsedMesh.alphaIndex;
  33560. }
  33561. mesh.receiveShadows = parsedMesh.receiveShadows;
  33562. mesh.billboardMode = parsedMesh.billboardMode;
  33563. if (parsedMesh.visibility !== undefined) {
  33564. mesh.visibility = parsedMesh.visibility;
  33565. }
  33566. mesh.checkCollisions = parsedMesh.checkCollisions;
  33567. if (parsedMesh.isBlocker !== undefined) {
  33568. mesh.isBlocker = parsedMesh.isBlocker;
  33569. }
  33570. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  33571. // freezeWorldMatrix
  33572. if (parsedMesh.freezeWorldMatrix) {
  33573. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  33574. }
  33575. // Parent
  33576. if (parsedMesh.parentId) {
  33577. mesh._waitingParentId = parsedMesh.parentId;
  33578. }
  33579. // Actions
  33580. if (parsedMesh.actions !== undefined) {
  33581. mesh._waitingActions = parsedMesh.actions;
  33582. }
  33583. // Overlay
  33584. if (parsedMesh.overlayAlpha !== undefined) {
  33585. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  33586. }
  33587. if (parsedMesh.overlayColor !== undefined) {
  33588. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  33589. }
  33590. if (parsedMesh.renderOverlay !== undefined) {
  33591. mesh.renderOverlay = parsedMesh.renderOverlay;
  33592. }
  33593. // Geometry
  33594. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  33595. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  33596. if (parsedMesh.delayLoadingFile) {
  33597. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33598. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  33599. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  33600. if (parsedMesh._binaryInfo) {
  33601. mesh._binaryInfo = parsedMesh._binaryInfo;
  33602. }
  33603. mesh._delayInfo = [];
  33604. if (parsedMesh.hasUVs) {
  33605. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  33606. }
  33607. if (parsedMesh.hasUVs2) {
  33608. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  33609. }
  33610. if (parsedMesh.hasUVs3) {
  33611. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  33612. }
  33613. if (parsedMesh.hasUVs4) {
  33614. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  33615. }
  33616. if (parsedMesh.hasUVs5) {
  33617. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  33618. }
  33619. if (parsedMesh.hasUVs6) {
  33620. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  33621. }
  33622. if (parsedMesh.hasColors) {
  33623. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  33624. }
  33625. if (parsedMesh.hasMatricesIndices) {
  33626. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33627. }
  33628. if (parsedMesh.hasMatricesWeights) {
  33629. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33630. }
  33631. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  33632. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  33633. mesh._checkDelayState();
  33634. }
  33635. }
  33636. else {
  33637. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  33638. }
  33639. // Material
  33640. if (parsedMesh.materialId) {
  33641. mesh.setMaterialByID(parsedMesh.materialId);
  33642. }
  33643. else {
  33644. mesh.material = null;
  33645. }
  33646. // Morph targets
  33647. if (parsedMesh.morphTargetManagerId > -1) {
  33648. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  33649. }
  33650. // Skeleton
  33651. if (parsedMesh.skeletonId > -1) {
  33652. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  33653. if (parsedMesh.numBoneInfluencers) {
  33654. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  33655. }
  33656. }
  33657. // Animations
  33658. if (parsedMesh.animations) {
  33659. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33660. var parsedAnimation = parsedMesh.animations[animationIndex];
  33661. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33662. }
  33663. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  33664. }
  33665. if (parsedMesh.autoAnimate) {
  33666. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33667. }
  33668. // Layer Mask
  33669. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  33670. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  33671. }
  33672. else {
  33673. mesh.layerMask = 0x0FFFFFFF;
  33674. }
  33675. // Physics
  33676. if (parsedMesh.physicsImpostor) {
  33677. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  33678. mass: parsedMesh.physicsMass,
  33679. friction: parsedMesh.physicsFriction,
  33680. restitution: parsedMesh.physicsRestitution
  33681. }, scene);
  33682. }
  33683. // Instances
  33684. if (parsedMesh.instances) {
  33685. for (var index = 0; index < parsedMesh.instances.length; index++) {
  33686. var parsedInstance = parsedMesh.instances[index];
  33687. var instance = mesh.createInstance(parsedInstance.name);
  33688. if (parsedInstance.id) {
  33689. instance.id = parsedInstance.id;
  33690. }
  33691. if (BABYLON.Tags) {
  33692. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  33693. }
  33694. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  33695. if (parsedInstance.parentId) {
  33696. instance._waitingParentId = parsedInstance.parentId;
  33697. }
  33698. if (parsedInstance.rotationQuaternion) {
  33699. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  33700. }
  33701. else if (parsedInstance.rotation) {
  33702. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  33703. }
  33704. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  33705. instance.checkCollisions = mesh.checkCollisions;
  33706. if (parsedMesh.animations) {
  33707. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33708. parsedAnimation = parsedMesh.animations[animationIndex];
  33709. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33710. }
  33711. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  33712. if (parsedMesh.autoAnimate) {
  33713. scene.beginAnimation(instance, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33714. }
  33715. }
  33716. }
  33717. }
  33718. return mesh;
  33719. };
  33720. /**
  33721. * Creates a ribbon mesh.
  33722. * Please consider using the same method from the MeshBuilder class instead.
  33723. * 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.
  33724. *
  33725. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  33726. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  33727. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  33728. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  33729. * 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.
  33730. * 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.
  33731. * 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
  33732. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33733. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33734. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33735. */
  33736. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  33737. if (closeArray === void 0) { closeArray = false; }
  33738. if (updatable === void 0) { updatable = false; }
  33739. return BABYLON.MeshBuilder.CreateRibbon(name, {
  33740. pathArray: pathArray,
  33741. closeArray: closeArray,
  33742. closePath: closePath,
  33743. offset: offset,
  33744. updatable: updatable,
  33745. sideOrientation: sideOrientation,
  33746. instance: instance
  33747. }, scene);
  33748. };
  33749. /**
  33750. * Creates a plane polygonal mesh. By default, this is a disc.
  33751. * Please consider using the same method from the MeshBuilder class instead.
  33752. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  33753. * 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.
  33754. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33755. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33756. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33757. */
  33758. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  33759. if (scene === void 0) { scene = null; }
  33760. var options = {
  33761. radius: radius,
  33762. tessellation: tessellation,
  33763. sideOrientation: sideOrientation,
  33764. updatable: updatable
  33765. };
  33766. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  33767. };
  33768. /**
  33769. * Creates a box mesh.
  33770. * Please consider using the same method from the MeshBuilder class instead.
  33771. * The parameter `size` sets the size (float) of each box side (default 1).
  33772. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33773. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33774. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33775. */
  33776. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  33777. if (scene === void 0) { scene = null; }
  33778. var options = {
  33779. size: size,
  33780. sideOrientation: sideOrientation,
  33781. updatable: updatable
  33782. };
  33783. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  33784. };
  33785. /**
  33786. * Creates a sphere mesh.
  33787. * Please consider using the same method from the MeshBuilder class instead.
  33788. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  33789. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  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.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  33795. var options = {
  33796. segments: segments,
  33797. diameterX: diameter,
  33798. diameterY: diameter,
  33799. diameterZ: diameter,
  33800. sideOrientation: sideOrientation,
  33801. updatable: updatable
  33802. };
  33803. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  33804. };
  33805. /**
  33806. * Creates a cylinder or a cone mesh.
  33807. * Please consider using the same method from the MeshBuilder class instead.
  33808. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  33809. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  33810. * 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.
  33811. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  33812. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  33813. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33814. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33815. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33816. */
  33817. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  33818. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  33819. if (scene !== undefined) {
  33820. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  33821. updatable = scene;
  33822. }
  33823. scene = subdivisions;
  33824. subdivisions = 1;
  33825. }
  33826. var options = {
  33827. height: height,
  33828. diameterTop: diameterTop,
  33829. diameterBottom: diameterBottom,
  33830. tessellation: tessellation,
  33831. subdivisions: subdivisions,
  33832. sideOrientation: sideOrientation,
  33833. updatable: updatable
  33834. };
  33835. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  33836. };
  33837. // Torus (Code from SharpDX.org)
  33838. /**
  33839. * Creates a torus mesh.
  33840. * Please consider using the same method from the MeshBuilder class instead.
  33841. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  33842. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  33843. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  33844. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33845. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33846. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33847. */
  33848. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  33849. var options = {
  33850. diameter: diameter,
  33851. thickness: thickness,
  33852. tessellation: tessellation,
  33853. sideOrientation: sideOrientation,
  33854. updatable: updatable
  33855. };
  33856. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  33857. };
  33858. /**
  33859. * Creates a torus knot mesh.
  33860. * Please consider using the same method from the MeshBuilder class instead.
  33861. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  33862. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  33863. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  33864. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  33865. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33866. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  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.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  33870. var options = {
  33871. radius: radius,
  33872. tube: tube,
  33873. radialSegments: radialSegments,
  33874. tubularSegments: tubularSegments,
  33875. p: p,
  33876. q: q,
  33877. sideOrientation: sideOrientation,
  33878. updatable: updatable
  33879. };
  33880. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  33881. };
  33882. /**
  33883. * Creates a line mesh.
  33884. * Please consider using the same method from the MeshBuilder class instead.
  33885. * 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.
  33886. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33887. * The parameter `points` is an array successive Vector3.
  33888. * 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
  33889. * When updating an instance, remember that only point positions can change, not the number of points.
  33890. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33891. */
  33892. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  33893. if (scene === void 0) { scene = null; }
  33894. if (updatable === void 0) { updatable = false; }
  33895. if (instance === void 0) { instance = null; }
  33896. var options = {
  33897. points: points,
  33898. updatable: updatable,
  33899. instance: instance
  33900. };
  33901. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  33902. };
  33903. /**
  33904. * Creates a dashed line mesh.
  33905. * Please consider using the same method from the MeshBuilder class instead.
  33906. * 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.
  33907. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33908. * The parameter `points` is an array successive Vector3.
  33909. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  33910. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  33911. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  33912. * 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
  33913. * When updating an instance, remember that only point positions can change, not the number of points.
  33914. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33915. */
  33916. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  33917. if (scene === void 0) { scene = null; }
  33918. var options = {
  33919. points: points,
  33920. dashSize: dashSize,
  33921. gapSize: gapSize,
  33922. dashNb: dashNb,
  33923. updatable: updatable,
  33924. instance: instance
  33925. };
  33926. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  33927. };
  33928. /**
  33929. * Creates a polygon mesh.
  33930. * Please consider using the same method from the MeshBuilder class instead.
  33931. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  33932. * 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.
  33933. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33934. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33935. * Remember you can only change the shape positions, not their number when updating a polygon.
  33936. */
  33937. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  33938. var options = {
  33939. shape: shape,
  33940. holes: holes,
  33941. updatable: updatable,
  33942. sideOrientation: sideOrientation
  33943. };
  33944. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  33945. };
  33946. /**
  33947. * Creates an extruded polygon mesh, with depth in the Y direction.
  33948. * Please consider using the same method from the MeshBuilder class instead.
  33949. */
  33950. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  33951. var options = {
  33952. shape: shape,
  33953. holes: holes,
  33954. depth: depth,
  33955. updatable: updatable,
  33956. sideOrientation: sideOrientation
  33957. };
  33958. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  33959. };
  33960. /**
  33961. * Creates an extruded shape mesh.
  33962. * 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.
  33963. * Please consider using the same method from the MeshBuilder class instead.
  33964. *
  33965. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33966. * 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
  33967. * extruded along the Z axis.
  33968. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33969. * 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.
  33970. * The parameter `scale` (float, default 1) is the value to scale the shape.
  33971. * 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
  33972. * 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
  33973. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33974. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33975. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33976. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33977. */
  33978. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  33979. if (scene === void 0) { scene = null; }
  33980. var options = {
  33981. shape: shape,
  33982. path: path,
  33983. scale: scale,
  33984. rotation: rotation,
  33985. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33986. sideOrientation: sideOrientation,
  33987. instance: instance,
  33988. updatable: updatable
  33989. };
  33990. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  33991. };
  33992. /**
  33993. * Creates an custom extruded shape mesh.
  33994. * 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.
  33995. * Please consider using the same method from the MeshBuilder class instead.
  33996. *
  33997. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33998. * 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
  33999. * extruded along the Z axis.
  34000. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  34001. * 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
  34002. * and the distance of this point from the begining of the path :
  34003. * ```javascript
  34004. * var rotationFunction = function(i, distance) {
  34005. * // do things
  34006. * return rotationValue; }
  34007. * ```
  34008. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  34009. * 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
  34010. * and the distance of this point from the begining of the path :
  34011. * ```javascript
  34012. * var scaleFunction = function(i, distance) {
  34013. * // do things
  34014. * return scaleValue;}
  34015. * ```
  34016. * It must returns a float value that will be the scale value applied to the shape on each path point.
  34017. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  34018. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  34019. * 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
  34020. * 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
  34021. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  34022. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34023. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34024. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34025. */
  34026. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  34027. var options = {
  34028. shape: shape,
  34029. path: path,
  34030. scaleFunction: scaleFunction,
  34031. rotationFunction: rotationFunction,
  34032. ribbonCloseArray: ribbonCloseArray,
  34033. ribbonClosePath: ribbonClosePath,
  34034. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  34035. sideOrientation: sideOrientation,
  34036. instance: instance,
  34037. updatable: updatable
  34038. };
  34039. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  34040. };
  34041. /**
  34042. * Creates lathe mesh.
  34043. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  34044. * Please consider using the same method from the MeshBuilder class instead.
  34045. * 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
  34046. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  34047. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  34048. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  34049. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34050. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34051. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34052. */
  34053. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  34054. var options = {
  34055. shape: shape,
  34056. radius: radius,
  34057. tessellation: tessellation,
  34058. sideOrientation: sideOrientation,
  34059. updatable: updatable
  34060. };
  34061. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  34062. };
  34063. /**
  34064. * Creates a plane mesh.
  34065. * Please consider using the same method from the MeshBuilder class instead.
  34066. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  34067. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34068. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34069. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34070. */
  34071. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  34072. var options = {
  34073. size: size,
  34074. width: size,
  34075. height: size,
  34076. sideOrientation: sideOrientation,
  34077. updatable: updatable
  34078. };
  34079. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  34080. };
  34081. /**
  34082. * Creates a ground mesh.
  34083. * Please consider using the same method from the MeshBuilder class instead.
  34084. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  34085. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  34086. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34087. */
  34088. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  34089. var options = {
  34090. width: width,
  34091. height: height,
  34092. subdivisions: subdivisions,
  34093. updatable: updatable
  34094. };
  34095. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  34096. };
  34097. /**
  34098. * Creates a tiled ground mesh.
  34099. * Please consider using the same method from the MeshBuilder class instead.
  34100. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  34101. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  34102. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  34103. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  34104. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  34105. * numbers of subdivisions on the ground width and height of each tile.
  34106. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34107. */
  34108. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  34109. var options = {
  34110. xmin: xmin,
  34111. zmin: zmin,
  34112. xmax: xmax,
  34113. zmax: zmax,
  34114. subdivisions: subdivisions,
  34115. precision: precision,
  34116. updatable: updatable
  34117. };
  34118. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  34119. };
  34120. /**
  34121. * Creates a ground mesh from a height map.
  34122. * tuto : http://doc.babylonjs.com/babylon101/height_map
  34123. * Please consider using the same method from the MeshBuilder class instead.
  34124. * The parameter `url` sets the URL of the height map image resource.
  34125. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  34126. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  34127. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  34128. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  34129. * 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).
  34130. * This function is passed the newly built mesh :
  34131. * ```javascript
  34132. * function(mesh) { // do things
  34133. * return; }
  34134. * ```
  34135. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34136. */
  34137. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  34138. var options = {
  34139. width: width,
  34140. height: height,
  34141. subdivisions: subdivisions,
  34142. minHeight: minHeight,
  34143. maxHeight: maxHeight,
  34144. updatable: updatable,
  34145. onReady: onReady
  34146. };
  34147. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  34148. };
  34149. /**
  34150. * Creates a tube mesh.
  34151. * 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.
  34152. * Please consider using the same method from the MeshBuilder class instead.
  34153. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  34154. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  34155. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  34156. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  34157. * 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.
  34158. * It must return a radius value (positive float) :
  34159. * ```javascript
  34160. * var radiusFunction = function(i, distance) {
  34161. * // do things
  34162. * return radius; }
  34163. * ```
  34164. * 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
  34165. * 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
  34166. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34167. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34168. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34169. */
  34170. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  34171. var options = {
  34172. path: path,
  34173. radius: radius,
  34174. tessellation: tessellation,
  34175. radiusFunction: radiusFunction,
  34176. arc: 1,
  34177. cap: cap,
  34178. updatable: updatable,
  34179. sideOrientation: sideOrientation,
  34180. instance: instance
  34181. };
  34182. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  34183. };
  34184. /**
  34185. * Creates a polyhedron mesh.
  34186. * Please consider using the same method from the MeshBuilder class instead.
  34187. * 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
  34188. * to choose the wanted type.
  34189. * The parameter `size` (positive float, default 1) sets the polygon size.
  34190. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  34191. * 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`.
  34192. * 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
  34193. * 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)`).
  34194. * 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
  34195. * 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.
  34196. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34197. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34198. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34199. */
  34200. Mesh.CreatePolyhedron = function (name, options, scene) {
  34201. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  34202. };
  34203. /**
  34204. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  34205. * Please consider using the same method from the MeshBuilder class instead.
  34206. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  34207. * 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`).
  34208. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  34209. * 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.
  34210. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34211. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34212. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34213. */
  34214. Mesh.CreateIcoSphere = function (name, options, scene) {
  34215. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  34216. };
  34217. /**
  34218. * Creates a decal mesh.
  34219. * Please consider using the same method from the MeshBuilder class instead.
  34220. * 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.
  34221. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  34222. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  34223. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  34224. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  34225. */
  34226. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  34227. var options = {
  34228. position: position,
  34229. normal: normal,
  34230. size: size,
  34231. angle: angle
  34232. };
  34233. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  34234. };
  34235. // Skeletons
  34236. /**
  34237. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  34238. */
  34239. Mesh.prototype.setPositionsForCPUSkinning = function () {
  34240. if (!this._sourcePositions) {
  34241. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34242. if (!source) {
  34243. return this._sourcePositions;
  34244. }
  34245. this._sourcePositions = new Float32Array(source);
  34246. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  34247. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  34248. }
  34249. }
  34250. return this._sourcePositions;
  34251. };
  34252. /**
  34253. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  34254. */
  34255. Mesh.prototype.setNormalsForCPUSkinning = function () {
  34256. if (!this._sourceNormals) {
  34257. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34258. if (!source) {
  34259. return this._sourceNormals;
  34260. }
  34261. this._sourceNormals = new Float32Array(source);
  34262. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  34263. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  34264. }
  34265. }
  34266. return this._sourceNormals;
  34267. };
  34268. /**
  34269. * Updates the vertex buffer by applying transformation from the bones.
  34270. * Returns the Mesh.
  34271. *
  34272. * @param {skeleton} skeleton to apply
  34273. */
  34274. Mesh.prototype.applySkeleton = function (skeleton) {
  34275. if (!this.geometry) {
  34276. return this;
  34277. }
  34278. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  34279. return this;
  34280. }
  34281. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  34282. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  34283. return this;
  34284. }
  34285. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  34286. return this;
  34287. }
  34288. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  34289. return this;
  34290. }
  34291. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  34292. return this;
  34293. }
  34294. if (!this._sourcePositions) {
  34295. var submeshes = this.subMeshes.slice();
  34296. this.setPositionsForCPUSkinning();
  34297. this.subMeshes = submeshes;
  34298. }
  34299. if (!this._sourceNormals) {
  34300. this.setNormalsForCPUSkinning();
  34301. }
  34302. // positionsData checks for not being Float32Array will only pass at most once
  34303. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34304. if (!positionsData) {
  34305. return this;
  34306. }
  34307. if (!(positionsData instanceof Float32Array)) {
  34308. positionsData = new Float32Array(positionsData);
  34309. }
  34310. // normalsData checks for not being Float32Array will only pass at most once
  34311. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34312. if (!normalsData) {
  34313. return this;
  34314. }
  34315. if (!(normalsData instanceof Float32Array)) {
  34316. normalsData = new Float32Array(normalsData);
  34317. }
  34318. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  34319. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  34320. if (!matricesWeightsData || !matricesIndicesData) {
  34321. return this;
  34322. }
  34323. var needExtras = this.numBoneInfluencers > 4;
  34324. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  34325. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  34326. var skeletonMatrices = skeleton.getTransformMatrices(this);
  34327. var tempVector3 = BABYLON.Vector3.Zero();
  34328. var finalMatrix = new BABYLON.Matrix();
  34329. var tempMatrix = new BABYLON.Matrix();
  34330. var matWeightIdx = 0;
  34331. var inf;
  34332. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  34333. var weight;
  34334. for (inf = 0; inf < 4; inf++) {
  34335. weight = matricesWeightsData[matWeightIdx + inf];
  34336. if (weight > 0) {
  34337. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  34338. finalMatrix.addToSelf(tempMatrix);
  34339. }
  34340. else
  34341. break;
  34342. }
  34343. if (needExtras) {
  34344. for (inf = 0; inf < 4; inf++) {
  34345. weight = matricesWeightsExtraData[matWeightIdx + inf];
  34346. if (weight > 0) {
  34347. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  34348. finalMatrix.addToSelf(tempMatrix);
  34349. }
  34350. else
  34351. break;
  34352. }
  34353. }
  34354. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  34355. tempVector3.toArray(positionsData, index);
  34356. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  34357. tempVector3.toArray(normalsData, index);
  34358. finalMatrix.reset();
  34359. }
  34360. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  34361. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  34362. return this;
  34363. };
  34364. // Tools
  34365. /**
  34366. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  34367. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  34368. */
  34369. Mesh.MinMax = function (meshes) {
  34370. var minVector = null;
  34371. var maxVector = null;
  34372. meshes.forEach(function (mesh, index, array) {
  34373. var boundingInfo = mesh.getBoundingInfo();
  34374. var boundingBox = boundingInfo.boundingBox;
  34375. if (!minVector || !maxVector) {
  34376. minVector = boundingBox.minimumWorld;
  34377. maxVector = boundingBox.maximumWorld;
  34378. }
  34379. else {
  34380. minVector.minimizeInPlace(boundingBox.minimumWorld);
  34381. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  34382. }
  34383. });
  34384. if (!minVector || !maxVector) {
  34385. return {
  34386. min: BABYLON.Vector3.Zero(),
  34387. max: BABYLON.Vector3.Zero()
  34388. };
  34389. }
  34390. return {
  34391. min: minVector,
  34392. max: maxVector
  34393. };
  34394. };
  34395. /**
  34396. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  34397. */
  34398. Mesh.Center = function (meshesOrMinMaxVector) {
  34399. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  34400. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  34401. };
  34402. /**
  34403. * Merge the array of meshes into a single mesh for performance reasons.
  34404. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  34405. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  34406. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  34407. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  34408. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  34409. */
  34410. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  34411. if (disposeSource === void 0) { disposeSource = true; }
  34412. var index;
  34413. if (!allow32BitsIndices) {
  34414. var totalVertices = 0;
  34415. // Counting vertices
  34416. for (index = 0; index < meshes.length; index++) {
  34417. if (meshes[index]) {
  34418. totalVertices += meshes[index].getTotalVertices();
  34419. if (totalVertices > 65536) {
  34420. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  34421. return null;
  34422. }
  34423. }
  34424. }
  34425. }
  34426. // Merge
  34427. var vertexData = null;
  34428. var otherVertexData;
  34429. var indiceArray = new Array();
  34430. var source = null;
  34431. for (index = 0; index < meshes.length; index++) {
  34432. if (meshes[index]) {
  34433. meshes[index].computeWorldMatrix(true);
  34434. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true, true);
  34435. otherVertexData.transform(meshes[index].getWorldMatrix());
  34436. if (vertexData) {
  34437. vertexData.merge(otherVertexData);
  34438. }
  34439. else {
  34440. vertexData = otherVertexData;
  34441. source = meshes[index];
  34442. }
  34443. if (subdivideWithSubMeshes) {
  34444. indiceArray.push(meshes[index].getTotalIndices());
  34445. }
  34446. }
  34447. }
  34448. source = source;
  34449. if (!meshSubclass) {
  34450. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  34451. }
  34452. vertexData.applyToMesh(meshSubclass);
  34453. // Setting properties
  34454. meshSubclass.material = source.material;
  34455. meshSubclass.checkCollisions = source.checkCollisions;
  34456. // Cleaning
  34457. if (disposeSource) {
  34458. for (index = 0; index < meshes.length; index++) {
  34459. if (meshes[index]) {
  34460. meshes[index].dispose();
  34461. }
  34462. }
  34463. }
  34464. // Subdivide
  34465. if (subdivideWithSubMeshes) {
  34466. //-- removal of global submesh
  34467. meshSubclass.releaseSubMeshes();
  34468. index = 0;
  34469. var offset = 0;
  34470. //-- apply subdivision according to index table
  34471. while (index < indiceArray.length) {
  34472. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  34473. offset += indiceArray[index];
  34474. index++;
  34475. }
  34476. }
  34477. return meshSubclass;
  34478. };
  34479. // Consts
  34480. Mesh._FRONTSIDE = 0;
  34481. Mesh._BACKSIDE = 1;
  34482. Mesh._DOUBLESIDE = 2;
  34483. Mesh._DEFAULTSIDE = 0;
  34484. Mesh._NO_CAP = 0;
  34485. Mesh._CAP_START = 1;
  34486. Mesh._CAP_END = 2;
  34487. Mesh._CAP_ALL = 3;
  34488. return Mesh;
  34489. }(BABYLON.AbstractMesh));
  34490. BABYLON.Mesh = Mesh;
  34491. })(BABYLON || (BABYLON = {}));
  34492. //# sourceMappingURL=babylon.mesh.js.map
  34493. var BABYLON;
  34494. (function (BABYLON) {
  34495. var BaseSubMesh = /** @class */ (function () {
  34496. function BaseSubMesh() {
  34497. }
  34498. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  34499. get: function () {
  34500. return this._materialEffect;
  34501. },
  34502. enumerable: true,
  34503. configurable: true
  34504. });
  34505. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  34506. if (defines === void 0) { defines = null; }
  34507. if (this._materialEffect === effect) {
  34508. if (!effect) {
  34509. this._materialDefines = null;
  34510. }
  34511. return;
  34512. }
  34513. this._materialDefines = defines;
  34514. this._materialEffect = effect;
  34515. };
  34516. return BaseSubMesh;
  34517. }());
  34518. BABYLON.BaseSubMesh = BaseSubMesh;
  34519. var SubMesh = /** @class */ (function (_super) {
  34520. __extends(SubMesh, _super);
  34521. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34522. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34523. var _this = _super.call(this) || this;
  34524. _this.materialIndex = materialIndex;
  34525. _this.verticesStart = verticesStart;
  34526. _this.verticesCount = verticesCount;
  34527. _this.indexStart = indexStart;
  34528. _this.indexCount = indexCount;
  34529. _this._renderId = 0;
  34530. _this._mesh = mesh;
  34531. _this._renderingMesh = renderingMesh || mesh;
  34532. mesh.subMeshes.push(_this);
  34533. _this._trianglePlanes = [];
  34534. _this._id = mesh.subMeshes.length - 1;
  34535. if (createBoundingBox) {
  34536. _this.refreshBoundingInfo();
  34537. mesh.computeWorldMatrix(true);
  34538. }
  34539. return _this;
  34540. }
  34541. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34542. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34543. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  34544. };
  34545. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  34546. get: function () {
  34547. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  34548. },
  34549. enumerable: true,
  34550. configurable: true
  34551. });
  34552. /**
  34553. * Returns the submesh BoudingInfo object.
  34554. */
  34555. SubMesh.prototype.getBoundingInfo = function () {
  34556. if (this.IsGlobal) {
  34557. return this._mesh.getBoundingInfo();
  34558. }
  34559. return this._boundingInfo;
  34560. };
  34561. /**
  34562. * Sets the submesh BoundingInfo.
  34563. * Return the SubMesh.
  34564. */
  34565. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  34566. this._boundingInfo = boundingInfo;
  34567. return this;
  34568. };
  34569. /**
  34570. * Returns the mesh of the current submesh.
  34571. */
  34572. SubMesh.prototype.getMesh = function () {
  34573. return this._mesh;
  34574. };
  34575. /**
  34576. * Returns the rendering mesh of the submesh.
  34577. */
  34578. SubMesh.prototype.getRenderingMesh = function () {
  34579. return this._renderingMesh;
  34580. };
  34581. /**
  34582. * Returns the submesh material.
  34583. */
  34584. SubMesh.prototype.getMaterial = function () {
  34585. var rootMaterial = this._renderingMesh.material;
  34586. if (rootMaterial === null || rootMaterial === undefined) {
  34587. return this._mesh.getScene().defaultMaterial;
  34588. }
  34589. else if (rootMaterial.getSubMaterial) {
  34590. var multiMaterial = rootMaterial;
  34591. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  34592. if (this._currentMaterial !== effectiveMaterial) {
  34593. this._currentMaterial = effectiveMaterial;
  34594. this._materialDefines = null;
  34595. }
  34596. return effectiveMaterial;
  34597. }
  34598. return rootMaterial;
  34599. };
  34600. // Methods
  34601. /**
  34602. * Sets a new updated BoundingInfo object to the submesh.
  34603. * Returns the SubMesh.
  34604. */
  34605. SubMesh.prototype.refreshBoundingInfo = function () {
  34606. this._lastColliderWorldVertices = null;
  34607. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  34608. return this;
  34609. }
  34610. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34611. if (!data) {
  34612. this._boundingInfo = this._mesh.getBoundingInfo();
  34613. return this;
  34614. }
  34615. var indices = this._renderingMesh.getIndices();
  34616. var extend;
  34617. //is this the only submesh?
  34618. if (this.indexStart === 0 && this.indexCount === indices.length) {
  34619. var boundingInfo = this._renderingMesh.getBoundingInfo();
  34620. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  34621. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  34622. }
  34623. else {
  34624. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  34625. }
  34626. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  34627. return this;
  34628. };
  34629. SubMesh.prototype._checkCollision = function (collider) {
  34630. var boundingInfo = this.getBoundingInfo();
  34631. return boundingInfo._checkCollision(collider);
  34632. };
  34633. /**
  34634. * Updates the submesh BoundingInfo.
  34635. * Returns the Submesh.
  34636. */
  34637. SubMesh.prototype.updateBoundingInfo = function (world) {
  34638. var boundingInfo = this.getBoundingInfo();
  34639. if (!boundingInfo) {
  34640. this.refreshBoundingInfo();
  34641. boundingInfo = this.getBoundingInfo();
  34642. }
  34643. boundingInfo.update(world);
  34644. return this;
  34645. };
  34646. /**
  34647. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  34648. * Boolean returned.
  34649. */
  34650. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  34651. var boundingInfo = this.getBoundingInfo();
  34652. if (!boundingInfo) {
  34653. return false;
  34654. }
  34655. return boundingInfo.isInFrustum(frustumPlanes);
  34656. };
  34657. /**
  34658. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  34659. * Boolean returned.
  34660. */
  34661. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  34662. var boundingInfo = this.getBoundingInfo();
  34663. if (!boundingInfo) {
  34664. return false;
  34665. }
  34666. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  34667. };
  34668. /**
  34669. * Renders the submesh.
  34670. * Returns it.
  34671. */
  34672. SubMesh.prototype.render = function (enableAlphaMode) {
  34673. this._renderingMesh.render(this, enableAlphaMode);
  34674. return this;
  34675. };
  34676. /**
  34677. * Returns a new Index Buffer.
  34678. * Type returned : WebGLBuffer.
  34679. */
  34680. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  34681. if (!this._linesIndexBuffer) {
  34682. var linesIndices = [];
  34683. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34684. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  34685. }
  34686. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  34687. this.linesIndexCount = linesIndices.length;
  34688. }
  34689. return this._linesIndexBuffer;
  34690. };
  34691. /**
  34692. * True is the passed Ray intersects the submesh bounding box.
  34693. * Boolean returned.
  34694. */
  34695. SubMesh.prototype.canIntersects = function (ray) {
  34696. var boundingInfo = this.getBoundingInfo();
  34697. if (!boundingInfo) {
  34698. return false;
  34699. }
  34700. return ray.intersectsBox(boundingInfo.boundingBox);
  34701. };
  34702. /**
  34703. * Returns an object IntersectionInfo.
  34704. */
  34705. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  34706. var intersectInfo = null;
  34707. var material = this.getMaterial();
  34708. if (!material) {
  34709. return null;
  34710. }
  34711. switch (material.fillMode) {
  34712. case BABYLON.Material.PointListDrawMode:
  34713. case BABYLON.Material.LineListDrawMode:
  34714. case BABYLON.Material.LineLoopDrawMode:
  34715. case BABYLON.Material.LineStripDrawMode:
  34716. case BABYLON.Material.TriangleFanDrawMode:
  34717. case BABYLON.Material.TriangleStripDrawMode:
  34718. return null;
  34719. }
  34720. // LineMesh first as it's also a Mesh...
  34721. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  34722. var lineMesh = this._mesh;
  34723. // Line test
  34724. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  34725. var p0 = positions[indices[index]];
  34726. var p1 = positions[indices[index + 1]];
  34727. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  34728. if (length < 0) {
  34729. continue;
  34730. }
  34731. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  34732. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  34733. if (fastCheck) {
  34734. break;
  34735. }
  34736. }
  34737. }
  34738. }
  34739. else {
  34740. // Triangles test
  34741. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34742. var p0 = positions[indices[index]];
  34743. var p1 = positions[indices[index + 1]];
  34744. var p2 = positions[indices[index + 2]];
  34745. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  34746. if (currentIntersectInfo) {
  34747. if (currentIntersectInfo.distance < 0) {
  34748. continue;
  34749. }
  34750. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  34751. intersectInfo = currentIntersectInfo;
  34752. intersectInfo.faceId = index / 3;
  34753. if (fastCheck) {
  34754. break;
  34755. }
  34756. }
  34757. }
  34758. }
  34759. }
  34760. return intersectInfo;
  34761. };
  34762. SubMesh.prototype._rebuild = function () {
  34763. if (this._linesIndexBuffer) {
  34764. this._linesIndexBuffer = null;
  34765. }
  34766. };
  34767. // Clone
  34768. /**
  34769. * Creates a new Submesh from the passed Mesh.
  34770. */
  34771. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  34772. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  34773. if (!this.IsGlobal) {
  34774. var boundingInfo = this.getBoundingInfo();
  34775. if (!boundingInfo) {
  34776. return result;
  34777. }
  34778. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  34779. }
  34780. return result;
  34781. };
  34782. // Dispose
  34783. /**
  34784. * Disposes the Submesh.
  34785. * Returns nothing.
  34786. */
  34787. SubMesh.prototype.dispose = function () {
  34788. if (this._linesIndexBuffer) {
  34789. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  34790. this._linesIndexBuffer = null;
  34791. }
  34792. // Remove from mesh
  34793. var index = this._mesh.subMeshes.indexOf(this);
  34794. this._mesh.subMeshes.splice(index, 1);
  34795. };
  34796. // Statics
  34797. /**
  34798. * Creates a new Submesh from the passed parameters :
  34799. * - materialIndex (integer) : the index of the main mesh material.
  34800. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  34801. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  34802. * - mesh (Mesh) : the main mesh to create the submesh from.
  34803. * - renderingMesh (optional Mesh) : rendering mesh.
  34804. */
  34805. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  34806. var minVertexIndex = Number.MAX_VALUE;
  34807. var maxVertexIndex = -Number.MAX_VALUE;
  34808. renderingMesh = (renderingMesh || mesh);
  34809. var indices = renderingMesh.getIndices();
  34810. for (var index = startIndex; index < startIndex + indexCount; index++) {
  34811. var vertexIndex = indices[index];
  34812. if (vertexIndex < minVertexIndex)
  34813. minVertexIndex = vertexIndex;
  34814. if (vertexIndex > maxVertexIndex)
  34815. maxVertexIndex = vertexIndex;
  34816. }
  34817. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  34818. };
  34819. return SubMesh;
  34820. }(BaseSubMesh));
  34821. BABYLON.SubMesh = SubMesh;
  34822. })(BABYLON || (BABYLON = {}));
  34823. //# sourceMappingURL=babylon.subMesh.js.map
  34824. var __assign = (this && this.__assign) || Object.assign || function(t) {
  34825. for (var s, i = 1, n = arguments.length; i < n; i++) {
  34826. s = arguments[i];
  34827. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  34828. t[p] = s[p];
  34829. }
  34830. return t;
  34831. };
  34832. var BABYLON;
  34833. (function (BABYLON) {
  34834. /**
  34835. * Manages the defines for the Material
  34836. */
  34837. var MaterialDefines = /** @class */ (function () {
  34838. function MaterialDefines() {
  34839. this._isDirty = true;
  34840. /** @hidden */
  34841. this._areLightsDirty = true;
  34842. /** @hidden */
  34843. this._areAttributesDirty = true;
  34844. /** @hidden */
  34845. this._areTexturesDirty = true;
  34846. /** @hidden */
  34847. this._areFresnelDirty = true;
  34848. /** @hidden */
  34849. this._areMiscDirty = true;
  34850. /** @hidden */
  34851. this._areImageProcessingDirty = true;
  34852. /** @hidden */
  34853. this._normals = false;
  34854. /** @hidden */
  34855. this._uvs = false;
  34856. /** @hidden */
  34857. this._needNormals = false;
  34858. /** @hidden */
  34859. this._needUVs = false;
  34860. }
  34861. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  34862. /**
  34863. * Specifies if the material needs to be re-calculated
  34864. */
  34865. get: function () {
  34866. return this._isDirty;
  34867. },
  34868. enumerable: true,
  34869. configurable: true
  34870. });
  34871. /**
  34872. * Marks the material to indicate that it has been re-calculated
  34873. */
  34874. MaterialDefines.prototype.markAsProcessed = function () {
  34875. this._isDirty = false;
  34876. this._areAttributesDirty = false;
  34877. this._areTexturesDirty = false;
  34878. this._areFresnelDirty = false;
  34879. this._areLightsDirty = false;
  34880. this._areMiscDirty = false;
  34881. this._areImageProcessingDirty = false;
  34882. };
  34883. /**
  34884. * Marks the material to indicate that it needs to be re-calculated
  34885. */
  34886. MaterialDefines.prototype.markAsUnprocessed = function () {
  34887. this._isDirty = true;
  34888. };
  34889. /**
  34890. * Marks the material to indicate all of its defines need to be re-calculated
  34891. */
  34892. MaterialDefines.prototype.markAllAsDirty = function () {
  34893. this._areTexturesDirty = true;
  34894. this._areAttributesDirty = true;
  34895. this._areLightsDirty = true;
  34896. this._areFresnelDirty = true;
  34897. this._areMiscDirty = true;
  34898. this._areImageProcessingDirty = true;
  34899. this._isDirty = true;
  34900. };
  34901. /**
  34902. * Marks the material to indicate that image processing needs to be re-calculated
  34903. */
  34904. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  34905. this._areImageProcessingDirty = true;
  34906. this._isDirty = true;
  34907. };
  34908. /**
  34909. * Marks the material to indicate the lights need to be re-calculated
  34910. */
  34911. MaterialDefines.prototype.markAsLightDirty = function () {
  34912. this._areLightsDirty = true;
  34913. this._isDirty = true;
  34914. };
  34915. /**
  34916. * Marks the attribute state as changed
  34917. */
  34918. MaterialDefines.prototype.markAsAttributesDirty = function () {
  34919. this._areAttributesDirty = true;
  34920. this._isDirty = true;
  34921. };
  34922. /**
  34923. * Marks the texture state as changed
  34924. */
  34925. MaterialDefines.prototype.markAsTexturesDirty = function () {
  34926. this._areTexturesDirty = true;
  34927. this._isDirty = true;
  34928. };
  34929. /**
  34930. * Marks the fresnel state as changed
  34931. */
  34932. MaterialDefines.prototype.markAsFresnelDirty = function () {
  34933. this._areFresnelDirty = true;
  34934. this._isDirty = true;
  34935. };
  34936. /**
  34937. * Marks the misc state as changed
  34938. */
  34939. MaterialDefines.prototype.markAsMiscDirty = function () {
  34940. this._areMiscDirty = true;
  34941. this._isDirty = true;
  34942. };
  34943. /**
  34944. * Rebuilds the material defines
  34945. */
  34946. MaterialDefines.prototype.rebuild = function () {
  34947. if (this._keys) {
  34948. delete this._keys;
  34949. }
  34950. this._keys = [];
  34951. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  34952. var key = _a[_i];
  34953. if (key[0] === "_") {
  34954. continue;
  34955. }
  34956. this._keys.push(key);
  34957. }
  34958. };
  34959. /**
  34960. * Specifies if two material defines are equal
  34961. * @param other - A material define instance to compare to
  34962. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  34963. */
  34964. MaterialDefines.prototype.isEqual = function (other) {
  34965. if (this._keys.length !== other._keys.length) {
  34966. return false;
  34967. }
  34968. for (var index = 0; index < this._keys.length; index++) {
  34969. var prop = this._keys[index];
  34970. if (this[prop] !== other[prop]) {
  34971. return false;
  34972. }
  34973. }
  34974. return true;
  34975. };
  34976. /**
  34977. * Clones this instance's defines to another instance
  34978. * @param other - material defines to clone values to
  34979. */
  34980. MaterialDefines.prototype.cloneTo = function (other) {
  34981. if (this._keys.length !== other._keys.length) {
  34982. other._keys = this._keys.slice(0);
  34983. }
  34984. for (var index = 0; index < this._keys.length; index++) {
  34985. var prop = this._keys[index];
  34986. other[prop] = this[prop];
  34987. }
  34988. };
  34989. /**
  34990. * Resets the material define values
  34991. */
  34992. MaterialDefines.prototype.reset = function () {
  34993. for (var index = 0; index < this._keys.length; index++) {
  34994. var prop = this._keys[index];
  34995. var type = typeof this[prop];
  34996. switch (type) {
  34997. case "number":
  34998. this[prop] = 0;
  34999. break;
  35000. case "string":
  35001. this[prop] = "";
  35002. break;
  35003. default:
  35004. this[prop] = false;
  35005. break;
  35006. }
  35007. }
  35008. };
  35009. /**
  35010. * Converts the material define values to a string
  35011. * @returns - String of material define information
  35012. */
  35013. MaterialDefines.prototype.toString = function () {
  35014. var result = "";
  35015. for (var index = 0; index < this._keys.length; index++) {
  35016. var prop = this._keys[index];
  35017. var value = this[prop];
  35018. var type = typeof value;
  35019. switch (type) {
  35020. case "number":
  35021. case "string":
  35022. result += "#define " + prop + " " + value + "\n";
  35023. break;
  35024. default:
  35025. if (value) {
  35026. result += "#define " + prop + "\n";
  35027. }
  35028. break;
  35029. }
  35030. }
  35031. return result;
  35032. };
  35033. return MaterialDefines;
  35034. }());
  35035. BABYLON.MaterialDefines = MaterialDefines;
  35036. /**
  35037. * Base class for the main features of a material in Babylon.js
  35038. */
  35039. var Material = /** @class */ (function () {
  35040. /**
  35041. * Creates a material instance
  35042. * @param name defines the name of the material
  35043. * @param scene defines the scene to reference
  35044. * @param doNotAdd specifies if the material should be added to the scene
  35045. */
  35046. function Material(name, scene, doNotAdd) {
  35047. /**
  35048. * Specifies if the ready state should be checked on each call
  35049. */
  35050. this.checkReadyOnEveryCall = false;
  35051. /**
  35052. * Specifies if the ready state should be checked once
  35053. */
  35054. this.checkReadyOnlyOnce = false;
  35055. /**
  35056. * The state of the material
  35057. */
  35058. this.state = "";
  35059. /**
  35060. * The alpha value of the material
  35061. */
  35062. this._alpha = 1.0;
  35063. /**
  35064. * Specifies if back face culling is enabled
  35065. */
  35066. this._backFaceCulling = true;
  35067. /**
  35068. * Specifies if the material should be serialized
  35069. */
  35070. this.doNotSerialize = false;
  35071. /**
  35072. * Specifies if the effect should be stored on sub meshes
  35073. */
  35074. this.storeEffectOnSubMeshes = false;
  35075. /**
  35076. * An event triggered when the material is disposed
  35077. */
  35078. this.onDisposeObservable = new BABYLON.Observable();
  35079. /**
  35080. * An event triggered when the material is bound
  35081. */
  35082. this.onBindObservable = new BABYLON.Observable();
  35083. /**
  35084. * An event triggered when the material is unbound
  35085. */
  35086. this.onUnBindObservable = new BABYLON.Observable();
  35087. /**
  35088. * Stores the value of the alpha mode
  35089. */
  35090. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  35091. /**
  35092. * Stores the state of the need depth pre-pass value
  35093. */
  35094. this._needDepthPrePass = false;
  35095. /**
  35096. * Specifies if depth writing should be disabled
  35097. */
  35098. this.disableDepthWrite = false;
  35099. /**
  35100. * Specifies if depth writing should be forced
  35101. */
  35102. this.forceDepthWrite = false;
  35103. /**
  35104. * Specifies if there should be a separate pass for culling
  35105. */
  35106. this.separateCullingPass = false;
  35107. /**
  35108. * Stores the state specifing if fog should be enabled
  35109. */
  35110. this._fogEnabled = true;
  35111. /**
  35112. * Stores the size of points
  35113. */
  35114. this.pointSize = 1.0;
  35115. /**
  35116. * Stores the z offset value
  35117. */
  35118. this.zOffset = 0;
  35119. /**
  35120. * Specifies if the material was previously ready
  35121. */
  35122. this._wasPreviouslyReady = false;
  35123. /**
  35124. * Stores the fill mode state
  35125. */
  35126. this._fillMode = Material.TriangleFillMode;
  35127. this.name = name;
  35128. this.id = name || BABYLON.Tools.RandomId();
  35129. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  35130. this.uniqueId = this._scene.getUniqueId();
  35131. if (this._scene.useRightHandedSystem) {
  35132. this.sideOrientation = Material.ClockWiseSideOrientation;
  35133. }
  35134. else {
  35135. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  35136. }
  35137. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  35138. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  35139. if (!doNotAdd) {
  35140. this._scene.materials.push(this);
  35141. }
  35142. }
  35143. Object.defineProperty(Material, "TriangleFillMode", {
  35144. /**
  35145. * Returns the triangle fill mode
  35146. */
  35147. get: function () {
  35148. return Material._TriangleFillMode;
  35149. },
  35150. enumerable: true,
  35151. configurable: true
  35152. });
  35153. Object.defineProperty(Material, "WireFrameFillMode", {
  35154. /**
  35155. * Returns the wireframe mode
  35156. */
  35157. get: function () {
  35158. return Material._WireFrameFillMode;
  35159. },
  35160. enumerable: true,
  35161. configurable: true
  35162. });
  35163. Object.defineProperty(Material, "PointFillMode", {
  35164. /**
  35165. * Returns the point fill mode
  35166. */
  35167. get: function () {
  35168. return Material._PointFillMode;
  35169. },
  35170. enumerable: true,
  35171. configurable: true
  35172. });
  35173. Object.defineProperty(Material, "PointListDrawMode", {
  35174. /**
  35175. * Returns the point list draw mode
  35176. */
  35177. get: function () {
  35178. return Material._PointListDrawMode;
  35179. },
  35180. enumerable: true,
  35181. configurable: true
  35182. });
  35183. Object.defineProperty(Material, "LineListDrawMode", {
  35184. /**
  35185. * Returns the line list draw mode
  35186. */
  35187. get: function () {
  35188. return Material._LineListDrawMode;
  35189. },
  35190. enumerable: true,
  35191. configurable: true
  35192. });
  35193. Object.defineProperty(Material, "LineLoopDrawMode", {
  35194. /**
  35195. * Returns the line loop draw mode
  35196. */
  35197. get: function () {
  35198. return Material._LineLoopDrawMode;
  35199. },
  35200. enumerable: true,
  35201. configurable: true
  35202. });
  35203. Object.defineProperty(Material, "LineStripDrawMode", {
  35204. /**
  35205. * Returns the line strip draw mode
  35206. */
  35207. get: function () {
  35208. return Material._LineStripDrawMode;
  35209. },
  35210. enumerable: true,
  35211. configurable: true
  35212. });
  35213. Object.defineProperty(Material, "TriangleStripDrawMode", {
  35214. /**
  35215. * Returns the triangle strip draw mode
  35216. */
  35217. get: function () {
  35218. return Material._TriangleStripDrawMode;
  35219. },
  35220. enumerable: true,
  35221. configurable: true
  35222. });
  35223. Object.defineProperty(Material, "TriangleFanDrawMode", {
  35224. /**
  35225. * Returns the triangle fan draw mode
  35226. */
  35227. get: function () {
  35228. return Material._TriangleFanDrawMode;
  35229. },
  35230. enumerable: true,
  35231. configurable: true
  35232. });
  35233. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  35234. /**
  35235. * Returns the clock-wise side orientation
  35236. */
  35237. get: function () {
  35238. return Material._ClockWiseSideOrientation;
  35239. },
  35240. enumerable: true,
  35241. configurable: true
  35242. });
  35243. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  35244. /**
  35245. * Returns the counter clock-wise side orientation
  35246. */
  35247. get: function () {
  35248. return Material._CounterClockWiseSideOrientation;
  35249. },
  35250. enumerable: true,
  35251. configurable: true
  35252. });
  35253. Object.defineProperty(Material, "TextureDirtyFlag", {
  35254. /**
  35255. * Returns the dirty texture flag value
  35256. */
  35257. get: function () {
  35258. return Material._TextureDirtyFlag;
  35259. },
  35260. enumerable: true,
  35261. configurable: true
  35262. });
  35263. Object.defineProperty(Material, "LightDirtyFlag", {
  35264. /**
  35265. * Returns the dirty light flag value
  35266. */
  35267. get: function () {
  35268. return Material._LightDirtyFlag;
  35269. },
  35270. enumerable: true,
  35271. configurable: true
  35272. });
  35273. Object.defineProperty(Material, "FresnelDirtyFlag", {
  35274. /**
  35275. * Returns the dirty fresnel flag value
  35276. */
  35277. get: function () {
  35278. return Material._FresnelDirtyFlag;
  35279. },
  35280. enumerable: true,
  35281. configurable: true
  35282. });
  35283. Object.defineProperty(Material, "AttributesDirtyFlag", {
  35284. /**
  35285. * Returns the dirty attributes flag value
  35286. */
  35287. get: function () {
  35288. return Material._AttributesDirtyFlag;
  35289. },
  35290. enumerable: true,
  35291. configurable: true
  35292. });
  35293. Object.defineProperty(Material, "MiscDirtyFlag", {
  35294. /**
  35295. * Returns the dirty misc flag value
  35296. */
  35297. get: function () {
  35298. return Material._MiscDirtyFlag;
  35299. },
  35300. enumerable: true,
  35301. configurable: true
  35302. });
  35303. Object.defineProperty(Material.prototype, "alpha", {
  35304. /**
  35305. * Gets the alpha value of the material
  35306. */
  35307. get: function () {
  35308. return this._alpha;
  35309. },
  35310. /**
  35311. * Sets the alpha value of the material
  35312. */
  35313. set: function (value) {
  35314. if (this._alpha === value) {
  35315. return;
  35316. }
  35317. this._alpha = value;
  35318. this.markAsDirty(Material.MiscDirtyFlag);
  35319. },
  35320. enumerable: true,
  35321. configurable: true
  35322. });
  35323. Object.defineProperty(Material.prototype, "backFaceCulling", {
  35324. /**
  35325. * Gets the back-face culling state
  35326. */
  35327. get: function () {
  35328. return this._backFaceCulling;
  35329. },
  35330. /**
  35331. * Sets the back-face culling state
  35332. */
  35333. set: function (value) {
  35334. if (this._backFaceCulling === value) {
  35335. return;
  35336. }
  35337. this._backFaceCulling = value;
  35338. this.markAsDirty(Material.TextureDirtyFlag);
  35339. },
  35340. enumerable: true,
  35341. configurable: true
  35342. });
  35343. Object.defineProperty(Material.prototype, "onDispose", {
  35344. /**
  35345. * Called during a dispose event
  35346. */
  35347. set: function (callback) {
  35348. if (this._onDisposeObserver) {
  35349. this.onDisposeObservable.remove(this._onDisposeObserver);
  35350. }
  35351. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  35352. },
  35353. enumerable: true,
  35354. configurable: true
  35355. });
  35356. Object.defineProperty(Material.prototype, "onBind", {
  35357. /**
  35358. * Called during a bind event
  35359. */
  35360. set: function (callback) {
  35361. if (this._onBindObserver) {
  35362. this.onBindObservable.remove(this._onBindObserver);
  35363. }
  35364. this._onBindObserver = this.onBindObservable.add(callback);
  35365. },
  35366. enumerable: true,
  35367. configurable: true
  35368. });
  35369. Object.defineProperty(Material.prototype, "alphaMode", {
  35370. /**
  35371. * Gets the value of the alpha mode
  35372. */
  35373. get: function () {
  35374. return this._alphaMode;
  35375. },
  35376. /**
  35377. * Sets the value of the alpha mode.
  35378. *
  35379. * | Value | Type | Description |
  35380. * | --- | --- | --- |
  35381. * | 0 | ALPHA_DISABLE | |
  35382. * | 1 | ALPHA_ADD | |
  35383. * | 2 | ALPHA_COMBINE | |
  35384. * | 3 | ALPHA_SUBTRACT | |
  35385. * | 4 | ALPHA_MULTIPLY | |
  35386. * | 5 | ALPHA_MAXIMIZED | |
  35387. * | 6 | ALPHA_ONEONE | |
  35388. * | 7 | ALPHA_PREMULTIPLIED | |
  35389. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  35390. * | 9 | ALPHA_INTERPOLATE | |
  35391. * | 10 | ALPHA_SCREENMODE | |
  35392. *
  35393. */
  35394. set: function (value) {
  35395. if (this._alphaMode === value) {
  35396. return;
  35397. }
  35398. this._alphaMode = value;
  35399. this.markAsDirty(Material.TextureDirtyFlag);
  35400. },
  35401. enumerable: true,
  35402. configurable: true
  35403. });
  35404. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  35405. /**
  35406. * Gets the depth pre-pass value
  35407. */
  35408. get: function () {
  35409. return this._needDepthPrePass;
  35410. },
  35411. /**
  35412. * Sets the need depth pre-pass value
  35413. */
  35414. set: function (value) {
  35415. if (this._needDepthPrePass === value) {
  35416. return;
  35417. }
  35418. this._needDepthPrePass = value;
  35419. if (this._needDepthPrePass) {
  35420. this.checkReadyOnEveryCall = true;
  35421. }
  35422. },
  35423. enumerable: true,
  35424. configurable: true
  35425. });
  35426. Object.defineProperty(Material.prototype, "fogEnabled", {
  35427. /**
  35428. * Gets the value of the fog enabled state
  35429. */
  35430. get: function () {
  35431. return this._fogEnabled;
  35432. },
  35433. /**
  35434. * Sets the state for enabling fog
  35435. */
  35436. set: function (value) {
  35437. if (this._fogEnabled === value) {
  35438. return;
  35439. }
  35440. this._fogEnabled = value;
  35441. this.markAsDirty(Material.MiscDirtyFlag);
  35442. },
  35443. enumerable: true,
  35444. configurable: true
  35445. });
  35446. Object.defineProperty(Material.prototype, "wireframe", {
  35447. /**
  35448. * Gets a value specifying if wireframe mode is enabled
  35449. */
  35450. get: function () {
  35451. switch (this._fillMode) {
  35452. case Material.WireFrameFillMode:
  35453. case Material.LineListDrawMode:
  35454. case Material.LineLoopDrawMode:
  35455. case Material.LineStripDrawMode:
  35456. return true;
  35457. }
  35458. return this._scene.forceWireframe;
  35459. },
  35460. /**
  35461. * Sets the state of wireframe mode
  35462. */
  35463. set: function (value) {
  35464. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  35465. },
  35466. enumerable: true,
  35467. configurable: true
  35468. });
  35469. Object.defineProperty(Material.prototype, "pointsCloud", {
  35470. /**
  35471. * Gets the value specifying if point clouds are enabled
  35472. */
  35473. get: function () {
  35474. switch (this._fillMode) {
  35475. case Material.PointFillMode:
  35476. case Material.PointListDrawMode:
  35477. return true;
  35478. }
  35479. return this._scene.forcePointsCloud;
  35480. },
  35481. /**
  35482. * Sets the state of point cloud mode
  35483. */
  35484. set: function (value) {
  35485. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  35486. },
  35487. enumerable: true,
  35488. configurable: true
  35489. });
  35490. Object.defineProperty(Material.prototype, "fillMode", {
  35491. /**
  35492. * Gets the material fill mode
  35493. */
  35494. get: function () {
  35495. return this._fillMode;
  35496. },
  35497. /**
  35498. * Sets the material fill mode
  35499. */
  35500. set: function (value) {
  35501. if (this._fillMode === value) {
  35502. return;
  35503. }
  35504. this._fillMode = value;
  35505. this.markAsDirty(Material.MiscDirtyFlag);
  35506. },
  35507. enumerable: true,
  35508. configurable: true
  35509. });
  35510. /**
  35511. * Returns a string representation of the current material
  35512. * @param fullDetails defines a boolean indicating which levels of logging is desired
  35513. * @returns a string with material information
  35514. */
  35515. Material.prototype.toString = function (fullDetails) {
  35516. var ret = "Name: " + this.name;
  35517. if (fullDetails) {
  35518. }
  35519. return ret;
  35520. };
  35521. /**
  35522. * Gets the class name of the material
  35523. * @returns a string with the class name of the material
  35524. */
  35525. Material.prototype.getClassName = function () {
  35526. return "Material";
  35527. };
  35528. Object.defineProperty(Material.prototype, "isFrozen", {
  35529. /**
  35530. * Specifies if updates for the material been locked
  35531. */
  35532. get: function () {
  35533. return this.checkReadyOnlyOnce;
  35534. },
  35535. enumerable: true,
  35536. configurable: true
  35537. });
  35538. /**
  35539. * Locks updates for the material
  35540. */
  35541. Material.prototype.freeze = function () {
  35542. this.checkReadyOnlyOnce = true;
  35543. };
  35544. /**
  35545. * Unlocks updates for the material
  35546. */
  35547. Material.prototype.unfreeze = function () {
  35548. this.checkReadyOnlyOnce = false;
  35549. };
  35550. /**
  35551. * Specifies if the material is ready to be used
  35552. * @param mesh defines the mesh to check
  35553. * @param useInstances specifies if instances should be used
  35554. * @returns a boolean indicating if the material is ready to be used
  35555. */
  35556. Material.prototype.isReady = function (mesh, useInstances) {
  35557. return true;
  35558. };
  35559. /**
  35560. * Specifies that the submesh is ready to be used
  35561. * @param mesh defines the mesh to check
  35562. * @param subMesh defines which submesh to check
  35563. * @param useInstances specifies that instances should be used
  35564. * @returns a boolean indicating that the submesh is ready or not
  35565. */
  35566. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  35567. return false;
  35568. };
  35569. /**
  35570. * Returns the material effect
  35571. * @returns the effect associated with the material
  35572. */
  35573. Material.prototype.getEffect = function () {
  35574. return this._effect;
  35575. };
  35576. /**
  35577. * Returns the current scene
  35578. * @returns a Scene
  35579. */
  35580. Material.prototype.getScene = function () {
  35581. return this._scene;
  35582. };
  35583. /**
  35584. * Specifies if the material will require alpha blending
  35585. * @returns a boolean specifying if alpha blending is needed
  35586. */
  35587. Material.prototype.needAlphaBlending = function () {
  35588. return (this.alpha < 1.0);
  35589. };
  35590. /**
  35591. * Specifies if the mesh will require alpha blending
  35592. * @param mesh defines the mesh to check
  35593. * @returns a boolean specifying if alpha blending is needed for the mesh
  35594. */
  35595. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  35596. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  35597. };
  35598. /**
  35599. * Specifies if this material should be rendered in alpha test mode
  35600. * @returns a boolean specifying if an alpha test is needed.
  35601. */
  35602. Material.prototype.needAlphaTesting = function () {
  35603. return false;
  35604. };
  35605. /**
  35606. * Gets the texture used for the alpha test
  35607. * @returns the texture to use for alpha testing
  35608. */
  35609. Material.prototype.getAlphaTestTexture = function () {
  35610. return null;
  35611. };
  35612. /**
  35613. * Marks the material to indicate that it needs to be re-calculated
  35614. */
  35615. Material.prototype.markDirty = function () {
  35616. this._wasPreviouslyReady = false;
  35617. };
  35618. /** @hidden */
  35619. Material.prototype._preBind = function (effect, overrideOrientation) {
  35620. if (overrideOrientation === void 0) { overrideOrientation = null; }
  35621. var engine = this._scene.getEngine();
  35622. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  35623. var reverse = orientation === Material.ClockWiseSideOrientation;
  35624. engine.enableEffect(effect ? effect : this._effect);
  35625. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  35626. return reverse;
  35627. };
  35628. /**
  35629. * Binds the material to the mesh
  35630. * @param world defines the world transformation matrix
  35631. * @param mesh defines the mesh to bind the material to
  35632. */
  35633. Material.prototype.bind = function (world, mesh) {
  35634. };
  35635. /**
  35636. * Binds the submesh to the material
  35637. * @param world defines the world transformation matrix
  35638. * @param mesh defines the mesh containing the submesh
  35639. * @param subMesh defines the submesh to bind the material to
  35640. */
  35641. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35642. };
  35643. /**
  35644. * Binds the world matrix to the material
  35645. * @param world defines the world transformation matrix
  35646. */
  35647. Material.prototype.bindOnlyWorldMatrix = function (world) {
  35648. };
  35649. /**
  35650. * Binds the scene's uniform buffer to the effect.
  35651. * @param effect defines the effect to bind to the scene uniform buffer
  35652. * @param sceneUbo defines the uniform buffer storing scene data
  35653. */
  35654. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  35655. sceneUbo.bindToEffect(effect, "Scene");
  35656. };
  35657. /**
  35658. * Binds the view matrix to the effect
  35659. * @param effect defines the effect to bind the view matrix to
  35660. */
  35661. Material.prototype.bindView = function (effect) {
  35662. if (!this._useUBO) {
  35663. effect.setMatrix("view", this.getScene().getViewMatrix());
  35664. }
  35665. else {
  35666. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35667. }
  35668. };
  35669. /**
  35670. * Binds the view projection matrix to the effect
  35671. * @param effect defines the effect to bind the view projection matrix to
  35672. */
  35673. Material.prototype.bindViewProjection = function (effect) {
  35674. if (!this._useUBO) {
  35675. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  35676. }
  35677. else {
  35678. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35679. }
  35680. };
  35681. /**
  35682. * Specifies if material alpha testing should be turned on for the mesh
  35683. * @param mesh defines the mesh to check
  35684. */
  35685. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  35686. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  35687. };
  35688. /**
  35689. * Processes to execute after binding the material to a mesh
  35690. * @param mesh defines the rendered mesh
  35691. */
  35692. Material.prototype._afterBind = function (mesh) {
  35693. this._scene._cachedMaterial = this;
  35694. if (mesh) {
  35695. this._scene._cachedVisibility = mesh.visibility;
  35696. }
  35697. else {
  35698. this._scene._cachedVisibility = 1;
  35699. }
  35700. if (mesh) {
  35701. this.onBindObservable.notifyObservers(mesh);
  35702. }
  35703. if (this.disableDepthWrite) {
  35704. var engine = this._scene.getEngine();
  35705. this._cachedDepthWriteState = engine.getDepthWrite();
  35706. engine.setDepthWrite(false);
  35707. }
  35708. };
  35709. /**
  35710. * Unbinds the material from the mesh
  35711. */
  35712. Material.prototype.unbind = function () {
  35713. this.onUnBindObservable.notifyObservers(this);
  35714. if (this.disableDepthWrite) {
  35715. var engine = this._scene.getEngine();
  35716. engine.setDepthWrite(this._cachedDepthWriteState);
  35717. }
  35718. };
  35719. /**
  35720. * Gets the active textures from the material
  35721. * @returns an array of textures
  35722. */
  35723. Material.prototype.getActiveTextures = function () {
  35724. return [];
  35725. };
  35726. /**
  35727. * Specifies if the material uses a texture
  35728. * @param texture defines the texture to check against the material
  35729. * @returns a boolean specifying if the material uses the texture
  35730. */
  35731. Material.prototype.hasTexture = function (texture) {
  35732. return false;
  35733. };
  35734. /**
  35735. * Makes a duplicate of the material, and gives it a new name
  35736. * @param name defines the new name for the duplicated material
  35737. * @returns the cloned material
  35738. */
  35739. Material.prototype.clone = function (name) {
  35740. return null;
  35741. };
  35742. /**
  35743. * Gets the meshes bound to the material
  35744. * @returns an array of meshes bound to the material
  35745. */
  35746. Material.prototype.getBindedMeshes = function () {
  35747. var result = new Array();
  35748. for (var index = 0; index < this._scene.meshes.length; index++) {
  35749. var mesh = this._scene.meshes[index];
  35750. if (mesh.material === this) {
  35751. result.push(mesh);
  35752. }
  35753. }
  35754. return result;
  35755. };
  35756. /**
  35757. * Force shader compilation
  35758. * @param mesh defines the mesh associated with this material
  35759. * @param onCompiled defines a function to execute once the material is compiled
  35760. * @param options defines the options to configure the compilation
  35761. */
  35762. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  35763. var _this = this;
  35764. var localOptions = __assign({ clipPlane: false }, options);
  35765. var subMesh = new BABYLON.BaseSubMesh();
  35766. var scene = this.getScene();
  35767. var checkReady = function () {
  35768. if (!_this._scene || !_this._scene.getEngine()) {
  35769. return;
  35770. }
  35771. if (subMesh._materialDefines) {
  35772. subMesh._materialDefines._renderId = -1;
  35773. }
  35774. var clipPlaneState = scene.clipPlane;
  35775. if (localOptions.clipPlane) {
  35776. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  35777. }
  35778. if (_this.storeEffectOnSubMeshes) {
  35779. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  35780. if (onCompiled) {
  35781. onCompiled(_this);
  35782. }
  35783. }
  35784. else {
  35785. setTimeout(checkReady, 16);
  35786. }
  35787. }
  35788. else {
  35789. if (_this.isReady(mesh)) {
  35790. if (onCompiled) {
  35791. onCompiled(_this);
  35792. }
  35793. }
  35794. else {
  35795. setTimeout(checkReady, 16);
  35796. }
  35797. }
  35798. if (localOptions.clipPlane) {
  35799. scene.clipPlane = clipPlaneState;
  35800. }
  35801. };
  35802. checkReady();
  35803. };
  35804. /**
  35805. * Force shader compilation
  35806. * @param mesh defines the mesh that will use this material
  35807. * @param options defines additional options for compiling the shaders
  35808. * @returns a promise that resolves when the compilation completes
  35809. */
  35810. Material.prototype.forceCompilationAsync = function (mesh, options) {
  35811. var _this = this;
  35812. return new Promise(function (resolve) {
  35813. _this.forceCompilation(mesh, function () {
  35814. resolve();
  35815. }, options);
  35816. });
  35817. };
  35818. /**
  35819. * Marks a define in the material to indicate that it needs to be re-computed
  35820. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  35821. */
  35822. Material.prototype.markAsDirty = function (flag) {
  35823. if (flag & Material.TextureDirtyFlag) {
  35824. this._markAllSubMeshesAsTexturesDirty();
  35825. }
  35826. if (flag & Material.LightDirtyFlag) {
  35827. this._markAllSubMeshesAsLightsDirty();
  35828. }
  35829. if (flag & Material.FresnelDirtyFlag) {
  35830. this._markAllSubMeshesAsFresnelDirty();
  35831. }
  35832. if (flag & Material.AttributesDirtyFlag) {
  35833. this._markAllSubMeshesAsAttributesDirty();
  35834. }
  35835. if (flag & Material.MiscDirtyFlag) {
  35836. this._markAllSubMeshesAsMiscDirty();
  35837. }
  35838. this.getScene().resetCachedMaterial();
  35839. };
  35840. /**
  35841. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  35842. * @param func defines a function which checks material defines against the submeshes
  35843. */
  35844. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  35845. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  35846. var mesh = _a[_i];
  35847. if (!mesh.subMeshes) {
  35848. continue;
  35849. }
  35850. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  35851. var subMesh = _c[_b];
  35852. if (subMesh.getMaterial() !== this) {
  35853. continue;
  35854. }
  35855. if (!subMesh._materialDefines) {
  35856. continue;
  35857. }
  35858. func(subMesh._materialDefines);
  35859. }
  35860. }
  35861. };
  35862. /**
  35863. * Indicates that image processing needs to be re-calculated for all submeshes
  35864. */
  35865. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  35866. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  35867. };
  35868. /**
  35869. * Indicates that textures need to be re-calculated for all submeshes
  35870. */
  35871. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  35872. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  35873. };
  35874. /**
  35875. * Indicates that fresnel needs to be re-calculated for all submeshes
  35876. */
  35877. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  35878. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  35879. };
  35880. /**
  35881. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  35882. */
  35883. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  35884. this._markAllSubMeshesAsDirty(function (defines) {
  35885. defines.markAsFresnelDirty();
  35886. defines.markAsMiscDirty();
  35887. });
  35888. };
  35889. /**
  35890. * Indicates that lights need to be re-calculated for all submeshes
  35891. */
  35892. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  35893. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  35894. };
  35895. /**
  35896. * Indicates that attributes need to be re-calculated for all submeshes
  35897. */
  35898. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  35899. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  35900. };
  35901. /**
  35902. * Indicates that misc needs to be re-calculated for all submeshes
  35903. */
  35904. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  35905. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  35906. };
  35907. /**
  35908. * Indicates that textures and misc need to be re-calculated for all submeshes
  35909. */
  35910. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  35911. this._markAllSubMeshesAsDirty(function (defines) {
  35912. defines.markAsTexturesDirty();
  35913. defines.markAsMiscDirty();
  35914. });
  35915. };
  35916. /**
  35917. * Disposes the material
  35918. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  35919. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  35920. */
  35921. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35922. // Animations
  35923. this.getScene().stopAnimation(this);
  35924. this.getScene().freeProcessedMaterials();
  35925. // Remove from scene
  35926. var index = this._scene.materials.indexOf(this);
  35927. if (index >= 0) {
  35928. this._scene.materials.splice(index, 1);
  35929. }
  35930. // Remove from meshes
  35931. for (index = 0; index < this._scene.meshes.length; index++) {
  35932. var mesh = this._scene.meshes[index];
  35933. if (mesh.material === this) {
  35934. mesh.material = null;
  35935. if (mesh.geometry) {
  35936. var geometry = (mesh.geometry);
  35937. if (this.storeEffectOnSubMeshes) {
  35938. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  35939. var subMesh = _a[_i];
  35940. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  35941. if (forceDisposeEffect && subMesh._materialEffect) {
  35942. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  35943. }
  35944. }
  35945. }
  35946. else {
  35947. geometry._releaseVertexArrayObject(this._effect);
  35948. }
  35949. }
  35950. }
  35951. }
  35952. this._uniformBuffer.dispose();
  35953. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  35954. if (forceDisposeEffect && this._effect) {
  35955. if (!this.storeEffectOnSubMeshes) {
  35956. this._scene.getEngine()._releaseEffect(this._effect);
  35957. }
  35958. this._effect = null;
  35959. }
  35960. // Callback
  35961. this.onDisposeObservable.notifyObservers(this);
  35962. this.onDisposeObservable.clear();
  35963. this.onBindObservable.clear();
  35964. this.onUnBindObservable.clear();
  35965. };
  35966. /**
  35967. * Serializes this material
  35968. * @returns the serialized material object
  35969. */
  35970. Material.prototype.serialize = function () {
  35971. return BABYLON.SerializationHelper.Serialize(this);
  35972. };
  35973. /**
  35974. * Creates a MultiMaterial from parsed MultiMaterial data.
  35975. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  35976. * @param scene defines the hosting scene
  35977. * @returns a new MultiMaterial
  35978. */
  35979. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  35980. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  35981. multiMaterial.id = parsedMultiMaterial.id;
  35982. if (BABYLON.Tags) {
  35983. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  35984. }
  35985. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  35986. var subMatId = parsedMultiMaterial.materials[matIndex];
  35987. if (subMatId) {
  35988. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  35989. }
  35990. else {
  35991. multiMaterial.subMaterials.push(null);
  35992. }
  35993. }
  35994. return multiMaterial;
  35995. };
  35996. /**
  35997. * Creates a material from parsed material data
  35998. * @param parsedMaterial defines parsed material data
  35999. * @param scene defines the hosting scene
  36000. * @param rootUrl defines the root URL to use to load textures
  36001. * @returns a new material
  36002. */
  36003. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  36004. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  36005. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  36006. }
  36007. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  36008. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  36009. if (!BABYLON.LegacyPBRMaterial) {
  36010. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  36011. return;
  36012. }
  36013. }
  36014. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  36015. return materialType.Parse(parsedMaterial, scene, rootUrl);
  36016. };
  36017. // Triangle views
  36018. Material._TriangleFillMode = 0;
  36019. Material._WireFrameFillMode = 1;
  36020. Material._PointFillMode = 2;
  36021. // Draw modes
  36022. Material._PointListDrawMode = 3;
  36023. Material._LineListDrawMode = 4;
  36024. Material._LineLoopDrawMode = 5;
  36025. Material._LineStripDrawMode = 6;
  36026. Material._TriangleStripDrawMode = 7;
  36027. Material._TriangleFanDrawMode = 8;
  36028. /**
  36029. * Stores the clock-wise side orientation
  36030. */
  36031. Material._ClockWiseSideOrientation = 0;
  36032. /**
  36033. * Stores the counter clock-wise side orientation
  36034. */
  36035. Material._CounterClockWiseSideOrientation = 1;
  36036. /**
  36037. * The dirty texture flag value
  36038. */
  36039. Material._TextureDirtyFlag = 1;
  36040. /**
  36041. * The dirty light flag value
  36042. */
  36043. Material._LightDirtyFlag = 2;
  36044. /**
  36045. * The dirty fresnel flag value
  36046. */
  36047. Material._FresnelDirtyFlag = 4;
  36048. /**
  36049. * The dirty attribute flag value
  36050. */
  36051. Material._AttributesDirtyFlag = 8;
  36052. /**
  36053. * The dirty misc flag value
  36054. */
  36055. Material._MiscDirtyFlag = 16;
  36056. __decorate([
  36057. BABYLON.serialize()
  36058. ], Material.prototype, "id", void 0);
  36059. __decorate([
  36060. BABYLON.serialize()
  36061. ], Material.prototype, "uniqueId", void 0);
  36062. __decorate([
  36063. BABYLON.serialize()
  36064. ], Material.prototype, "name", void 0);
  36065. __decorate([
  36066. BABYLON.serialize()
  36067. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  36068. __decorate([
  36069. BABYLON.serialize()
  36070. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  36071. __decorate([
  36072. BABYLON.serialize()
  36073. ], Material.prototype, "state", void 0);
  36074. __decorate([
  36075. BABYLON.serialize("alpha")
  36076. ], Material.prototype, "_alpha", void 0);
  36077. __decorate([
  36078. BABYLON.serialize("backFaceCulling")
  36079. ], Material.prototype, "_backFaceCulling", void 0);
  36080. __decorate([
  36081. BABYLON.serialize()
  36082. ], Material.prototype, "sideOrientation", void 0);
  36083. __decorate([
  36084. BABYLON.serialize("alphaMode")
  36085. ], Material.prototype, "_alphaMode", void 0);
  36086. __decorate([
  36087. BABYLON.serialize()
  36088. ], Material.prototype, "_needDepthPrePass", void 0);
  36089. __decorate([
  36090. BABYLON.serialize()
  36091. ], Material.prototype, "disableDepthWrite", void 0);
  36092. __decorate([
  36093. BABYLON.serialize()
  36094. ], Material.prototype, "forceDepthWrite", void 0);
  36095. __decorate([
  36096. BABYLON.serialize()
  36097. ], Material.prototype, "separateCullingPass", void 0);
  36098. __decorate([
  36099. BABYLON.serialize("fogEnabled")
  36100. ], Material.prototype, "_fogEnabled", void 0);
  36101. __decorate([
  36102. BABYLON.serialize()
  36103. ], Material.prototype, "pointSize", void 0);
  36104. __decorate([
  36105. BABYLON.serialize()
  36106. ], Material.prototype, "zOffset", void 0);
  36107. __decorate([
  36108. BABYLON.serialize()
  36109. ], Material.prototype, "wireframe", null);
  36110. __decorate([
  36111. BABYLON.serialize()
  36112. ], Material.prototype, "pointsCloud", null);
  36113. __decorate([
  36114. BABYLON.serialize()
  36115. ], Material.prototype, "fillMode", null);
  36116. return Material;
  36117. }());
  36118. BABYLON.Material = Material;
  36119. })(BABYLON || (BABYLON = {}));
  36120. //# sourceMappingURL=babylon.material.js.map
  36121. var BABYLON;
  36122. (function (BABYLON) {
  36123. var UniformBuffer = /** @class */ (function () {
  36124. /**
  36125. * Uniform buffer objects.
  36126. *
  36127. * Handles blocks of uniform on the GPU.
  36128. *
  36129. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  36130. *
  36131. * For more information, please refer to :
  36132. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  36133. */
  36134. function UniformBuffer(engine, data, dynamic) {
  36135. this._engine = engine;
  36136. this._noUBO = !engine.supportsUniformBuffers;
  36137. this._dynamic = dynamic;
  36138. this._data = data || [];
  36139. this._uniformLocations = {};
  36140. this._uniformSizes = {};
  36141. this._uniformLocationPointer = 0;
  36142. this._needSync = false;
  36143. if (this._noUBO) {
  36144. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  36145. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  36146. this.updateFloat = this._updateFloatForEffect;
  36147. this.updateFloat2 = this._updateFloat2ForEffect;
  36148. this.updateFloat3 = this._updateFloat3ForEffect;
  36149. this.updateFloat4 = this._updateFloat4ForEffect;
  36150. this.updateMatrix = this._updateMatrixForEffect;
  36151. this.updateVector3 = this._updateVector3ForEffect;
  36152. this.updateVector4 = this._updateVector4ForEffect;
  36153. this.updateColor3 = this._updateColor3ForEffect;
  36154. this.updateColor4 = this._updateColor4ForEffect;
  36155. }
  36156. else {
  36157. this._engine._uniformBuffers.push(this);
  36158. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  36159. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  36160. this.updateFloat = this._updateFloatForUniform;
  36161. this.updateFloat2 = this._updateFloat2ForUniform;
  36162. this.updateFloat3 = this._updateFloat3ForUniform;
  36163. this.updateFloat4 = this._updateFloat4ForUniform;
  36164. this.updateMatrix = this._updateMatrixForUniform;
  36165. this.updateVector3 = this._updateVector3ForUniform;
  36166. this.updateVector4 = this._updateVector4ForUniform;
  36167. this.updateColor3 = this._updateColor3ForUniform;
  36168. this.updateColor4 = this._updateColor4ForUniform;
  36169. }
  36170. }
  36171. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  36172. // Properties
  36173. /**
  36174. * Indicates if the buffer is using the WebGL2 UBO implementation,
  36175. * or just falling back on setUniformXXX calls.
  36176. */
  36177. get: function () {
  36178. return !this._noUBO;
  36179. },
  36180. enumerable: true,
  36181. configurable: true
  36182. });
  36183. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  36184. /**
  36185. * Indicates if the WebGL underlying uniform buffer is in sync
  36186. * with the javascript cache data.
  36187. */
  36188. get: function () {
  36189. return !this._needSync;
  36190. },
  36191. enumerable: true,
  36192. configurable: true
  36193. });
  36194. /**
  36195. * Indicates if the WebGL underlying uniform buffer is dynamic.
  36196. * Also, a dynamic UniformBuffer will disable cache verification and always
  36197. * update the underlying WebGL uniform buffer to the GPU.
  36198. */
  36199. UniformBuffer.prototype.isDynamic = function () {
  36200. return this._dynamic !== undefined;
  36201. };
  36202. /**
  36203. * The data cache on JS side.
  36204. */
  36205. UniformBuffer.prototype.getData = function () {
  36206. return this._bufferData;
  36207. };
  36208. /**
  36209. * The underlying WebGL Uniform buffer.
  36210. */
  36211. UniformBuffer.prototype.getBuffer = function () {
  36212. return this._buffer;
  36213. };
  36214. /**
  36215. * std140 layout specifies how to align data within an UBO structure.
  36216. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  36217. * for specs.
  36218. */
  36219. UniformBuffer.prototype._fillAlignment = function (size) {
  36220. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  36221. // and 4x4 matrices
  36222. // TODO : change if other types are used
  36223. var alignment;
  36224. if (size <= 2) {
  36225. alignment = size;
  36226. }
  36227. else {
  36228. alignment = 4;
  36229. }
  36230. if ((this._uniformLocationPointer % alignment) !== 0) {
  36231. var oldPointer = this._uniformLocationPointer;
  36232. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  36233. var diff = this._uniformLocationPointer - oldPointer;
  36234. for (var i = 0; i < diff; i++) {
  36235. this._data.push(0);
  36236. }
  36237. }
  36238. };
  36239. /**
  36240. * Adds an uniform in the buffer.
  36241. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  36242. * for the layout to be correct !
  36243. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36244. * @param {number|number[]} size Data size, or data directly.
  36245. */
  36246. UniformBuffer.prototype.addUniform = function (name, size) {
  36247. if (this._noUBO) {
  36248. return;
  36249. }
  36250. if (this._uniformLocations[name] !== undefined) {
  36251. // Already existing uniform
  36252. return;
  36253. }
  36254. // This function must be called in the order of the shader layout !
  36255. // size can be the size of the uniform, or data directly
  36256. var data;
  36257. if (size instanceof Array) {
  36258. data = size;
  36259. size = data.length;
  36260. }
  36261. else {
  36262. size = size;
  36263. data = [];
  36264. // Fill with zeros
  36265. for (var i = 0; i < size; i++) {
  36266. data.push(0);
  36267. }
  36268. }
  36269. this._fillAlignment(size);
  36270. this._uniformSizes[name] = size;
  36271. this._uniformLocations[name] = this._uniformLocationPointer;
  36272. this._uniformLocationPointer += size;
  36273. for (var i = 0; i < size; i++) {
  36274. this._data.push(data[i]);
  36275. }
  36276. this._needSync = true;
  36277. };
  36278. /**
  36279. * Wrapper for addUniform.
  36280. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36281. * @param {Matrix} mat A 4x4 matrix.
  36282. */
  36283. UniformBuffer.prototype.addMatrix = function (name, mat) {
  36284. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  36285. };
  36286. /**
  36287. * Wrapper for addUniform.
  36288. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36289. * @param {number} x
  36290. * @param {number} y
  36291. */
  36292. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  36293. var temp = [x, y];
  36294. this.addUniform(name, temp);
  36295. };
  36296. /**
  36297. * Wrapper for addUniform.
  36298. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36299. * @param {number} x
  36300. * @param {number} y
  36301. * @param {number} z
  36302. */
  36303. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  36304. var temp = [x, y, z];
  36305. this.addUniform(name, temp);
  36306. };
  36307. /**
  36308. * Wrapper for addUniform.
  36309. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36310. * @param {Color3} color
  36311. */
  36312. UniformBuffer.prototype.addColor3 = function (name, color) {
  36313. var temp = new Array();
  36314. color.toArray(temp);
  36315. this.addUniform(name, temp);
  36316. };
  36317. /**
  36318. * Wrapper for addUniform.
  36319. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36320. * @param {Color3} color
  36321. * @param {number} alpha
  36322. */
  36323. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  36324. var temp = new Array();
  36325. color.toArray(temp);
  36326. temp.push(alpha);
  36327. this.addUniform(name, temp);
  36328. };
  36329. /**
  36330. * Wrapper for addUniform.
  36331. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36332. * @param {Vector3} vector
  36333. */
  36334. UniformBuffer.prototype.addVector3 = function (name, vector) {
  36335. var temp = new Array();
  36336. vector.toArray(temp);
  36337. this.addUniform(name, temp);
  36338. };
  36339. /**
  36340. * Wrapper for addUniform.
  36341. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36342. */
  36343. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  36344. this.addUniform(name, 12);
  36345. };
  36346. /**
  36347. * Wrapper for addUniform.
  36348. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36349. */
  36350. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  36351. this.addUniform(name, 8);
  36352. };
  36353. /**
  36354. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  36355. */
  36356. UniformBuffer.prototype.create = function () {
  36357. if (this._noUBO) {
  36358. return;
  36359. }
  36360. if (this._buffer) {
  36361. return; // nothing to do
  36362. }
  36363. // See spec, alignment must be filled as a vec4
  36364. this._fillAlignment(4);
  36365. this._bufferData = new Float32Array(this._data);
  36366. this._rebuild();
  36367. this._needSync = true;
  36368. };
  36369. UniformBuffer.prototype._rebuild = function () {
  36370. if (this._noUBO) {
  36371. return;
  36372. }
  36373. if (this._dynamic) {
  36374. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  36375. }
  36376. else {
  36377. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  36378. }
  36379. };
  36380. /**
  36381. * Updates the WebGL Uniform Buffer on the GPU.
  36382. * If the `dynamic` flag is set to true, no cache comparison is done.
  36383. * Otherwise, the buffer will be updated only if the cache differs.
  36384. */
  36385. UniformBuffer.prototype.update = function () {
  36386. if (!this._buffer) {
  36387. this.create();
  36388. return;
  36389. }
  36390. if (!this._dynamic && !this._needSync) {
  36391. return;
  36392. }
  36393. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  36394. this._needSync = false;
  36395. };
  36396. /**
  36397. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  36398. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36399. * @param {number[]|Float32Array} data Flattened data
  36400. * @param {number} size Size of the data.
  36401. */
  36402. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  36403. var location = this._uniformLocations[uniformName];
  36404. if (location === undefined) {
  36405. if (this._buffer) {
  36406. // Cannot add an uniform if the buffer is already created
  36407. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  36408. return;
  36409. }
  36410. this.addUniform(uniformName, size);
  36411. location = this._uniformLocations[uniformName];
  36412. }
  36413. if (!this._buffer) {
  36414. this.create();
  36415. }
  36416. if (!this._dynamic) {
  36417. // Cache for static uniform buffers
  36418. var changed = false;
  36419. for (var i = 0; i < size; i++) {
  36420. if (this._bufferData[location + i] !== data[i]) {
  36421. changed = true;
  36422. this._bufferData[location + i] = data[i];
  36423. }
  36424. }
  36425. this._needSync = this._needSync || changed;
  36426. }
  36427. else {
  36428. // No cache for dynamic
  36429. for (var i = 0; i < size; i++) {
  36430. this._bufferData[location + i] = data[i];
  36431. }
  36432. }
  36433. };
  36434. // Update methods
  36435. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  36436. // To match std140, matrix must be realigned
  36437. for (var i = 0; i < 3; i++) {
  36438. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  36439. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  36440. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  36441. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36442. }
  36443. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  36444. };
  36445. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  36446. this._currentEffect.setMatrix3x3(name, matrix);
  36447. };
  36448. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  36449. this._currentEffect.setMatrix2x2(name, matrix);
  36450. };
  36451. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  36452. // To match std140, matrix must be realigned
  36453. for (var i = 0; i < 2; i++) {
  36454. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  36455. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  36456. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  36457. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36458. }
  36459. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  36460. };
  36461. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  36462. this._currentEffect.setFloat(name, x);
  36463. };
  36464. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  36465. UniformBuffer._tempBuffer[0] = x;
  36466. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  36467. };
  36468. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  36469. if (suffix === void 0) { suffix = ""; }
  36470. this._currentEffect.setFloat2(name + suffix, x, y);
  36471. };
  36472. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  36473. if (suffix === void 0) { suffix = ""; }
  36474. UniformBuffer._tempBuffer[0] = x;
  36475. UniformBuffer._tempBuffer[1] = y;
  36476. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  36477. };
  36478. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  36479. if (suffix === void 0) { suffix = ""; }
  36480. this._currentEffect.setFloat3(name + suffix, x, y, z);
  36481. };
  36482. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  36483. if (suffix === void 0) { suffix = ""; }
  36484. UniformBuffer._tempBuffer[0] = x;
  36485. UniformBuffer._tempBuffer[1] = y;
  36486. UniformBuffer._tempBuffer[2] = z;
  36487. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36488. };
  36489. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  36490. if (suffix === void 0) { suffix = ""; }
  36491. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  36492. };
  36493. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  36494. if (suffix === void 0) { suffix = ""; }
  36495. UniformBuffer._tempBuffer[0] = x;
  36496. UniformBuffer._tempBuffer[1] = y;
  36497. UniformBuffer._tempBuffer[2] = z;
  36498. UniformBuffer._tempBuffer[3] = w;
  36499. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36500. };
  36501. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  36502. this._currentEffect.setMatrix(name, mat);
  36503. };
  36504. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  36505. this.updateUniform(name, mat.toArray(), 16);
  36506. };
  36507. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  36508. this._currentEffect.setVector3(name, vector);
  36509. };
  36510. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  36511. vector.toArray(UniformBuffer._tempBuffer);
  36512. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36513. };
  36514. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  36515. this._currentEffect.setVector4(name, vector);
  36516. };
  36517. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  36518. vector.toArray(UniformBuffer._tempBuffer);
  36519. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36520. };
  36521. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  36522. if (suffix === void 0) { suffix = ""; }
  36523. this._currentEffect.setColor3(name + suffix, color);
  36524. };
  36525. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  36526. if (suffix === void 0) { suffix = ""; }
  36527. color.toArray(UniformBuffer._tempBuffer);
  36528. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36529. };
  36530. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  36531. if (suffix === void 0) { suffix = ""; }
  36532. this._currentEffect.setColor4(name + suffix, color, alpha);
  36533. };
  36534. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  36535. if (suffix === void 0) { suffix = ""; }
  36536. color.toArray(UniformBuffer._tempBuffer);
  36537. UniformBuffer._tempBuffer[3] = alpha;
  36538. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36539. };
  36540. /**
  36541. * Sets a sampler uniform on the effect.
  36542. * @param {string} name Name of the sampler.
  36543. * @param {Texture} texture
  36544. */
  36545. UniformBuffer.prototype.setTexture = function (name, texture) {
  36546. this._currentEffect.setTexture(name, texture);
  36547. };
  36548. /**
  36549. * Directly updates the value of the uniform in the cache AND on the GPU.
  36550. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36551. * @param {number[]|Float32Array} data Flattened data
  36552. */
  36553. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  36554. this.updateUniform(uniformName, data, data.length);
  36555. this.update();
  36556. };
  36557. /**
  36558. * Binds this uniform buffer to an effect.
  36559. * @param {Effect} effect
  36560. * @param {string} name Name of the uniform block in the shader.
  36561. */
  36562. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  36563. this._currentEffect = effect;
  36564. if (this._noUBO || !this._buffer) {
  36565. return;
  36566. }
  36567. effect.bindUniformBuffer(this._buffer, name);
  36568. };
  36569. /**
  36570. * Disposes the uniform buffer.
  36571. */
  36572. UniformBuffer.prototype.dispose = function () {
  36573. if (this._noUBO) {
  36574. return;
  36575. }
  36576. var index = this._engine._uniformBuffers.indexOf(this);
  36577. if (index !== -1) {
  36578. this._engine._uniformBuffers.splice(index, 1);
  36579. }
  36580. if (!this._buffer) {
  36581. return;
  36582. }
  36583. if (this._engine._releaseBuffer(this._buffer)) {
  36584. this._buffer = null;
  36585. }
  36586. };
  36587. // Pool for avoiding memory leaks
  36588. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  36589. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  36590. return UniformBuffer;
  36591. }());
  36592. BABYLON.UniformBuffer = UniformBuffer;
  36593. })(BABYLON || (BABYLON = {}));
  36594. //# sourceMappingURL=babylon.uniformBuffer.js.map
  36595. var BABYLON;
  36596. (function (BABYLON) {
  36597. /**
  36598. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  36599. */
  36600. var VertexData = /** @class */ (function () {
  36601. function VertexData() {
  36602. }
  36603. /**
  36604. * Uses the passed data array to set the set the values for the specified kind of data
  36605. * @param data a linear array of floating numbers
  36606. * @param kind the type of data that is being set, eg positions, colors etc
  36607. */
  36608. VertexData.prototype.set = function (data, kind) {
  36609. switch (kind) {
  36610. case BABYLON.VertexBuffer.PositionKind:
  36611. this.positions = data;
  36612. break;
  36613. case BABYLON.VertexBuffer.NormalKind:
  36614. this.normals = data;
  36615. break;
  36616. case BABYLON.VertexBuffer.TangentKind:
  36617. this.tangents = data;
  36618. break;
  36619. case BABYLON.VertexBuffer.UVKind:
  36620. this.uvs = data;
  36621. break;
  36622. case BABYLON.VertexBuffer.UV2Kind:
  36623. this.uvs2 = data;
  36624. break;
  36625. case BABYLON.VertexBuffer.UV3Kind:
  36626. this.uvs3 = data;
  36627. break;
  36628. case BABYLON.VertexBuffer.UV4Kind:
  36629. this.uvs4 = data;
  36630. break;
  36631. case BABYLON.VertexBuffer.UV5Kind:
  36632. this.uvs5 = data;
  36633. break;
  36634. case BABYLON.VertexBuffer.UV6Kind:
  36635. this.uvs6 = data;
  36636. break;
  36637. case BABYLON.VertexBuffer.ColorKind:
  36638. this.colors = data;
  36639. break;
  36640. case BABYLON.VertexBuffer.MatricesIndicesKind:
  36641. this.matricesIndices = data;
  36642. break;
  36643. case BABYLON.VertexBuffer.MatricesWeightsKind:
  36644. this.matricesWeights = data;
  36645. break;
  36646. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  36647. this.matricesIndicesExtra = data;
  36648. break;
  36649. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  36650. this.matricesWeightsExtra = data;
  36651. break;
  36652. }
  36653. };
  36654. /**
  36655. * Associates the vertexData to the passed Mesh.
  36656. * Sets it as updatable or not (default `false`)
  36657. * @param mesh the mesh the vertexData is applied to
  36658. * @param updatable when used and having the value true allows new data to update the vertexData
  36659. * @returns the VertexData
  36660. */
  36661. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  36662. this._applyTo(mesh, updatable);
  36663. return this;
  36664. };
  36665. /**
  36666. * Associates the vertexData to the passed Geometry.
  36667. * Sets it as updatable or not (default `false`)
  36668. * @param geometry the geometry the vertexData is applied to
  36669. * @param updatable when used and having the value true allows new data to update the vertexData
  36670. * @returns VertexData
  36671. */
  36672. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  36673. this._applyTo(geometry, updatable);
  36674. return this;
  36675. };
  36676. /**
  36677. * Updates the associated mesh
  36678. * @param mesh the mesh to be updated
  36679. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36680. * @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
  36681. * @returns VertexData
  36682. */
  36683. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  36684. this._update(mesh);
  36685. return this;
  36686. };
  36687. /**
  36688. * Updates the associated geometry
  36689. * @param geometry the geometry to be updated
  36690. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36691. * @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
  36692. * @returns VertexData.
  36693. */
  36694. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  36695. this._update(geometry);
  36696. return this;
  36697. };
  36698. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  36699. if (updatable === void 0) { updatable = false; }
  36700. if (this.positions) {
  36701. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  36702. }
  36703. if (this.normals) {
  36704. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  36705. }
  36706. if (this.tangents) {
  36707. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  36708. }
  36709. if (this.uvs) {
  36710. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  36711. }
  36712. if (this.uvs2) {
  36713. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  36714. }
  36715. if (this.uvs3) {
  36716. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  36717. }
  36718. if (this.uvs4) {
  36719. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  36720. }
  36721. if (this.uvs5) {
  36722. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  36723. }
  36724. if (this.uvs6) {
  36725. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  36726. }
  36727. if (this.colors) {
  36728. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  36729. }
  36730. if (this.matricesIndices) {
  36731. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  36732. }
  36733. if (this.matricesWeights) {
  36734. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  36735. }
  36736. if (this.matricesIndicesExtra) {
  36737. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  36738. }
  36739. if (this.matricesWeightsExtra) {
  36740. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  36741. }
  36742. if (this.indices) {
  36743. meshOrGeometry.setIndices(this.indices, null, updatable);
  36744. }
  36745. else {
  36746. meshOrGeometry.setIndices([], null);
  36747. }
  36748. return this;
  36749. };
  36750. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  36751. if (this.positions) {
  36752. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  36753. }
  36754. if (this.normals) {
  36755. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  36756. }
  36757. if (this.tangents) {
  36758. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  36759. }
  36760. if (this.uvs) {
  36761. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  36762. }
  36763. if (this.uvs2) {
  36764. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  36765. }
  36766. if (this.uvs3) {
  36767. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  36768. }
  36769. if (this.uvs4) {
  36770. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  36771. }
  36772. if (this.uvs5) {
  36773. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  36774. }
  36775. if (this.uvs6) {
  36776. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  36777. }
  36778. if (this.colors) {
  36779. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  36780. }
  36781. if (this.matricesIndices) {
  36782. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  36783. }
  36784. if (this.matricesWeights) {
  36785. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  36786. }
  36787. if (this.matricesIndicesExtra) {
  36788. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  36789. }
  36790. if (this.matricesWeightsExtra) {
  36791. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  36792. }
  36793. if (this.indices) {
  36794. meshOrGeometry.setIndices(this.indices, null);
  36795. }
  36796. return this;
  36797. };
  36798. /**
  36799. * Transforms each position and each normal of the vertexData according to the passed Matrix
  36800. * @param matrix the transforming matrix
  36801. * @returns the VertexData
  36802. */
  36803. VertexData.prototype.transform = function (matrix) {
  36804. var transformed = BABYLON.Vector3.Zero();
  36805. var index;
  36806. if (this.positions) {
  36807. var position = BABYLON.Vector3.Zero();
  36808. for (index = 0; index < this.positions.length; index += 3) {
  36809. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  36810. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  36811. this.positions[index] = transformed.x;
  36812. this.positions[index + 1] = transformed.y;
  36813. this.positions[index + 2] = transformed.z;
  36814. }
  36815. }
  36816. if (this.normals) {
  36817. var normal = BABYLON.Vector3.Zero();
  36818. for (index = 0; index < this.normals.length; index += 3) {
  36819. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  36820. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  36821. this.normals[index] = transformed.x;
  36822. this.normals[index + 1] = transformed.y;
  36823. this.normals[index + 2] = transformed.z;
  36824. }
  36825. }
  36826. if (this.tangents) {
  36827. var tangent = BABYLON.Vector4.Zero();
  36828. var tangentTransformed = BABYLON.Vector4.Zero();
  36829. for (index = 0; index < this.tangents.length; index += 4) {
  36830. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  36831. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  36832. this.tangents[index] = tangentTransformed.x;
  36833. this.tangents[index + 1] = tangentTransformed.y;
  36834. this.tangents[index + 2] = tangentTransformed.z;
  36835. this.tangents[index + 3] = tangentTransformed.w;
  36836. }
  36837. }
  36838. return this;
  36839. };
  36840. /**
  36841. * Merges the passed VertexData into the current one
  36842. * @param other the VertexData to be merged into the current one
  36843. * @returns the modified VertexData
  36844. */
  36845. VertexData.prototype.merge = function (other) {
  36846. this._validate();
  36847. other._validate();
  36848. if (!this.normals !== !other.normals ||
  36849. !this.tangents !== !other.tangents ||
  36850. !this.uvs !== !other.uvs ||
  36851. !this.uvs2 !== !other.uvs2 ||
  36852. !this.uvs3 !== !other.uvs3 ||
  36853. !this.uvs4 !== !other.uvs4 ||
  36854. !this.uvs5 !== !other.uvs5 ||
  36855. !this.uvs6 !== !other.uvs6 ||
  36856. !this.colors !== !other.colors ||
  36857. !this.matricesIndices !== !other.matricesIndices ||
  36858. !this.matricesWeights !== !other.matricesWeights ||
  36859. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  36860. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  36861. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  36862. }
  36863. if (other.indices) {
  36864. if (!this.indices) {
  36865. this.indices = [];
  36866. }
  36867. var offset = this.positions ? this.positions.length / 3 : 0;
  36868. for (var index = 0; index < other.indices.length; index++) {
  36869. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  36870. this.indices.push(other.indices[index] + offset);
  36871. }
  36872. }
  36873. this.positions = this._mergeElement(this.positions, other.positions);
  36874. this.normals = this._mergeElement(this.normals, other.normals);
  36875. this.tangents = this._mergeElement(this.tangents, other.tangents);
  36876. this.uvs = this._mergeElement(this.uvs, other.uvs);
  36877. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  36878. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  36879. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  36880. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  36881. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  36882. this.colors = this._mergeElement(this.colors, other.colors);
  36883. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  36884. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  36885. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  36886. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  36887. return this;
  36888. };
  36889. VertexData.prototype._mergeElement = function (source, other) {
  36890. if (!source) {
  36891. return other;
  36892. }
  36893. if (!other) {
  36894. return source;
  36895. }
  36896. var len = other.length + source.length;
  36897. var isSrcTypedArray = source instanceof Float32Array;
  36898. var isOthTypedArray = other instanceof Float32Array;
  36899. // use non-loop method when the source is Float32Array
  36900. if (isSrcTypedArray) {
  36901. var ret32 = new Float32Array(len);
  36902. ret32.set(source);
  36903. ret32.set(other, source.length);
  36904. return ret32;
  36905. // source is number[], when other is also use concat
  36906. }
  36907. else if (!isOthTypedArray) {
  36908. return source.concat(other);
  36909. // source is a number[], but other is a Float32Array, loop required
  36910. }
  36911. else {
  36912. var ret = source.slice(0); // copy source to a separate array
  36913. for (var i = 0, len = other.length; i < len; i++) {
  36914. ret.push(other[i]);
  36915. }
  36916. return ret;
  36917. }
  36918. };
  36919. VertexData.prototype._validate = function () {
  36920. if (!this.positions) {
  36921. throw new Error("Positions are required");
  36922. }
  36923. var getElementCount = function (kind, values) {
  36924. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  36925. if ((values.length % stride) !== 0) {
  36926. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  36927. }
  36928. return values.length / stride;
  36929. };
  36930. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  36931. var validateElementCount = function (kind, values) {
  36932. var elementCount = getElementCount(kind, values);
  36933. if (elementCount !== positionsElementCount) {
  36934. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  36935. }
  36936. };
  36937. if (this.normals)
  36938. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  36939. if (this.tangents)
  36940. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  36941. if (this.uvs)
  36942. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  36943. if (this.uvs2)
  36944. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  36945. if (this.uvs3)
  36946. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  36947. if (this.uvs4)
  36948. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  36949. if (this.uvs5)
  36950. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  36951. if (this.uvs6)
  36952. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  36953. if (this.colors)
  36954. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  36955. if (this.matricesIndices)
  36956. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  36957. if (this.matricesWeights)
  36958. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  36959. if (this.matricesIndicesExtra)
  36960. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  36961. if (this.matricesWeightsExtra)
  36962. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  36963. };
  36964. /**
  36965. * Serializes the VertexData
  36966. * @returns a serialized object
  36967. */
  36968. VertexData.prototype.serialize = function () {
  36969. var serializationObject = this.serialize();
  36970. if (this.positions) {
  36971. serializationObject.positions = this.positions;
  36972. }
  36973. if (this.normals) {
  36974. serializationObject.normals = this.normals;
  36975. }
  36976. if (this.tangents) {
  36977. serializationObject.tangents = this.tangents;
  36978. }
  36979. if (this.uvs) {
  36980. serializationObject.uvs = this.uvs;
  36981. }
  36982. if (this.uvs2) {
  36983. serializationObject.uvs2 = this.uvs2;
  36984. }
  36985. if (this.uvs3) {
  36986. serializationObject.uvs3 = this.uvs3;
  36987. }
  36988. if (this.uvs4) {
  36989. serializationObject.uvs4 = this.uvs4;
  36990. }
  36991. if (this.uvs5) {
  36992. serializationObject.uvs5 = this.uvs5;
  36993. }
  36994. if (this.uvs6) {
  36995. serializationObject.uvs6 = this.uvs6;
  36996. }
  36997. if (this.colors) {
  36998. serializationObject.colors = this.colors;
  36999. }
  37000. if (this.matricesIndices) {
  37001. serializationObject.matricesIndices = this.matricesIndices;
  37002. serializationObject.matricesIndices._isExpanded = true;
  37003. }
  37004. if (this.matricesWeights) {
  37005. serializationObject.matricesWeights = this.matricesWeights;
  37006. }
  37007. if (this.matricesIndicesExtra) {
  37008. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  37009. serializationObject.matricesIndicesExtra._isExpanded = true;
  37010. }
  37011. if (this.matricesWeightsExtra) {
  37012. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  37013. }
  37014. serializationObject.indices = this.indices;
  37015. return serializationObject;
  37016. };
  37017. // Statics
  37018. /**
  37019. * Extracts the vertexData from a mesh
  37020. * @param mesh the mesh from which to extract the VertexData
  37021. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  37022. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  37023. * @returns the object VertexData associated to the passed mesh
  37024. */
  37025. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  37026. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  37027. };
  37028. /**
  37029. * Extracts the vertexData from the geometry
  37030. * @param geometry the geometry from which to extract the VertexData
  37031. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  37032. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  37033. * @returns the object VertexData associated to the passed mesh
  37034. */
  37035. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  37036. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  37037. };
  37038. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  37039. var result = new VertexData();
  37040. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  37041. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  37042. }
  37043. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  37044. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  37045. }
  37046. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  37047. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  37048. }
  37049. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  37050. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  37051. }
  37052. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  37053. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  37054. }
  37055. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  37056. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  37057. }
  37058. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  37059. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  37060. }
  37061. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  37062. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  37063. }
  37064. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  37065. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  37066. }
  37067. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  37068. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  37069. }
  37070. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  37071. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  37072. }
  37073. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  37074. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  37075. }
  37076. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  37077. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  37078. }
  37079. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  37080. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  37081. }
  37082. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  37083. return result;
  37084. };
  37085. /**
  37086. * Creates the VertexData for a Ribbon
  37087. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  37088. * * pathArray array of paths, each of which an array of successive Vector3
  37089. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  37090. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  37091. * * 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
  37092. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37093. * * 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)
  37094. * * 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)
  37095. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  37096. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  37097. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  37098. * @returns the VertexData of the ribbon
  37099. */
  37100. VertexData.CreateRibbon = function (options) {
  37101. var pathArray = options.pathArray;
  37102. var closeArray = options.closeArray || false;
  37103. var closePath = options.closePath || false;
  37104. var invertUV = options.invertUV || false;
  37105. var defaultOffset = Math.floor(pathArray[0].length / 2);
  37106. var offset = options.offset || defaultOffset;
  37107. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  37108. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37109. var customUV = options.uvs;
  37110. var customColors = options.colors;
  37111. var positions = [];
  37112. var indices = [];
  37113. var normals = [];
  37114. var uvs = [];
  37115. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  37116. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  37117. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  37118. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  37119. var minlg; // minimal length among all paths from pathArray
  37120. var lg = []; // array of path lengths : nb of vertex per path
  37121. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  37122. var p; // path iterator
  37123. var i; // point iterator
  37124. var j; // point iterator
  37125. // if single path in pathArray
  37126. if (pathArray.length < 2) {
  37127. var ar1 = [];
  37128. var ar2 = [];
  37129. for (i = 0; i < pathArray[0].length - offset; i++) {
  37130. ar1.push(pathArray[0][i]);
  37131. ar2.push(pathArray[0][i + offset]);
  37132. }
  37133. pathArray = [ar1, ar2];
  37134. }
  37135. // positions and horizontal distances (u)
  37136. var idc = 0;
  37137. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  37138. var path;
  37139. var l;
  37140. minlg = pathArray[0].length;
  37141. var vectlg;
  37142. var dist;
  37143. for (p = 0; p < pathArray.length; p++) {
  37144. uTotalDistance[p] = 0;
  37145. us[p] = [0];
  37146. path = pathArray[p];
  37147. l = path.length;
  37148. minlg = (minlg < l) ? minlg : l;
  37149. j = 0;
  37150. while (j < l) {
  37151. positions.push(path[j].x, path[j].y, path[j].z);
  37152. if (j > 0) {
  37153. vectlg = path[j].subtract(path[j - 1]).length();
  37154. dist = vectlg + uTotalDistance[p];
  37155. us[p].push(dist);
  37156. uTotalDistance[p] = dist;
  37157. }
  37158. j++;
  37159. }
  37160. if (closePath) { // an extra hidden vertex is added in the "positions" array
  37161. j--;
  37162. positions.push(path[0].x, path[0].y, path[0].z);
  37163. vectlg = path[j].subtract(path[0]).length();
  37164. dist = vectlg + uTotalDistance[p];
  37165. us[p].push(dist);
  37166. uTotalDistance[p] = dist;
  37167. }
  37168. lg[p] = l + closePathCorr;
  37169. idx[p] = idc;
  37170. idc += (l + closePathCorr);
  37171. }
  37172. // vertical distances (v)
  37173. var path1;
  37174. var path2;
  37175. var vertex1 = null;
  37176. var vertex2 = null;
  37177. for (i = 0; i < minlg + closePathCorr; i++) {
  37178. vTotalDistance[i] = 0;
  37179. vs[i] = [0];
  37180. for (p = 0; p < pathArray.length - 1; p++) {
  37181. path1 = pathArray[p];
  37182. path2 = pathArray[p + 1];
  37183. if (i === minlg) { // closePath
  37184. vertex1 = path1[0];
  37185. vertex2 = path2[0];
  37186. }
  37187. else {
  37188. vertex1 = path1[i];
  37189. vertex2 = path2[i];
  37190. }
  37191. vectlg = vertex2.subtract(vertex1).length();
  37192. dist = vectlg + vTotalDistance[i];
  37193. vs[i].push(dist);
  37194. vTotalDistance[i] = dist;
  37195. }
  37196. if (closeArray && vertex2 && vertex1) {
  37197. path1 = pathArray[p];
  37198. path2 = pathArray[0];
  37199. if (i === minlg) { // closePath
  37200. vertex2 = path2[0];
  37201. }
  37202. vectlg = vertex2.subtract(vertex1).length();
  37203. dist = vectlg + vTotalDistance[i];
  37204. vTotalDistance[i] = dist;
  37205. }
  37206. }
  37207. // uvs
  37208. var u;
  37209. var v;
  37210. if (customUV) {
  37211. for (p = 0; p < customUV.length; p++) {
  37212. uvs.push(customUV[p].x, customUV[p].y);
  37213. }
  37214. }
  37215. else {
  37216. for (p = 0; p < pathArray.length; p++) {
  37217. for (i = 0; i < minlg + closePathCorr; i++) {
  37218. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  37219. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  37220. if (invertUV) {
  37221. uvs.push(v, u);
  37222. }
  37223. else {
  37224. uvs.push(u, v);
  37225. }
  37226. }
  37227. }
  37228. }
  37229. // indices
  37230. p = 0; // path index
  37231. var pi = 0; // positions array index
  37232. var l1 = lg[p] - 1; // path1 length
  37233. var l2 = lg[p + 1] - 1; // path2 length
  37234. var min = (l1 < l2) ? l1 : l2; // current path stop index
  37235. var shft = idx[1] - idx[0]; // shift
  37236. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  37237. while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path
  37238. // 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
  37239. indices.push(pi, pi + shft, pi + 1);
  37240. indices.push(pi + shft + 1, pi + 1, pi + shft);
  37241. pi += 1;
  37242. if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path
  37243. p++;
  37244. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  37245. shft = idx[0] - idx[p];
  37246. l1 = lg[p] - 1;
  37247. l2 = lg[0] - 1;
  37248. }
  37249. else {
  37250. shft = idx[p + 1] - idx[p];
  37251. l1 = lg[p] - 1;
  37252. l2 = lg[p + 1] - 1;
  37253. }
  37254. pi = idx[p];
  37255. min = (l1 < l2) ? l1 + pi : l2 + pi;
  37256. }
  37257. }
  37258. // normals
  37259. VertexData.ComputeNormals(positions, indices, normals);
  37260. if (closePath) { // update both the first and last vertex normals to their average value
  37261. var indexFirst = 0;
  37262. var indexLast = 0;
  37263. for (p = 0; p < pathArray.length; p++) {
  37264. indexFirst = idx[p] * 3;
  37265. if (p + 1 < pathArray.length) {
  37266. indexLast = (idx[p + 1] - 1) * 3;
  37267. }
  37268. else {
  37269. indexLast = normals.length - 3;
  37270. }
  37271. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  37272. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  37273. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  37274. normals[indexLast] = normals[indexFirst];
  37275. normals[indexLast + 1] = normals[indexFirst + 1];
  37276. normals[indexLast + 2] = normals[indexFirst + 2];
  37277. }
  37278. }
  37279. // sides
  37280. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37281. // Colors
  37282. var colors = null;
  37283. if (customColors) {
  37284. colors = new Float32Array(customColors.length * 4);
  37285. for (var c = 0; c < customColors.length; c++) {
  37286. colors[c * 4] = customColors[c].r;
  37287. colors[c * 4 + 1] = customColors[c].g;
  37288. colors[c * 4 + 2] = customColors[c].b;
  37289. colors[c * 4 + 3] = customColors[c].a;
  37290. }
  37291. }
  37292. // Result
  37293. var vertexData = new VertexData();
  37294. var positions32 = new Float32Array(positions);
  37295. var normals32 = new Float32Array(normals);
  37296. var uvs32 = new Float32Array(uvs);
  37297. vertexData.indices = indices;
  37298. vertexData.positions = positions32;
  37299. vertexData.normals = normals32;
  37300. vertexData.uvs = uvs32;
  37301. if (colors) {
  37302. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  37303. }
  37304. if (closePath) {
  37305. vertexData._idx = idx;
  37306. }
  37307. return vertexData;
  37308. };
  37309. /**
  37310. * Creates the VertexData for a box
  37311. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37312. * * size sets the width, height and depth of the box to the value of size, optional default 1
  37313. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  37314. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  37315. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  37316. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  37317. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  37318. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37319. * * 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)
  37320. * * 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)
  37321. * @returns the VertexData of the box
  37322. */
  37323. VertexData.CreateBox = function (options) {
  37324. var normalsSource = [
  37325. new BABYLON.Vector3(0, 0, 1),
  37326. new BABYLON.Vector3(0, 0, -1),
  37327. new BABYLON.Vector3(1, 0, 0),
  37328. new BABYLON.Vector3(-1, 0, 0),
  37329. new BABYLON.Vector3(0, 1, 0),
  37330. new BABYLON.Vector3(0, -1, 0)
  37331. ];
  37332. var indices = [];
  37333. var positions = [];
  37334. var normals = [];
  37335. var uvs = [];
  37336. var width = options.width || options.size || 1;
  37337. var height = options.height || options.size || 1;
  37338. var depth = options.depth || options.size || 1;
  37339. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37340. var faceUV = options.faceUV || new Array(6);
  37341. var faceColors = options.faceColors;
  37342. var colors = [];
  37343. // default face colors and UV if undefined
  37344. for (var f = 0; f < 6; f++) {
  37345. if (faceUV[f] === undefined) {
  37346. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37347. }
  37348. if (faceColors && faceColors[f] === undefined) {
  37349. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37350. }
  37351. }
  37352. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  37353. // Create each face in turn.
  37354. for (var index = 0; index < normalsSource.length; index++) {
  37355. var normal = normalsSource[index];
  37356. // Get two vectors perpendicular to the face normal and to each other.
  37357. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  37358. var side2 = BABYLON.Vector3.Cross(normal, side1);
  37359. // Six indices (two triangles) per face.
  37360. var verticesLength = positions.length / 3;
  37361. indices.push(verticesLength);
  37362. indices.push(verticesLength + 1);
  37363. indices.push(verticesLength + 2);
  37364. indices.push(verticesLength);
  37365. indices.push(verticesLength + 2);
  37366. indices.push(verticesLength + 3);
  37367. // Four vertices per face.
  37368. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  37369. positions.push(vertex.x, vertex.y, vertex.z);
  37370. normals.push(normal.x, normal.y, normal.z);
  37371. uvs.push(faceUV[index].z, faceUV[index].w);
  37372. if (faceColors) {
  37373. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37374. }
  37375. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  37376. positions.push(vertex.x, vertex.y, vertex.z);
  37377. normals.push(normal.x, normal.y, normal.z);
  37378. uvs.push(faceUV[index].x, faceUV[index].w);
  37379. if (faceColors) {
  37380. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37381. }
  37382. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  37383. positions.push(vertex.x, vertex.y, vertex.z);
  37384. normals.push(normal.x, normal.y, normal.z);
  37385. uvs.push(faceUV[index].x, faceUV[index].y);
  37386. if (faceColors) {
  37387. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37388. }
  37389. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  37390. positions.push(vertex.x, vertex.y, vertex.z);
  37391. normals.push(normal.x, normal.y, normal.z);
  37392. uvs.push(faceUV[index].z, faceUV[index].y);
  37393. if (faceColors) {
  37394. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37395. }
  37396. }
  37397. // sides
  37398. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37399. // Result
  37400. var vertexData = new VertexData();
  37401. vertexData.indices = indices;
  37402. vertexData.positions = positions;
  37403. vertexData.normals = normals;
  37404. vertexData.uvs = uvs;
  37405. if (faceColors) {
  37406. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37407. vertexData.colors = totalColors;
  37408. }
  37409. return vertexData;
  37410. };
  37411. /**
  37412. * Creates the VertexData for an ellipsoid, defaults to a sphere
  37413. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37414. * * segments sets the number of horizontal strips optional, default 32
  37415. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  37416. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  37417. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  37418. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  37419. * * 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
  37420. * * 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
  37421. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37422. * * 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)
  37423. * * 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)
  37424. * @returns the VertexData of the ellipsoid
  37425. */
  37426. VertexData.CreateSphere = function (options) {
  37427. var segments = options.segments || 32;
  37428. var diameterX = options.diameterX || options.diameter || 1;
  37429. var diameterY = options.diameterY || options.diameter || 1;
  37430. var diameterZ = options.diameterZ || options.diameter || 1;
  37431. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37432. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  37433. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37434. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  37435. var totalZRotationSteps = 2 + segments;
  37436. var totalYRotationSteps = 2 * totalZRotationSteps;
  37437. var indices = [];
  37438. var positions = [];
  37439. var normals = [];
  37440. var uvs = [];
  37441. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  37442. var normalizedZ = zRotationStep / totalZRotationSteps;
  37443. var angleZ = normalizedZ * Math.PI * slice;
  37444. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  37445. var normalizedY = yRotationStep / totalYRotationSteps;
  37446. var angleY = normalizedY * Math.PI * 2 * arc;
  37447. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  37448. var rotationY = BABYLON.Matrix.RotationY(angleY);
  37449. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  37450. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  37451. var vertex = complete.multiply(radius);
  37452. var normal = complete.divide(radius).normalize();
  37453. positions.push(vertex.x, vertex.y, vertex.z);
  37454. normals.push(normal.x, normal.y, normal.z);
  37455. uvs.push(normalizedY, normalizedZ);
  37456. }
  37457. if (zRotationStep > 0) {
  37458. var verticesCount = positions.length / 3;
  37459. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  37460. indices.push((firstIndex));
  37461. indices.push((firstIndex + 1));
  37462. indices.push(firstIndex + totalYRotationSteps + 1);
  37463. indices.push((firstIndex + totalYRotationSteps + 1));
  37464. indices.push((firstIndex + 1));
  37465. indices.push((firstIndex + totalYRotationSteps + 2));
  37466. }
  37467. }
  37468. }
  37469. // Sides
  37470. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37471. // Result
  37472. var vertexData = new VertexData();
  37473. vertexData.indices = indices;
  37474. vertexData.positions = positions;
  37475. vertexData.normals = normals;
  37476. vertexData.uvs = uvs;
  37477. return vertexData;
  37478. };
  37479. /**
  37480. * Creates the VertexData for a cylinder, cone or prism
  37481. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37482. * * height sets the height (y direction) of the cylinder, optional, default 2
  37483. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  37484. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  37485. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  37486. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37487. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  37488. * * 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
  37489. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37490. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37491. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  37492. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  37493. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37494. * * 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)
  37495. * * 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)
  37496. * @returns the VertexData of the cylinder, cone or prism
  37497. */
  37498. VertexData.CreateCylinder = function (options) {
  37499. var height = options.height || 2;
  37500. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  37501. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  37502. var tessellation = options.tessellation || 24;
  37503. var subdivisions = options.subdivisions || 1;
  37504. var hasRings = options.hasRings ? true : false;
  37505. var enclose = options.enclose ? true : false;
  37506. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37507. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37508. var faceUV = options.faceUV || new Array(3);
  37509. var faceColors = options.faceColors;
  37510. // default face colors and UV if undefined
  37511. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  37512. var ringNb = (hasRings) ? subdivisions : 1;
  37513. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  37514. var f;
  37515. for (f = 0; f < surfaceNb; f++) {
  37516. if (faceColors && faceColors[f] === undefined) {
  37517. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37518. }
  37519. }
  37520. for (f = 0; f < surfaceNb; f++) {
  37521. if (faceUV && faceUV[f] === undefined) {
  37522. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37523. }
  37524. }
  37525. var indices = new Array();
  37526. var positions = new Array();
  37527. var normals = new Array();
  37528. var uvs = new Array();
  37529. var colors = new Array();
  37530. var angle_step = Math.PI * 2 * arc / tessellation;
  37531. var angle;
  37532. var h;
  37533. var radius;
  37534. var tan = (diameterBottom - diameterTop) / 2 / height;
  37535. var ringVertex = BABYLON.Vector3.Zero();
  37536. var ringNormal = BABYLON.Vector3.Zero();
  37537. var ringFirstVertex = BABYLON.Vector3.Zero();
  37538. var ringFirstNormal = BABYLON.Vector3.Zero();
  37539. var quadNormal = BABYLON.Vector3.Zero();
  37540. var Y = BABYLON.Axis.Y;
  37541. // positions, normals, uvs
  37542. var i;
  37543. var j;
  37544. var r;
  37545. var ringIdx = 1;
  37546. var s = 1; // surface index
  37547. var cs = 0;
  37548. var v = 0;
  37549. for (i = 0; i <= subdivisions; i++) {
  37550. h = i / subdivisions;
  37551. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  37552. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  37553. for (r = 0; r < ringIdx; r++) {
  37554. if (hasRings) {
  37555. s += r;
  37556. }
  37557. if (enclose) {
  37558. s += 2 * r;
  37559. }
  37560. for (j = 0; j <= tessellation; j++) {
  37561. angle = j * angle_step;
  37562. // position
  37563. ringVertex.x = Math.cos(-angle) * radius;
  37564. ringVertex.y = -height / 2 + h * height;
  37565. ringVertex.z = Math.sin(-angle) * radius;
  37566. // normal
  37567. if (diameterTop === 0 && i === subdivisions) {
  37568. // if no top cap, reuse former normals
  37569. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  37570. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  37571. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  37572. }
  37573. else {
  37574. ringNormal.x = ringVertex.x;
  37575. ringNormal.z = ringVertex.z;
  37576. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  37577. ringNormal.normalize();
  37578. }
  37579. // keep first ring vertex values for enclose
  37580. if (j === 0) {
  37581. ringFirstVertex.copyFrom(ringVertex);
  37582. ringFirstNormal.copyFrom(ringNormal);
  37583. }
  37584. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37585. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  37586. if (hasRings) {
  37587. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  37588. }
  37589. else {
  37590. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  37591. }
  37592. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  37593. if (faceColors) {
  37594. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  37595. }
  37596. }
  37597. // if enclose, add four vertices and their dedicated normals
  37598. if (arc !== 1 && enclose) {
  37599. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37600. positions.push(0, ringVertex.y, 0);
  37601. positions.push(0, ringVertex.y, 0);
  37602. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  37603. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  37604. quadNormal.normalize();
  37605. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37606. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  37607. quadNormal.normalize();
  37608. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37609. if (hasRings) {
  37610. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  37611. }
  37612. else {
  37613. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  37614. }
  37615. uvs.push(faceUV[s + 1].x, v);
  37616. uvs.push(faceUV[s + 1].z, v);
  37617. if (hasRings) {
  37618. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  37619. }
  37620. else {
  37621. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  37622. }
  37623. uvs.push(faceUV[s + 2].x, v);
  37624. uvs.push(faceUV[s + 2].z, v);
  37625. if (faceColors) {
  37626. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37627. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37628. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37629. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37630. }
  37631. }
  37632. if (cs !== s) {
  37633. cs = s;
  37634. }
  37635. }
  37636. }
  37637. // indices
  37638. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  37639. var s;
  37640. i = 0;
  37641. for (s = 0; s < subdivisions; s++) {
  37642. var i0 = 0;
  37643. var i1 = 0;
  37644. var i2 = 0;
  37645. var i3 = 0;
  37646. for (j = 0; j < tessellation; j++) {
  37647. i0 = i * (e + 1) + j;
  37648. i1 = (i + 1) * (e + 1) + j;
  37649. i2 = i * (e + 1) + (j + 1);
  37650. i3 = (i + 1) * (e + 1) + (j + 1);
  37651. indices.push(i0, i1, i2);
  37652. indices.push(i3, i2, i1);
  37653. }
  37654. if (arc !== 1 && enclose) { // if enclose, add two quads
  37655. indices.push(i0 + 2, i1 + 2, i2 + 2);
  37656. indices.push(i3 + 2, i2 + 2, i1 + 2);
  37657. indices.push(i0 + 4, i1 + 4, i2 + 4);
  37658. indices.push(i3 + 4, i2 + 4, i1 + 4);
  37659. }
  37660. i = (hasRings) ? (i + 2) : (i + 1);
  37661. }
  37662. // Caps
  37663. var createCylinderCap = function (isTop) {
  37664. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  37665. if (radius === 0) {
  37666. return;
  37667. }
  37668. // Cap positions, normals & uvs
  37669. var angle;
  37670. var circleVector;
  37671. var i;
  37672. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  37673. var c = null;
  37674. if (faceColors) {
  37675. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  37676. }
  37677. // cap center
  37678. var vbase = positions.length / 3;
  37679. var offset = isTop ? height / 2 : -height / 2;
  37680. var center = new BABYLON.Vector3(0, offset, 0);
  37681. positions.push(center.x, center.y, center.z);
  37682. normals.push(0, isTop ? 1 : -1, 0);
  37683. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  37684. if (c) {
  37685. colors.push(c.r, c.g, c.b, c.a);
  37686. }
  37687. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  37688. for (i = 0; i <= tessellation; i++) {
  37689. angle = Math.PI * 2 * i * arc / tessellation;
  37690. var cos = Math.cos(-angle);
  37691. var sin = Math.sin(-angle);
  37692. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  37693. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  37694. positions.push(circleVector.x, circleVector.y, circleVector.z);
  37695. normals.push(0, isTop ? 1 : -1, 0);
  37696. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  37697. if (c) {
  37698. colors.push(c.r, c.g, c.b, c.a);
  37699. }
  37700. }
  37701. // Cap indices
  37702. for (i = 0; i < tessellation; i++) {
  37703. if (!isTop) {
  37704. indices.push(vbase);
  37705. indices.push(vbase + (i + 1));
  37706. indices.push(vbase + (i + 2));
  37707. }
  37708. else {
  37709. indices.push(vbase);
  37710. indices.push(vbase + (i + 2));
  37711. indices.push(vbase + (i + 1));
  37712. }
  37713. }
  37714. };
  37715. // add caps to geometry
  37716. createCylinderCap(false);
  37717. createCylinderCap(true);
  37718. // Sides
  37719. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37720. var vertexData = new VertexData();
  37721. vertexData.indices = indices;
  37722. vertexData.positions = positions;
  37723. vertexData.normals = normals;
  37724. vertexData.uvs = uvs;
  37725. if (faceColors) {
  37726. vertexData.colors = colors;
  37727. }
  37728. return vertexData;
  37729. };
  37730. /**
  37731. * Creates the VertexData for a torus
  37732. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37733. * * diameter the diameter of the torus, optional default 1
  37734. * * thickness the diameter of the tube forming the torus, optional default 0.5
  37735. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37736. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37737. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37738. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37739. * @returns the VertexData of the torus
  37740. */
  37741. VertexData.CreateTorus = function (options) {
  37742. var indices = [];
  37743. var positions = [];
  37744. var normals = [];
  37745. var uvs = [];
  37746. var diameter = options.diameter || 1;
  37747. var thickness = options.thickness || 0.5;
  37748. var tessellation = options.tessellation || 16;
  37749. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37750. var stride = tessellation + 1;
  37751. for (var i = 0; i <= tessellation; i++) {
  37752. var u = i / tessellation;
  37753. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  37754. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  37755. for (var j = 0; j <= tessellation; j++) {
  37756. var v = 1 - j / tessellation;
  37757. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  37758. var dx = Math.cos(innerAngle);
  37759. var dy = Math.sin(innerAngle);
  37760. // Create a vertex.
  37761. var normal = new BABYLON.Vector3(dx, dy, 0);
  37762. var position = normal.scale(thickness / 2);
  37763. var textureCoordinate = new BABYLON.Vector2(u, v);
  37764. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  37765. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  37766. positions.push(position.x, position.y, position.z);
  37767. normals.push(normal.x, normal.y, normal.z);
  37768. uvs.push(textureCoordinate.x, textureCoordinate.y);
  37769. // And create indices for two triangles.
  37770. var nextI = (i + 1) % stride;
  37771. var nextJ = (j + 1) % stride;
  37772. indices.push(i * stride + j);
  37773. indices.push(i * stride + nextJ);
  37774. indices.push(nextI * stride + j);
  37775. indices.push(i * stride + nextJ);
  37776. indices.push(nextI * stride + nextJ);
  37777. indices.push(nextI * stride + j);
  37778. }
  37779. }
  37780. // Sides
  37781. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37782. // Result
  37783. var vertexData = new VertexData();
  37784. vertexData.indices = indices;
  37785. vertexData.positions = positions;
  37786. vertexData.normals = normals;
  37787. vertexData.uvs = uvs;
  37788. return vertexData;
  37789. };
  37790. /**
  37791. * Creates the VertexData of the LineSystem
  37792. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  37793. * - lines an array of lines, each line being an array of successive Vector3
  37794. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  37795. * @returns the VertexData of the LineSystem
  37796. */
  37797. VertexData.CreateLineSystem = function (options) {
  37798. var indices = [];
  37799. var positions = [];
  37800. var lines = options.lines;
  37801. var colors = options.colors;
  37802. var vertexColors = [];
  37803. var idx = 0;
  37804. for (var l = 0; l < lines.length; l++) {
  37805. var points = lines[l];
  37806. for (var index = 0; index < points.length; index++) {
  37807. positions.push(points[index].x, points[index].y, points[index].z);
  37808. if (colors) {
  37809. var color = colors[l];
  37810. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  37811. }
  37812. if (index > 0) {
  37813. indices.push(idx - 1);
  37814. indices.push(idx);
  37815. }
  37816. idx++;
  37817. }
  37818. }
  37819. var vertexData = new VertexData();
  37820. vertexData.indices = indices;
  37821. vertexData.positions = positions;
  37822. if (colors) {
  37823. vertexData.colors = vertexColors;
  37824. }
  37825. return vertexData;
  37826. };
  37827. /**
  37828. * Create the VertexData for a DashedLines
  37829. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  37830. * - points an array successive Vector3
  37831. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  37832. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  37833. * - dashNb the intended total number of dashes, optional, default 200
  37834. * @returns the VertexData for the DashedLines
  37835. */
  37836. VertexData.CreateDashedLines = function (options) {
  37837. var dashSize = options.dashSize || 3;
  37838. var gapSize = options.gapSize || 1;
  37839. var dashNb = options.dashNb || 200;
  37840. var points = options.points;
  37841. var positions = new Array();
  37842. var indices = new Array();
  37843. var curvect = BABYLON.Vector3.Zero();
  37844. var lg = 0;
  37845. var nb = 0;
  37846. var shft = 0;
  37847. var dashshft = 0;
  37848. var curshft = 0;
  37849. var idx = 0;
  37850. var i = 0;
  37851. for (i = 0; i < points.length - 1; i++) {
  37852. points[i + 1].subtractToRef(points[i], curvect);
  37853. lg += curvect.length();
  37854. }
  37855. shft = lg / dashNb;
  37856. dashshft = dashSize * shft / (dashSize + gapSize);
  37857. for (i = 0; i < points.length - 1; i++) {
  37858. points[i + 1].subtractToRef(points[i], curvect);
  37859. nb = Math.floor(curvect.length() / shft);
  37860. curvect.normalize();
  37861. for (var j = 0; j < nb; j++) {
  37862. curshft = shft * j;
  37863. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  37864. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  37865. indices.push(idx, idx + 1);
  37866. idx += 2;
  37867. }
  37868. }
  37869. // Result
  37870. var vertexData = new VertexData();
  37871. vertexData.positions = positions;
  37872. vertexData.indices = indices;
  37873. return vertexData;
  37874. };
  37875. /**
  37876. * Creates the VertexData for a Ground
  37877. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37878. * - width the width (x direction) of the ground, optional, default 1
  37879. * - height the height (z direction) of the ground, optional, default 1
  37880. * - subdivisions the number of subdivisions per side, optional, default 1
  37881. * @returns the VertexData of the Ground
  37882. */
  37883. VertexData.CreateGround = function (options) {
  37884. var indices = [];
  37885. var positions = [];
  37886. var normals = [];
  37887. var uvs = [];
  37888. var row, col;
  37889. var width = options.width || 1;
  37890. var height = options.height || 1;
  37891. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  37892. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  37893. for (row = 0; row <= subdivisionsY; row++) {
  37894. for (col = 0; col <= subdivisionsX; col++) {
  37895. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  37896. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37897. positions.push(position.x, position.y, position.z);
  37898. normals.push(normal.x, normal.y, normal.z);
  37899. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  37900. }
  37901. }
  37902. for (row = 0; row < subdivisionsY; row++) {
  37903. for (col = 0; col < subdivisionsX; col++) {
  37904. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37905. indices.push(col + 1 + row * (subdivisionsX + 1));
  37906. indices.push(col + row * (subdivisionsX + 1));
  37907. indices.push(col + (row + 1) * (subdivisionsX + 1));
  37908. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37909. indices.push(col + row * (subdivisionsX + 1));
  37910. }
  37911. }
  37912. // Result
  37913. var vertexData = new VertexData();
  37914. vertexData.indices = indices;
  37915. vertexData.positions = positions;
  37916. vertexData.normals = normals;
  37917. vertexData.uvs = uvs;
  37918. return vertexData;
  37919. };
  37920. /**
  37921. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  37922. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37923. * * xmin the ground minimum X coordinate, optional, default -1
  37924. * * zmin the ground minimum Z coordinate, optional, default -1
  37925. * * xmax the ground maximum X coordinate, optional, default 1
  37926. * * zmax the ground maximum Z coordinate, optional, default 1
  37927. * * 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}
  37928. * * 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}
  37929. * @returns the VertexData of the TiledGround
  37930. */
  37931. VertexData.CreateTiledGround = function (options) {
  37932. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  37933. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  37934. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  37935. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  37936. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  37937. var precision = options.precision || { w: 1, h: 1 };
  37938. var indices = new Array();
  37939. var positions = new Array();
  37940. var normals = new Array();
  37941. var uvs = new Array();
  37942. var row, col, tileRow, tileCol;
  37943. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  37944. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  37945. precision.w = (precision.w < 1) ? 1 : precision.w;
  37946. precision.h = (precision.h < 1) ? 1 : precision.h;
  37947. var tileSize = {
  37948. 'w': (xmax - xmin) / subdivisions.w,
  37949. 'h': (zmax - zmin) / subdivisions.h
  37950. };
  37951. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  37952. // Indices
  37953. var base = positions.length / 3;
  37954. var rowLength = precision.w + 1;
  37955. for (row = 0; row < precision.h; row++) {
  37956. for (col = 0; col < precision.w; col++) {
  37957. var square = [
  37958. base + col + row * rowLength,
  37959. base + (col + 1) + row * rowLength,
  37960. base + (col + 1) + (row + 1) * rowLength,
  37961. base + col + (row + 1) * rowLength
  37962. ];
  37963. indices.push(square[1]);
  37964. indices.push(square[2]);
  37965. indices.push(square[3]);
  37966. indices.push(square[0]);
  37967. indices.push(square[1]);
  37968. indices.push(square[3]);
  37969. }
  37970. }
  37971. // Position, normals and uvs
  37972. var position = BABYLON.Vector3.Zero();
  37973. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37974. for (row = 0; row <= precision.h; row++) {
  37975. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  37976. for (col = 0; col <= precision.w; col++) {
  37977. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  37978. position.y = 0;
  37979. positions.push(position.x, position.y, position.z);
  37980. normals.push(normal.x, normal.y, normal.z);
  37981. uvs.push(col / precision.w, row / precision.h);
  37982. }
  37983. }
  37984. }
  37985. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  37986. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  37987. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  37988. }
  37989. }
  37990. // Result
  37991. var vertexData = new VertexData();
  37992. vertexData.indices = indices;
  37993. vertexData.positions = positions;
  37994. vertexData.normals = normals;
  37995. vertexData.uvs = uvs;
  37996. return vertexData;
  37997. };
  37998. /**
  37999. * Creates the VertexData of the Ground designed from a heightmap
  38000. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  38001. * * width the width (x direction) of the ground
  38002. * * height the height (z direction) of the ground
  38003. * * subdivisions the number of subdivisions per side
  38004. * * minHeight the minimum altitude on the ground, optional, default 0
  38005. * * maxHeight the maximum altitude on the ground, optional default 1
  38006. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  38007. * * buffer the array holding the image color data
  38008. * * bufferWidth the width of image
  38009. * * bufferHeight the height of image
  38010. * @returns the VertexData of the Ground designed from a heightmap
  38011. */
  38012. VertexData.CreateGroundFromHeightMap = function (options) {
  38013. var indices = [];
  38014. var positions = [];
  38015. var normals = [];
  38016. var uvs = [];
  38017. var row, col;
  38018. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  38019. // Vertices
  38020. for (row = 0; row <= options.subdivisions; row++) {
  38021. for (col = 0; col <= options.subdivisions; col++) {
  38022. 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));
  38023. // Compute height
  38024. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  38025. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  38026. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  38027. var r = options.buffer[pos] / 255.0;
  38028. var g = options.buffer[pos + 1] / 255.0;
  38029. var b = options.buffer[pos + 2] / 255.0;
  38030. var gradient = r * filter.r + g * filter.g + b * filter.b;
  38031. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  38032. // Add vertex
  38033. positions.push(position.x, position.y, position.z);
  38034. normals.push(0, 0, 0);
  38035. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  38036. }
  38037. }
  38038. // Indices
  38039. for (row = 0; row < options.subdivisions; row++) {
  38040. for (col = 0; col < options.subdivisions; col++) {
  38041. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  38042. indices.push(col + 1 + row * (options.subdivisions + 1));
  38043. indices.push(col + row * (options.subdivisions + 1));
  38044. indices.push(col + (row + 1) * (options.subdivisions + 1));
  38045. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  38046. indices.push(col + row * (options.subdivisions + 1));
  38047. }
  38048. }
  38049. // Normals
  38050. VertexData.ComputeNormals(positions, indices, normals);
  38051. // Result
  38052. var vertexData = new VertexData();
  38053. vertexData.indices = indices;
  38054. vertexData.positions = positions;
  38055. vertexData.normals = normals;
  38056. vertexData.uvs = uvs;
  38057. return vertexData;
  38058. };
  38059. /**
  38060. * Creates the VertexData for a Plane
  38061. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  38062. * * size sets the width and height of the plane to the value of size, optional default 1
  38063. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  38064. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  38065. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38066. * * 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)
  38067. * * 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)
  38068. * @returns the VertexData of the box
  38069. */
  38070. VertexData.CreatePlane = function (options) {
  38071. var indices = [];
  38072. var positions = [];
  38073. var normals = [];
  38074. var uvs = [];
  38075. var width = options.width || options.size || 1;
  38076. var height = options.height || options.size || 1;
  38077. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38078. // Vertices
  38079. var halfWidth = width / 2.0;
  38080. var halfHeight = height / 2.0;
  38081. positions.push(-halfWidth, -halfHeight, 0);
  38082. normals.push(0, 0, -1.0);
  38083. uvs.push(0.0, 0.0);
  38084. positions.push(halfWidth, -halfHeight, 0);
  38085. normals.push(0, 0, -1.0);
  38086. uvs.push(1.0, 0.0);
  38087. positions.push(halfWidth, halfHeight, 0);
  38088. normals.push(0, 0, -1.0);
  38089. uvs.push(1.0, 1.0);
  38090. positions.push(-halfWidth, halfHeight, 0);
  38091. normals.push(0, 0, -1.0);
  38092. uvs.push(0.0, 1.0);
  38093. // Indices
  38094. indices.push(0);
  38095. indices.push(1);
  38096. indices.push(2);
  38097. indices.push(0);
  38098. indices.push(2);
  38099. indices.push(3);
  38100. // Sides
  38101. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38102. // Result
  38103. var vertexData = new VertexData();
  38104. vertexData.indices = indices;
  38105. vertexData.positions = positions;
  38106. vertexData.normals = normals;
  38107. vertexData.uvs = uvs;
  38108. return vertexData;
  38109. };
  38110. /**
  38111. * Creates the VertexData of the Disc or regular Polygon
  38112. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  38113. * * radius the radius of the disc, optional default 0.5
  38114. * * tessellation the number of polygon sides, optional, default 64
  38115. * * 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
  38116. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38117. * * 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)
  38118. * * 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)
  38119. * @returns the VertexData of the box
  38120. */
  38121. VertexData.CreateDisc = function (options) {
  38122. var positions = new Array();
  38123. var indices = new Array();
  38124. var normals = new Array();
  38125. var uvs = new Array();
  38126. var radius = options.radius || 0.5;
  38127. var tessellation = options.tessellation || 64;
  38128. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  38129. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38130. // positions and uvs
  38131. positions.push(0, 0, 0); // disc center first
  38132. uvs.push(0.5, 0.5);
  38133. var theta = Math.PI * 2 * arc;
  38134. var step = theta / tessellation;
  38135. for (var a = 0; a < theta; a += step) {
  38136. var x = Math.cos(a);
  38137. var y = Math.sin(a);
  38138. var u = (x + 1) / 2;
  38139. var v = (1 - y) / 2;
  38140. positions.push(radius * x, radius * y, 0);
  38141. uvs.push(u, v);
  38142. }
  38143. if (arc === 1) {
  38144. positions.push(positions[3], positions[4], positions[5]); // close the circle
  38145. uvs.push(uvs[2], uvs[3]);
  38146. }
  38147. //indices
  38148. var vertexNb = positions.length / 3;
  38149. for (var i = 1; i < vertexNb - 1; i++) {
  38150. indices.push(i + 1, 0, i);
  38151. }
  38152. // result
  38153. VertexData.ComputeNormals(positions, indices, normals);
  38154. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38155. var vertexData = new VertexData();
  38156. vertexData.indices = indices;
  38157. vertexData.positions = positions;
  38158. vertexData.normals = normals;
  38159. vertexData.uvs = uvs;
  38160. return vertexData;
  38161. };
  38162. /**
  38163. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  38164. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  38165. * @param polygon a mesh built from polygonTriangulation.build()
  38166. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38167. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  38168. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  38169. * @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)
  38170. * @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)
  38171. * @returns the VertexData of the Polygon
  38172. */
  38173. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  38174. var faceUV = fUV || new Array(3);
  38175. var faceColors = fColors;
  38176. var colors = [];
  38177. // default face colors and UV if undefined
  38178. for (var f = 0; f < 3; f++) {
  38179. if (faceUV[f] === undefined) {
  38180. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38181. }
  38182. if (faceColors && faceColors[f] === undefined) {
  38183. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38184. }
  38185. }
  38186. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  38187. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  38188. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  38189. var indices = polygon.getIndices();
  38190. // set face colours and textures
  38191. var idx = 0;
  38192. var face = 0;
  38193. for (var index = 0; index < normals.length; index += 3) {
  38194. //Edge Face no. 1
  38195. if (Math.abs(normals[index + 1]) < 0.001) {
  38196. face = 1;
  38197. }
  38198. //Top Face no. 0
  38199. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  38200. face = 0;
  38201. }
  38202. //Bottom Face no. 2
  38203. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  38204. face = 2;
  38205. }
  38206. idx = index / 3;
  38207. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  38208. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  38209. if (faceColors) {
  38210. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  38211. }
  38212. }
  38213. // sides
  38214. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  38215. // Result
  38216. var vertexData = new VertexData();
  38217. vertexData.indices = indices;
  38218. vertexData.positions = positions;
  38219. vertexData.normals = normals;
  38220. vertexData.uvs = uvs;
  38221. if (faceColors) {
  38222. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  38223. vertexData.colors = totalColors;
  38224. }
  38225. return vertexData;
  38226. };
  38227. /**
  38228. * Creates the VertexData of the IcoSphere
  38229. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  38230. * * radius the radius of the IcoSphere, optional default 1
  38231. * * radiusX allows stretching in the x direction, optional, default radius
  38232. * * radiusY allows stretching in the y direction, optional, default radius
  38233. * * radiusZ allows stretching in the z direction, optional, default radius
  38234. * * flat when true creates a flat shaded mesh, optional, default true
  38235. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  38236. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38237. * * 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)
  38238. * * 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)
  38239. * @returns the VertexData of the IcoSphere
  38240. */
  38241. VertexData.CreateIcoSphere = function (options) {
  38242. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38243. var radius = options.radius || 1;
  38244. var flat = (options.flat === undefined) ? true : options.flat;
  38245. var subdivisions = options.subdivisions || 4;
  38246. var radiusX = options.radiusX || radius;
  38247. var radiusY = options.radiusY || radius;
  38248. var radiusZ = options.radiusZ || radius;
  38249. var t = (1 + Math.sqrt(5)) / 2;
  38250. // 12 vertex x,y,z
  38251. var ico_vertices = [
  38252. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  38253. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  38254. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  38255. ];
  38256. // index of 3 vertex makes a face of icopshere
  38257. var ico_indices = [
  38258. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  38259. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  38260. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  38261. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  38262. ];
  38263. // vertex for uv have aliased position, not for UV
  38264. var vertices_unalias_id = [
  38265. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  38266. // vertex alias
  38267. 0,
  38268. 2,
  38269. 3,
  38270. 3,
  38271. 3,
  38272. 4,
  38273. 7,
  38274. 8,
  38275. 9,
  38276. 9,
  38277. 10,
  38278. 11 // 23: B + 12
  38279. ];
  38280. // uv as integer step (not pixels !)
  38281. var ico_vertexuv = [
  38282. 5, 1, 3, 1, 6, 4, 0, 0,
  38283. 5, 3, 4, 2, 2, 2, 4, 0,
  38284. 2, 0, 1, 1, 6, 0, 6, 2,
  38285. // vertex alias (for same vertex on different faces)
  38286. 0, 4,
  38287. 3, 3,
  38288. 4, 4,
  38289. 3, 1,
  38290. 4, 2,
  38291. 4, 4,
  38292. 0, 2,
  38293. 1, 1,
  38294. 2, 2,
  38295. 3, 3,
  38296. 1, 3,
  38297. 2, 4 // 23: B + 12
  38298. ];
  38299. // Vertices[0, 1, ...9, A, B] : position on UV plane
  38300. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  38301. // First island of uv mapping
  38302. // v = 4h 3+ 2
  38303. // v = 3h 9+ 4
  38304. // v = 2h 9+ 5 B
  38305. // v = 1h 9 1 0
  38306. // v = 0h 3 8 7 A
  38307. // u = 0 1 2 3 4 5 6 *a
  38308. // Second island of uv mapping
  38309. // v = 4h 0+ B+ 4+
  38310. // v = 3h A+ 2+
  38311. // v = 2h 7+ 6 3+
  38312. // v = 1h 8+ 3+
  38313. // v = 0h
  38314. // u = 0 1 2 3 4 5 6 *a
  38315. // Face layout on texture UV mapping
  38316. // ============
  38317. // \ 4 /\ 16 / ======
  38318. // \ / \ / /\ 11 /
  38319. // \/ 7 \/ / \ /
  38320. // ======= / 10 \/
  38321. // /\ 17 /\ =======
  38322. // / \ / \ \ 15 /\
  38323. // / 8 \/ 12 \ \ / \
  38324. // ============ \/ 6 \
  38325. // \ 18 /\ ============
  38326. // \ / \ \ 5 /\ 0 /
  38327. // \/ 13 \ \ / \ /
  38328. // ======= \/ 1 \/
  38329. // =============
  38330. // /\ 19 /\ 2 /\
  38331. // / \ / \ / \
  38332. // / 14 \/ 9 \/ 3 \
  38333. // ===================
  38334. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  38335. var ustep = 138 / 1024;
  38336. var vstep = 239 / 1024;
  38337. var uoffset = 60 / 1024;
  38338. var voffset = 26 / 1024;
  38339. // Second island should have margin, not to touch the first island
  38340. // avoid any borderline artefact in pixel rounding
  38341. var island_u_offset = -40 / 1024;
  38342. var island_v_offset = +20 / 1024;
  38343. // face is either island 0 or 1 :
  38344. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  38345. var island = [
  38346. 0, 0, 0, 0, 1,
  38347. 0, 0, 1, 1, 0,
  38348. 0, 0, 1, 1, 0,
  38349. 0, 1, 1, 1, 0 // 15 - 19
  38350. ];
  38351. var indices = new Array();
  38352. var positions = new Array();
  38353. var normals = new Array();
  38354. var uvs = new Array();
  38355. var current_indice = 0;
  38356. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  38357. var face_vertex_pos = new Array(3);
  38358. var face_vertex_uv = new Array(3);
  38359. var v012;
  38360. for (v012 = 0; v012 < 3; v012++) {
  38361. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  38362. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  38363. }
  38364. // create all with normals
  38365. for (var face = 0; face < 20; face++) {
  38366. // 3 vertex per face
  38367. for (v012 = 0; v012 < 3; v012++) {
  38368. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  38369. var v_id = ico_indices[3 * face + v012];
  38370. // vertex have 3D position (x,y,z)
  38371. 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]);
  38372. // Normalize to get normal, then scale to radius
  38373. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  38374. // uv Coordinates from vertex ID
  38375. 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);
  38376. }
  38377. // Subdivide the face (interpolate pos, norm, uv)
  38378. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  38379. // - norm is linear interpolation of vertex corner normal
  38380. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  38381. // - uv is linear interpolation
  38382. //
  38383. // Topology is as below for sub-divide by 2
  38384. // vertex shown as v0,v1,v2
  38385. // interp index is i1 to progress in range [v0,v1[
  38386. // interp index is i2 to progress in range [v0,v2[
  38387. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  38388. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38389. //
  38390. //
  38391. // i2 v2
  38392. // ^ ^
  38393. // / / \
  38394. // / / \
  38395. // / / \
  38396. // / / (0,1) \
  38397. // / #---------\
  38398. // / / \ (0,0)'/ \
  38399. // / / \ / \
  38400. // / / \ / \
  38401. // / / (0,0) \ / (1,0) \
  38402. // / #---------#---------\
  38403. // v0 v1
  38404. //
  38405. // --------------------> i1
  38406. //
  38407. // interp of (i1,i2):
  38408. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  38409. // along i1 : lerp(x0,x1, i1/(S-i2))
  38410. //
  38411. // centroid of triangle is needed to get help normal computation
  38412. // (c1,c2) are used for centroid location
  38413. var interp_vertex = function (i1, i2, c1, c2) {
  38414. // vertex is interpolated from
  38415. // - face_vertex_pos[0..2]
  38416. // - face_vertex_uv[0..2]
  38417. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  38418. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  38419. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  38420. pos_interp.normalize();
  38421. var vertex_normal;
  38422. if (flat) {
  38423. // in flat mode, recalculate normal as face centroid normal
  38424. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  38425. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  38426. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  38427. }
  38428. else {
  38429. // in smooth mode, recalculate normal from each single vertex position
  38430. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  38431. }
  38432. // Vertex normal need correction due to X,Y,Z radius scaling
  38433. vertex_normal.x /= radiusX;
  38434. vertex_normal.y /= radiusY;
  38435. vertex_normal.z /= radiusZ;
  38436. vertex_normal.normalize();
  38437. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  38438. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  38439. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  38440. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  38441. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  38442. uvs.push(uv_interp.x, uv_interp.y);
  38443. // push each vertex has member of a face
  38444. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  38445. indices.push(current_indice);
  38446. current_indice++;
  38447. };
  38448. for (var i2 = 0; i2 < subdivisions; i2++) {
  38449. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  38450. // face : (i1,i2) for /\ :
  38451. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  38452. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38453. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38454. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38455. if (i1 + i2 + 1 < subdivisions) {
  38456. // face : (i1,i2)' for \/ :
  38457. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38458. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38459. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38460. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38461. }
  38462. }
  38463. }
  38464. }
  38465. // Sides
  38466. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38467. // Result
  38468. var vertexData = new VertexData();
  38469. vertexData.indices = indices;
  38470. vertexData.positions = positions;
  38471. vertexData.normals = normals;
  38472. vertexData.uvs = uvs;
  38473. return vertexData;
  38474. };
  38475. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  38476. /**
  38477. * Creates the VertexData for a Polyhedron
  38478. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  38479. * * type provided types are:
  38480. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38481. * * 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)
  38482. * * size the size of the IcoSphere, optional default 1
  38483. * * sizeX allows stretching in the x direction, optional, default size
  38484. * * sizeY allows stretching in the y direction, optional, default size
  38485. * * sizeZ allows stretching in the z direction, optional, default size
  38486. * * 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
  38487. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  38488. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  38489. * * flat when true creates a flat shaded mesh, optional, default true
  38490. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  38491. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38492. * * 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)
  38493. * * 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)
  38494. * @returns the VertexData of the Polyhedron
  38495. */
  38496. VertexData.CreatePolyhedron = function (options) {
  38497. // provided polyhedron types :
  38498. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38499. // 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)
  38500. var polyhedra = [];
  38501. 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]] };
  38502. 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]] };
  38503. polyhedra[2] = {
  38504. 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]],
  38505. 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]]
  38506. };
  38507. polyhedra[3] = {
  38508. 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]],
  38509. 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]]
  38510. };
  38511. polyhedra[4] = {
  38512. 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]],
  38513. 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]]
  38514. };
  38515. 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]] };
  38516. 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]] };
  38517. 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]] };
  38518. 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]] };
  38519. 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]] };
  38520. 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]] };
  38521. 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]] };
  38522. 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]] };
  38523. 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]] };
  38524. polyhedra[14] = {
  38525. 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]],
  38526. 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]]
  38527. };
  38528. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  38529. var size = options.size;
  38530. var sizeX = options.sizeX || size || 1;
  38531. var sizeY = options.sizeY || size || 1;
  38532. var sizeZ = options.sizeZ || size || 1;
  38533. var data = options.custom || polyhedra[type];
  38534. var nbfaces = data.face.length;
  38535. var faceUV = options.faceUV || new Array(nbfaces);
  38536. var faceColors = options.faceColors;
  38537. var flat = (options.flat === undefined) ? true : options.flat;
  38538. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38539. var positions = new Array();
  38540. var indices = new Array();
  38541. var normals = new Array();
  38542. var uvs = new Array();
  38543. var colors = new Array();
  38544. var index = 0;
  38545. var faceIdx = 0; // face cursor in the array "indexes"
  38546. var indexes = new Array();
  38547. var i = 0;
  38548. var f = 0;
  38549. var u, v, ang, x, y, tmp;
  38550. // default face colors and UV if undefined
  38551. if (flat) {
  38552. for (f = 0; f < nbfaces; f++) {
  38553. if (faceColors && faceColors[f] === undefined) {
  38554. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38555. }
  38556. if (faceUV && faceUV[f] === undefined) {
  38557. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38558. }
  38559. }
  38560. }
  38561. if (!flat) {
  38562. for (i = 0; i < data.vertex.length; i++) {
  38563. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  38564. uvs.push(0, 0);
  38565. }
  38566. for (f = 0; f < nbfaces; f++) {
  38567. for (i = 0; i < data.face[f].length - 2; i++) {
  38568. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  38569. }
  38570. }
  38571. }
  38572. else {
  38573. for (f = 0; f < nbfaces; f++) {
  38574. var fl = data.face[f].length; // number of vertices of the current face
  38575. ang = 2 * Math.PI / fl;
  38576. x = 0.5 * Math.tan(ang / 2);
  38577. y = 0.5;
  38578. // positions, uvs, colors
  38579. for (i = 0; i < fl; i++) {
  38580. // positions
  38581. 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);
  38582. indexes.push(index);
  38583. index++;
  38584. // uvs
  38585. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  38586. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  38587. uvs.push(u, v);
  38588. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  38589. y = x * Math.sin(ang) + y * Math.cos(ang);
  38590. x = tmp;
  38591. // colors
  38592. if (faceColors) {
  38593. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  38594. }
  38595. }
  38596. // indices from indexes
  38597. for (i = 0; i < fl - 2; i++) {
  38598. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  38599. }
  38600. faceIdx += fl;
  38601. }
  38602. }
  38603. VertexData.ComputeNormals(positions, indices, normals);
  38604. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38605. var vertexData = new VertexData();
  38606. vertexData.positions = positions;
  38607. vertexData.indices = indices;
  38608. vertexData.normals = normals;
  38609. vertexData.uvs = uvs;
  38610. if (faceColors && flat) {
  38611. vertexData.colors = colors;
  38612. }
  38613. return vertexData;
  38614. };
  38615. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  38616. /**
  38617. * Creates the VertexData for a TorusKnot
  38618. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  38619. * * radius the radius of the torus knot, optional, default 2
  38620. * * tube the thickness of the tube, optional, default 0.5
  38621. * * radialSegments the number of sides on each tube segments, optional, default 32
  38622. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  38623. * * p the number of windings around the z axis, optional, default 2
  38624. * * q the number of windings around the x axis, optional, default 3
  38625. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38626. * * 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)
  38627. * * 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)
  38628. * @returns the VertexData of the Torus Knot
  38629. */
  38630. VertexData.CreateTorusKnot = function (options) {
  38631. var indices = new Array();
  38632. var positions = new Array();
  38633. var normals = new Array();
  38634. var uvs = new Array();
  38635. var radius = options.radius || 2;
  38636. var tube = options.tube || 0.5;
  38637. var radialSegments = options.radialSegments || 32;
  38638. var tubularSegments = options.tubularSegments || 32;
  38639. var p = options.p || 2;
  38640. var q = options.q || 3;
  38641. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38642. // Helper
  38643. var getPos = function (angle) {
  38644. var cu = Math.cos(angle);
  38645. var su = Math.sin(angle);
  38646. var quOverP = q / p * angle;
  38647. var cs = Math.cos(quOverP);
  38648. var tx = radius * (2 + cs) * 0.5 * cu;
  38649. var ty = radius * (2 + cs) * su * 0.5;
  38650. var tz = radius * Math.sin(quOverP) * 0.5;
  38651. return new BABYLON.Vector3(tx, ty, tz);
  38652. };
  38653. // Vertices
  38654. var i;
  38655. var j;
  38656. for (i = 0; i <= radialSegments; i++) {
  38657. var modI = i % radialSegments;
  38658. var u = modI / radialSegments * 2 * p * Math.PI;
  38659. var p1 = getPos(u);
  38660. var p2 = getPos(u + 0.01);
  38661. var tang = p2.subtract(p1);
  38662. var n = p2.add(p1);
  38663. var bitan = BABYLON.Vector3.Cross(tang, n);
  38664. n = BABYLON.Vector3.Cross(bitan, tang);
  38665. bitan.normalize();
  38666. n.normalize();
  38667. for (j = 0; j < tubularSegments; j++) {
  38668. var modJ = j % tubularSegments;
  38669. var v = modJ / tubularSegments * 2 * Math.PI;
  38670. var cx = -tube * Math.cos(v);
  38671. var cy = tube * Math.sin(v);
  38672. positions.push(p1.x + cx * n.x + cy * bitan.x);
  38673. positions.push(p1.y + cx * n.y + cy * bitan.y);
  38674. positions.push(p1.z + cx * n.z + cy * bitan.z);
  38675. uvs.push(i / radialSegments);
  38676. uvs.push(j / tubularSegments);
  38677. }
  38678. }
  38679. for (i = 0; i < radialSegments; i++) {
  38680. for (j = 0; j < tubularSegments; j++) {
  38681. var jNext = (j + 1) % tubularSegments;
  38682. var a = i * tubularSegments + j;
  38683. var b = (i + 1) * tubularSegments + j;
  38684. var c = (i + 1) * tubularSegments + jNext;
  38685. var d = i * tubularSegments + jNext;
  38686. indices.push(d);
  38687. indices.push(b);
  38688. indices.push(a);
  38689. indices.push(d);
  38690. indices.push(c);
  38691. indices.push(b);
  38692. }
  38693. }
  38694. // Normals
  38695. VertexData.ComputeNormals(positions, indices, normals);
  38696. // Sides
  38697. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38698. // Result
  38699. var vertexData = new VertexData();
  38700. vertexData.indices = indices;
  38701. vertexData.positions = positions;
  38702. vertexData.normals = normals;
  38703. vertexData.uvs = uvs;
  38704. return vertexData;
  38705. };
  38706. // Tools
  38707. /**
  38708. * Compute normals for given positions and indices
  38709. * @param positions an array of vertex positions, [...., x, y, z, ......]
  38710. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  38711. * @param normals an array of vertex normals, [...., x, y, z, ......]
  38712. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  38713. * * facetNormals : optional array of facet normals (vector3)
  38714. * * facetPositions : optional array of facet positions (vector3)
  38715. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  38716. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  38717. * * bInfo : optional bounding info, required for facetPartitioning computation
  38718. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  38719. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  38720. * * useRightHandedSystem: optional boolean to for right handed system computation
  38721. * * depthSort : optional boolean to enable the facet depth sort computation
  38722. * * distanceTo : optional Vector3 to compute the facet depth from this location
  38723. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  38724. */
  38725. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  38726. // temporary scalar variables
  38727. var index = 0; // facet index
  38728. var p1p2x = 0.0; // p1p2 vector x coordinate
  38729. var p1p2y = 0.0; // p1p2 vector y coordinate
  38730. var p1p2z = 0.0; // p1p2 vector z coordinate
  38731. var p3p2x = 0.0; // p3p2 vector x coordinate
  38732. var p3p2y = 0.0; // p3p2 vector y coordinate
  38733. var p3p2z = 0.0; // p3p2 vector z coordinate
  38734. var faceNormalx = 0.0; // facet normal x coordinate
  38735. var faceNormaly = 0.0; // facet normal y coordinate
  38736. var faceNormalz = 0.0; // facet normal z coordinate
  38737. var length = 0.0; // facet normal length before normalization
  38738. var v1x = 0; // vector1 x index in the positions array
  38739. var v1y = 0; // vector1 y index in the positions array
  38740. var v1z = 0; // vector1 z index in the positions array
  38741. var v2x = 0; // vector2 x index in the positions array
  38742. var v2y = 0; // vector2 y index in the positions array
  38743. var v2z = 0; // vector2 z index in the positions array
  38744. var v3x = 0; // vector3 x index in the positions array
  38745. var v3y = 0; // vector3 y index in the positions array
  38746. var v3z = 0; // vector3 z index in the positions array
  38747. var computeFacetNormals = false;
  38748. var computeFacetPositions = false;
  38749. var computeFacetPartitioning = false;
  38750. var computeDepthSort = false;
  38751. var faceNormalSign = 1;
  38752. var ratio = 0;
  38753. var distanceTo = null;
  38754. if (options) {
  38755. computeFacetNormals = (options.facetNormals) ? true : false;
  38756. computeFacetPositions = (options.facetPositions) ? true : false;
  38757. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  38758. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  38759. ratio = options.ratio || 0;
  38760. computeDepthSort = (options.depthSort) ? true : false;
  38761. distanceTo = (options.distanceTo);
  38762. if (computeDepthSort) {
  38763. if (distanceTo === undefined) {
  38764. distanceTo = BABYLON.Vector3.Zero();
  38765. }
  38766. var depthSortedFacets = options.depthSortedFacets;
  38767. }
  38768. }
  38769. // facetPartitioning reinit if needed
  38770. var xSubRatio = 0;
  38771. var ySubRatio = 0;
  38772. var zSubRatio = 0;
  38773. var subSq = 0;
  38774. if (computeFacetPartitioning && options && options.bbSize) {
  38775. var ox = 0; // X partitioning index for facet position
  38776. var oy = 0; // Y partinioning index for facet position
  38777. var oz = 0; // Z partinioning index for facet position
  38778. var b1x = 0; // X partitioning index for facet v1 vertex
  38779. var b1y = 0; // Y partitioning index for facet v1 vertex
  38780. var b1z = 0; // z partitioning index for facet v1 vertex
  38781. var b2x = 0; // X partitioning index for facet v2 vertex
  38782. var b2y = 0; // Y partitioning index for facet v2 vertex
  38783. var b2z = 0; // Z partitioning index for facet v2 vertex
  38784. var b3x = 0; // X partitioning index for facet v3 vertex
  38785. var b3y = 0; // Y partitioning index for facet v3 vertex
  38786. var b3z = 0; // Z partitioning index for facet v3 vertex
  38787. var block_idx_o = 0; // facet barycenter block index
  38788. var block_idx_v1 = 0; // v1 vertex block index
  38789. var block_idx_v2 = 0; // v2 vertex block index
  38790. var block_idx_v3 = 0; // v3 vertex block index
  38791. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  38792. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  38793. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  38794. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  38795. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  38796. subSq = options.subDiv.max * options.subDiv.max;
  38797. options.facetPartitioning.length = 0;
  38798. }
  38799. // reset the normals
  38800. for (index = 0; index < positions.length; index++) {
  38801. normals[index] = 0.0;
  38802. }
  38803. // Loop : 1 indice triplet = 1 facet
  38804. var nbFaces = (indices.length / 3) | 0;
  38805. for (index = 0; index < nbFaces; index++) {
  38806. // get the indexes of the coordinates of each vertex of the facet
  38807. v1x = indices[index * 3] * 3;
  38808. v1y = v1x + 1;
  38809. v1z = v1x + 2;
  38810. v2x = indices[index * 3 + 1] * 3;
  38811. v2y = v2x + 1;
  38812. v2z = v2x + 2;
  38813. v3x = indices[index * 3 + 2] * 3;
  38814. v3y = v3x + 1;
  38815. v3z = v3x + 2;
  38816. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  38817. p1p2y = positions[v1y] - positions[v2y];
  38818. p1p2z = positions[v1z] - positions[v2z];
  38819. p3p2x = positions[v3x] - positions[v2x];
  38820. p3p2y = positions[v3y] - positions[v2y];
  38821. p3p2z = positions[v3z] - positions[v2z];
  38822. // compute the face normal with the cross product
  38823. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  38824. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  38825. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  38826. // normalize this normal and store it in the array facetData
  38827. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38828. length = (length === 0) ? 1.0 : length;
  38829. faceNormalx /= length;
  38830. faceNormaly /= length;
  38831. faceNormalz /= length;
  38832. if (computeFacetNormals && options) {
  38833. options.facetNormals[index].x = faceNormalx;
  38834. options.facetNormals[index].y = faceNormaly;
  38835. options.facetNormals[index].z = faceNormalz;
  38836. }
  38837. if (computeFacetPositions && options) {
  38838. // compute and the facet barycenter coordinates in the array facetPositions
  38839. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  38840. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  38841. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  38842. }
  38843. if (computeFacetPartitioning && options) {
  38844. // store the facet indexes in arrays in the main facetPartitioning array :
  38845. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  38846. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  38847. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  38848. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  38849. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38850. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38851. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38852. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38853. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38854. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38855. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38856. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38857. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38858. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  38859. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  38860. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  38861. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  38862. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  38863. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  38864. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  38865. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  38866. // push each facet index in each block containing the vertex
  38867. options.facetPartitioning[block_idx_v1].push(index);
  38868. if (block_idx_v2 != block_idx_v1) {
  38869. options.facetPartitioning[block_idx_v2].push(index);
  38870. }
  38871. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  38872. options.facetPartitioning[block_idx_v3].push(index);
  38873. }
  38874. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  38875. options.facetPartitioning[block_idx_o].push(index);
  38876. }
  38877. }
  38878. if (computeDepthSort && options && options.facetPositions) {
  38879. var dsf = depthSortedFacets[index];
  38880. dsf.ind = index * 3;
  38881. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  38882. }
  38883. // compute the normals anyway
  38884. normals[v1x] += faceNormalx; // accumulate all the normals per face
  38885. normals[v1y] += faceNormaly;
  38886. normals[v1z] += faceNormalz;
  38887. normals[v2x] += faceNormalx;
  38888. normals[v2y] += faceNormaly;
  38889. normals[v2z] += faceNormalz;
  38890. normals[v3x] += faceNormalx;
  38891. normals[v3y] += faceNormaly;
  38892. normals[v3z] += faceNormalz;
  38893. }
  38894. // last normalization of each normal
  38895. for (index = 0; index < normals.length / 3; index++) {
  38896. faceNormalx = normals[index * 3];
  38897. faceNormaly = normals[index * 3 + 1];
  38898. faceNormalz = normals[index * 3 + 2];
  38899. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38900. length = (length === 0) ? 1.0 : length;
  38901. faceNormalx /= length;
  38902. faceNormaly /= length;
  38903. faceNormalz /= length;
  38904. normals[index * 3] = faceNormalx;
  38905. normals[index * 3 + 1] = faceNormaly;
  38906. normals[index * 3 + 2] = faceNormalz;
  38907. }
  38908. };
  38909. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  38910. var li = indices.length;
  38911. var ln = normals.length;
  38912. var i;
  38913. var n;
  38914. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38915. switch (sideOrientation) {
  38916. case BABYLON.Mesh.FRONTSIDE:
  38917. // nothing changed
  38918. break;
  38919. case BABYLON.Mesh.BACKSIDE:
  38920. var tmp;
  38921. // indices
  38922. for (i = 0; i < li; i += 3) {
  38923. tmp = indices[i];
  38924. indices[i] = indices[i + 2];
  38925. indices[i + 2] = tmp;
  38926. }
  38927. // normals
  38928. for (n = 0; n < ln; n++) {
  38929. normals[n] = -normals[n];
  38930. }
  38931. break;
  38932. case BABYLON.Mesh.DOUBLESIDE:
  38933. // positions
  38934. var lp = positions.length;
  38935. var l = lp / 3;
  38936. for (var p = 0; p < lp; p++) {
  38937. positions[lp + p] = positions[p];
  38938. }
  38939. // indices
  38940. for (i = 0; i < li; i += 3) {
  38941. indices[i + li] = indices[i + 2] + l;
  38942. indices[i + 1 + li] = indices[i + 1] + l;
  38943. indices[i + 2 + li] = indices[i] + l;
  38944. }
  38945. // normals
  38946. for (n = 0; n < ln; n++) {
  38947. normals[ln + n] = -normals[n];
  38948. }
  38949. // uvs
  38950. var lu = uvs.length;
  38951. var u = 0;
  38952. for (u = 0; u < lu; u++) {
  38953. uvs[u + lu] = uvs[u];
  38954. }
  38955. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38956. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38957. u = 0;
  38958. for (i = 0; i < lu / 2; i++) {
  38959. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  38960. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  38961. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  38962. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  38963. u += 2;
  38964. }
  38965. break;
  38966. }
  38967. };
  38968. /**
  38969. * Applies VertexData created from the imported parameters to the geometry
  38970. * @param parsedVertexData the parsed data from an imported file
  38971. * @param geometry the geometry to apply the VertexData to
  38972. */
  38973. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  38974. var vertexData = new VertexData();
  38975. // positions
  38976. var positions = parsedVertexData.positions;
  38977. if (positions) {
  38978. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  38979. }
  38980. // normals
  38981. var normals = parsedVertexData.normals;
  38982. if (normals) {
  38983. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  38984. }
  38985. // tangents
  38986. var tangents = parsedVertexData.tangents;
  38987. if (tangents) {
  38988. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  38989. }
  38990. // uvs
  38991. var uvs = parsedVertexData.uvs;
  38992. if (uvs) {
  38993. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  38994. }
  38995. // uv2s
  38996. var uv2s = parsedVertexData.uv2s;
  38997. if (uv2s) {
  38998. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  38999. }
  39000. // uv3s
  39001. var uv3s = parsedVertexData.uv3s;
  39002. if (uv3s) {
  39003. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  39004. }
  39005. // uv4s
  39006. var uv4s = parsedVertexData.uv4s;
  39007. if (uv4s) {
  39008. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  39009. }
  39010. // uv5s
  39011. var uv5s = parsedVertexData.uv5s;
  39012. if (uv5s) {
  39013. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  39014. }
  39015. // uv6s
  39016. var uv6s = parsedVertexData.uv6s;
  39017. if (uv6s) {
  39018. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  39019. }
  39020. // colors
  39021. var colors = parsedVertexData.colors;
  39022. if (colors) {
  39023. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  39024. }
  39025. // matricesIndices
  39026. var matricesIndices = parsedVertexData.matricesIndices;
  39027. if (matricesIndices) {
  39028. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  39029. }
  39030. // matricesWeights
  39031. var matricesWeights = parsedVertexData.matricesWeights;
  39032. if (matricesWeights) {
  39033. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  39034. }
  39035. // indices
  39036. var indices = parsedVertexData.indices;
  39037. if (indices) {
  39038. vertexData.indices = indices;
  39039. }
  39040. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  39041. };
  39042. return VertexData;
  39043. }());
  39044. BABYLON.VertexData = VertexData;
  39045. })(BABYLON || (BABYLON = {}));
  39046. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  39047. var BABYLON;
  39048. (function (BABYLON) {
  39049. /**
  39050. * Class used to store geometry data (vertex buffers + index buffer)
  39051. */
  39052. var Geometry = /** @class */ (function () {
  39053. /**
  39054. * Creates a new geometry
  39055. * @param id defines the unique ID
  39056. * @param scene defines the hosting scene
  39057. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  39058. * @param updatable defines if geometry must be updatable (false by default)
  39059. * @param mesh defines the mesh that will be associated with the geometry
  39060. */
  39061. function Geometry(id, scene, vertexData, updatable, mesh) {
  39062. if (updatable === void 0) { updatable = false; }
  39063. if (mesh === void 0) { mesh = null; }
  39064. /**
  39065. * Gets the delay loading state of the geometry (none by default which means not delayed)
  39066. */
  39067. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39068. this._totalVertices = 0;
  39069. this._isDisposed = false;
  39070. this._indexBufferIsUpdatable = false;
  39071. this.id = id;
  39072. this._engine = scene.getEngine();
  39073. this._meshes = [];
  39074. this._scene = scene;
  39075. //Init vertex buffer cache
  39076. this._vertexBuffers = {};
  39077. this._indices = [];
  39078. this._updatable = updatable;
  39079. // vertexData
  39080. if (vertexData) {
  39081. this.setAllVerticesData(vertexData, updatable);
  39082. }
  39083. else {
  39084. this._totalVertices = 0;
  39085. this._indices = [];
  39086. }
  39087. if (this._engine.getCaps().vertexArrayObject) {
  39088. this._vertexArrayObjects = {};
  39089. }
  39090. // applyToMesh
  39091. if (mesh) {
  39092. if (mesh.getClassName() === "LinesMesh") {
  39093. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  39094. this._updateExtend();
  39095. }
  39096. this.applyToMesh(mesh);
  39097. mesh.computeWorldMatrix(true);
  39098. }
  39099. }
  39100. Object.defineProperty(Geometry.prototype, "boundingBias", {
  39101. /**
  39102. * 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
  39103. */
  39104. get: function () {
  39105. return this._boundingBias;
  39106. },
  39107. /**
  39108. * 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
  39109. */
  39110. set: function (value) {
  39111. if (this._boundingBias && this._boundingBias.equals(value)) {
  39112. return;
  39113. }
  39114. this._boundingBias = value.clone();
  39115. this._updateBoundingInfo(true, null);
  39116. },
  39117. enumerable: true,
  39118. configurable: true
  39119. });
  39120. /**
  39121. * Static function used to attach a new empty geometry to a mesh
  39122. * @param mesh defines the mesh to attach the geometry to
  39123. * @returns the new {BABYLON.Geometry}
  39124. */
  39125. Geometry.CreateGeometryForMesh = function (mesh) {
  39126. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  39127. geometry.applyToMesh(mesh);
  39128. return geometry;
  39129. };
  39130. Object.defineProperty(Geometry.prototype, "extend", {
  39131. /**
  39132. * Gets the current extend of the geometry
  39133. */
  39134. get: function () {
  39135. return this._extend;
  39136. },
  39137. enumerable: true,
  39138. configurable: true
  39139. });
  39140. /**
  39141. * Gets the hosting scene
  39142. * @returns the hosting {BABYLON.Scene}
  39143. */
  39144. Geometry.prototype.getScene = function () {
  39145. return this._scene;
  39146. };
  39147. /**
  39148. * Gets the hosting engine
  39149. * @returns the hosting {BABYLON.Engine}
  39150. */
  39151. Geometry.prototype.getEngine = function () {
  39152. return this._engine;
  39153. };
  39154. /**
  39155. * Defines if the geometry is ready to use
  39156. * @returns true if the geometry is ready to be used
  39157. */
  39158. Geometry.prototype.isReady = function () {
  39159. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  39160. };
  39161. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  39162. /**
  39163. * Gets a value indicating that the geometry should not be serialized
  39164. */
  39165. get: function () {
  39166. for (var index = 0; index < this._meshes.length; index++) {
  39167. if (!this._meshes[index].doNotSerialize) {
  39168. return false;
  39169. }
  39170. }
  39171. return true;
  39172. },
  39173. enumerable: true,
  39174. configurable: true
  39175. });
  39176. /** @hidden */
  39177. Geometry.prototype._rebuild = function () {
  39178. if (this._vertexArrayObjects) {
  39179. this._vertexArrayObjects = {};
  39180. }
  39181. // Index buffer
  39182. if (this._meshes.length !== 0 && this._indices) {
  39183. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39184. }
  39185. // Vertex buffers
  39186. for (var key in this._vertexBuffers) {
  39187. var vertexBuffer = this._vertexBuffers[key];
  39188. vertexBuffer._rebuild();
  39189. }
  39190. };
  39191. /**
  39192. * Affects all gemetry data in one call
  39193. * @param vertexData defines the geometry data
  39194. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  39195. */
  39196. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  39197. vertexData.applyToGeometry(this, updatable);
  39198. this.notifyUpdate();
  39199. };
  39200. /**
  39201. * Set specific vertex data
  39202. * @param kind defines the data kind (Position, normal, etc...)
  39203. * @param data defines the vertex data to use
  39204. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  39205. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  39206. */
  39207. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  39208. if (updatable === void 0) { updatable = false; }
  39209. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  39210. this.setVerticesBuffer(buffer);
  39211. };
  39212. /**
  39213. * Removes a specific vertex data
  39214. * @param kind defines the data kind (Position, normal, etc...)
  39215. */
  39216. Geometry.prototype.removeVerticesData = function (kind) {
  39217. if (this._vertexBuffers[kind]) {
  39218. this._vertexBuffers[kind].dispose();
  39219. delete this._vertexBuffers[kind];
  39220. }
  39221. };
  39222. /**
  39223. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  39224. * @param buffer defines the vertex buffer to use
  39225. * @param totalVertices defines the total number of vertices for position kind (could be null)
  39226. */
  39227. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  39228. if (totalVertices === void 0) { totalVertices = null; }
  39229. var kind = buffer.getKind();
  39230. if (this._vertexBuffers[kind]) {
  39231. this._vertexBuffers[kind].dispose();
  39232. }
  39233. this._vertexBuffers[kind] = buffer;
  39234. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39235. var data = buffer.getData();
  39236. if (totalVertices != null) {
  39237. this._totalVertices = totalVertices;
  39238. }
  39239. else {
  39240. if (data != null) {
  39241. this._totalVertices = data.length / (buffer.byteStride / 4);
  39242. }
  39243. }
  39244. this._updateExtend(data);
  39245. this._resetPointsArrayCache();
  39246. var meshes = this._meshes;
  39247. var numOfMeshes = meshes.length;
  39248. for (var index = 0; index < numOfMeshes; index++) {
  39249. var mesh = meshes[index];
  39250. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39251. mesh._createGlobalSubMesh(false);
  39252. mesh.computeWorldMatrix(true);
  39253. }
  39254. }
  39255. this.notifyUpdate(kind);
  39256. if (this._vertexArrayObjects) {
  39257. this._disposeVertexArrayObjects();
  39258. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  39259. }
  39260. };
  39261. /**
  39262. * Update a specific vertex buffer
  39263. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  39264. * It will do nothing if the buffer is not updatable
  39265. * @param kind defines the data kind (Position, normal, etc...)
  39266. * @param data defines the data to use
  39267. * @param offset defines the offset in the target buffer where to store the data
  39268. * @param useBytes set to true if the offset is in bytes
  39269. */
  39270. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  39271. if (useBytes === void 0) { useBytes = false; }
  39272. var vertexBuffer = this.getVertexBuffer(kind);
  39273. if (!vertexBuffer) {
  39274. return;
  39275. }
  39276. vertexBuffer.updateDirectly(data, offset, useBytes);
  39277. this.notifyUpdate(kind);
  39278. };
  39279. /**
  39280. * Update a specific vertex buffer
  39281. * This function will create a new buffer if the current one is not updatable
  39282. * @param kind defines the data kind (Position, normal, etc...)
  39283. * @param data defines the data to use
  39284. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  39285. */
  39286. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  39287. if (updateExtends === void 0) { updateExtends = false; }
  39288. var vertexBuffer = this.getVertexBuffer(kind);
  39289. if (!vertexBuffer) {
  39290. return;
  39291. }
  39292. vertexBuffer.update(data);
  39293. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39294. this._updateBoundingInfo(updateExtends, data);
  39295. }
  39296. this.notifyUpdate(kind);
  39297. };
  39298. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  39299. if (updateExtends) {
  39300. this._updateExtend(data);
  39301. }
  39302. var meshes = this._meshes;
  39303. var numOfMeshes = meshes.length;
  39304. this._resetPointsArrayCache();
  39305. for (var index = 0; index < numOfMeshes; index++) {
  39306. var mesh = meshes[index];
  39307. if (updateExtends) {
  39308. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39309. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  39310. var subMesh = mesh.subMeshes[subIndex];
  39311. subMesh.refreshBoundingInfo();
  39312. }
  39313. }
  39314. }
  39315. };
  39316. /** @hidden */
  39317. Geometry.prototype._bind = function (effect, indexToBind) {
  39318. if (!effect) {
  39319. return;
  39320. }
  39321. if (indexToBind === undefined) {
  39322. indexToBind = this._indexBuffer;
  39323. }
  39324. var vbs = this.getVertexBuffers();
  39325. if (!vbs) {
  39326. return;
  39327. }
  39328. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  39329. this._engine.bindBuffers(vbs, indexToBind, effect);
  39330. return;
  39331. }
  39332. // Using VAO
  39333. if (!this._vertexArrayObjects[effect.key]) {
  39334. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  39335. }
  39336. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  39337. };
  39338. /**
  39339. * Gets total number of vertices
  39340. * @returns the total number of vertices
  39341. */
  39342. Geometry.prototype.getTotalVertices = function () {
  39343. if (!this.isReady()) {
  39344. return 0;
  39345. }
  39346. return this._totalVertices;
  39347. };
  39348. /**
  39349. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  39350. * @param kind defines the data kind (Position, normal, etc...)
  39351. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39352. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  39353. * @returns a float array containing vertex data
  39354. */
  39355. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  39356. var vertexBuffer = this.getVertexBuffer(kind);
  39357. if (!vertexBuffer) {
  39358. return null;
  39359. }
  39360. var data = vertexBuffer.getData();
  39361. if (!data) {
  39362. return null;
  39363. }
  39364. var tightlyPackedByteStride = vertexBuffer.getSize() * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  39365. var count = this._totalVertices * vertexBuffer.getSize();
  39366. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== tightlyPackedByteStride) {
  39367. var copy_1 = new Array(count);
  39368. vertexBuffer.forEach(count, function (value, index) {
  39369. copy_1[index] = value;
  39370. });
  39371. return copy_1;
  39372. }
  39373. if (!((data instanceof Array) || (data instanceof Float32Array)) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  39374. if (data instanceof Array) {
  39375. var offset = vertexBuffer.byteOffset / 4;
  39376. return BABYLON.Tools.Slice(data, offset, offset + count);
  39377. }
  39378. else if (data instanceof ArrayBuffer) {
  39379. return new Float32Array(data, vertexBuffer.byteOffset, count);
  39380. }
  39381. else {
  39382. return new Float32Array(data.buffer, data.byteOffset + vertexBuffer.byteOffset, count);
  39383. }
  39384. }
  39385. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  39386. return BABYLON.Tools.Slice(data);
  39387. }
  39388. return data;
  39389. };
  39390. /**
  39391. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  39392. * @param kind defines the data kind (Position, normal, etc...)
  39393. * @returns true if the vertex buffer with the specified kind is updatable
  39394. */
  39395. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  39396. var vb = this._vertexBuffers[kind];
  39397. if (!vb) {
  39398. return false;
  39399. }
  39400. return vb.isUpdatable();
  39401. };
  39402. /**
  39403. * Gets a specific vertex buffer
  39404. * @param kind defines the data kind (Position, normal, etc...)
  39405. * @returns a {BABYLON.VertexBuffer}
  39406. */
  39407. Geometry.prototype.getVertexBuffer = function (kind) {
  39408. if (!this.isReady()) {
  39409. return null;
  39410. }
  39411. return this._vertexBuffers[kind];
  39412. };
  39413. /**
  39414. * Returns all vertex buffers
  39415. * @return an object holding all vertex buffers indexed by kind
  39416. */
  39417. Geometry.prototype.getVertexBuffers = function () {
  39418. if (!this.isReady()) {
  39419. return null;
  39420. }
  39421. return this._vertexBuffers;
  39422. };
  39423. /**
  39424. * Gets a boolean indicating if specific vertex buffer is present
  39425. * @param kind defines the data kind (Position, normal, etc...)
  39426. * @returns true if data is present
  39427. */
  39428. Geometry.prototype.isVerticesDataPresent = function (kind) {
  39429. if (!this._vertexBuffers) {
  39430. if (this._delayInfo) {
  39431. return this._delayInfo.indexOf(kind) !== -1;
  39432. }
  39433. return false;
  39434. }
  39435. return this._vertexBuffers[kind] !== undefined;
  39436. };
  39437. /**
  39438. * Gets a list of all attached data kinds (Position, normal, etc...)
  39439. * @returns a list of string containing all kinds
  39440. */
  39441. Geometry.prototype.getVerticesDataKinds = function () {
  39442. var result = [];
  39443. var kind;
  39444. if (!this._vertexBuffers && this._delayInfo) {
  39445. for (kind in this._delayInfo) {
  39446. result.push(kind);
  39447. }
  39448. }
  39449. else {
  39450. for (kind in this._vertexBuffers) {
  39451. result.push(kind);
  39452. }
  39453. }
  39454. return result;
  39455. };
  39456. /**
  39457. * Update index buffer
  39458. * @param indices defines the indices to store in the index buffer
  39459. * @param offset defines the offset in the target buffer where to store the data
  39460. */
  39461. Geometry.prototype.updateIndices = function (indices, offset) {
  39462. if (!this._indexBuffer) {
  39463. return;
  39464. }
  39465. if (!this._indexBufferIsUpdatable) {
  39466. this.setIndices(indices, null, true);
  39467. }
  39468. else {
  39469. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  39470. }
  39471. };
  39472. /**
  39473. * Creates a new index buffer
  39474. * @param indices defines the indices to store in the index buffer
  39475. * @param totalVertices defines the total number of vertices (could be null)
  39476. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  39477. */
  39478. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  39479. if (totalVertices === void 0) { totalVertices = null; }
  39480. if (updatable === void 0) { updatable = false; }
  39481. if (this._indexBuffer) {
  39482. this._engine._releaseBuffer(this._indexBuffer);
  39483. }
  39484. this._disposeVertexArrayObjects();
  39485. this._indices = indices;
  39486. this._indexBufferIsUpdatable = updatable;
  39487. if (this._meshes.length !== 0 && this._indices) {
  39488. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  39489. }
  39490. if (totalVertices != undefined) { // including null and undefined
  39491. this._totalVertices = totalVertices;
  39492. }
  39493. var meshes = this._meshes;
  39494. var numOfMeshes = meshes.length;
  39495. for (var index = 0; index < numOfMeshes; index++) {
  39496. meshes[index]._createGlobalSubMesh(true);
  39497. }
  39498. this.notifyUpdate();
  39499. };
  39500. /**
  39501. * Return the total number of indices
  39502. * @returns the total number of indices
  39503. */
  39504. Geometry.prototype.getTotalIndices = function () {
  39505. if (!this.isReady()) {
  39506. return 0;
  39507. }
  39508. return this._indices.length;
  39509. };
  39510. /**
  39511. * Gets the index buffer array
  39512. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39513. * @returns the index buffer array
  39514. */
  39515. Geometry.prototype.getIndices = function (copyWhenShared) {
  39516. if (!this.isReady()) {
  39517. return null;
  39518. }
  39519. var orig = this._indices;
  39520. if (!copyWhenShared || this._meshes.length === 1) {
  39521. return orig;
  39522. }
  39523. else {
  39524. var len = orig.length;
  39525. var copy = [];
  39526. for (var i = 0; i < len; i++) {
  39527. copy.push(orig[i]);
  39528. }
  39529. return copy;
  39530. }
  39531. };
  39532. /**
  39533. * Gets the index buffer
  39534. * @return the index buffer
  39535. */
  39536. Geometry.prototype.getIndexBuffer = function () {
  39537. if (!this.isReady()) {
  39538. return null;
  39539. }
  39540. return this._indexBuffer;
  39541. };
  39542. /** @hidden */
  39543. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  39544. if (effect === void 0) { effect = null; }
  39545. if (!effect || !this._vertexArrayObjects) {
  39546. return;
  39547. }
  39548. if (this._vertexArrayObjects[effect.key]) {
  39549. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  39550. delete this._vertexArrayObjects[effect.key];
  39551. }
  39552. };
  39553. /**
  39554. * Release the associated resources for a specific mesh
  39555. * @param mesh defines the source mesh
  39556. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  39557. */
  39558. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  39559. var meshes = this._meshes;
  39560. var index = meshes.indexOf(mesh);
  39561. if (index === -1) {
  39562. return;
  39563. }
  39564. meshes.splice(index, 1);
  39565. mesh._geometry = null;
  39566. if (meshes.length === 0 && shouldDispose) {
  39567. this.dispose();
  39568. }
  39569. };
  39570. /**
  39571. * Apply current geometry to a given mesh
  39572. * @param mesh defines the mesh to apply geometry to
  39573. */
  39574. Geometry.prototype.applyToMesh = function (mesh) {
  39575. if (mesh._geometry === this) {
  39576. return;
  39577. }
  39578. var previousGeometry = mesh._geometry;
  39579. if (previousGeometry) {
  39580. previousGeometry.releaseForMesh(mesh);
  39581. }
  39582. var meshes = this._meshes;
  39583. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  39584. mesh._geometry = this;
  39585. this._scene.pushGeometry(this);
  39586. meshes.push(mesh);
  39587. if (this.isReady()) {
  39588. this._applyToMesh(mesh);
  39589. }
  39590. else {
  39591. mesh._boundingInfo = this._boundingInfo;
  39592. }
  39593. };
  39594. Geometry.prototype._updateExtend = function (data) {
  39595. if (data === void 0) { data = null; }
  39596. if (!data) {
  39597. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39598. }
  39599. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  39600. };
  39601. Geometry.prototype._applyToMesh = function (mesh) {
  39602. var numOfMeshes = this._meshes.length;
  39603. // vertexBuffers
  39604. for (var kind in this._vertexBuffers) {
  39605. if (numOfMeshes === 1) {
  39606. this._vertexBuffers[kind].create();
  39607. }
  39608. var buffer = this._vertexBuffers[kind].getBuffer();
  39609. if (buffer)
  39610. buffer.references = numOfMeshes;
  39611. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39612. if (!this._extend) {
  39613. this._updateExtend();
  39614. }
  39615. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39616. mesh._createGlobalSubMesh(false);
  39617. //bounding info was just created again, world matrix should be applied again.
  39618. mesh._updateBoundingInfo();
  39619. }
  39620. }
  39621. // indexBuffer
  39622. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  39623. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39624. }
  39625. if (this._indexBuffer) {
  39626. this._indexBuffer.references = numOfMeshes;
  39627. }
  39628. };
  39629. Geometry.prototype.notifyUpdate = function (kind) {
  39630. if (this.onGeometryUpdated) {
  39631. this.onGeometryUpdated(this, kind);
  39632. }
  39633. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  39634. var mesh = _a[_i];
  39635. mesh._markSubMeshesAsAttributesDirty();
  39636. }
  39637. };
  39638. /**
  39639. * Load the geometry if it was flagged as delay loaded
  39640. * @param scene defines the hosting scene
  39641. * @param onLoaded defines a callback called when the geometry is loaded
  39642. */
  39643. Geometry.prototype.load = function (scene, onLoaded) {
  39644. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  39645. return;
  39646. }
  39647. if (this.isReady()) {
  39648. if (onLoaded) {
  39649. onLoaded();
  39650. }
  39651. return;
  39652. }
  39653. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  39654. this._queueLoad(scene, onLoaded);
  39655. };
  39656. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  39657. var _this = this;
  39658. if (!this.delayLoadingFile) {
  39659. return;
  39660. }
  39661. scene._addPendingData(this);
  39662. scene._loadFile(this.delayLoadingFile, function (data) {
  39663. if (!_this._delayLoadingFunction) {
  39664. return;
  39665. }
  39666. _this._delayLoadingFunction(JSON.parse(data), _this);
  39667. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  39668. _this._delayInfo = [];
  39669. scene._removePendingData(_this);
  39670. var meshes = _this._meshes;
  39671. var numOfMeshes = meshes.length;
  39672. for (var index = 0; index < numOfMeshes; index++) {
  39673. _this._applyToMesh(meshes[index]);
  39674. }
  39675. if (onLoaded) {
  39676. onLoaded();
  39677. }
  39678. }, undefined, true);
  39679. };
  39680. /**
  39681. * Invert the geometry to move from a right handed system to a left handed one.
  39682. */
  39683. Geometry.prototype.toLeftHanded = function () {
  39684. // Flip faces
  39685. var tIndices = this.getIndices(false);
  39686. if (tIndices != null && tIndices.length > 0) {
  39687. for (var i = 0; i < tIndices.length; i += 3) {
  39688. var tTemp = tIndices[i + 0];
  39689. tIndices[i + 0] = tIndices[i + 2];
  39690. tIndices[i + 2] = tTemp;
  39691. }
  39692. this.setIndices(tIndices);
  39693. }
  39694. // Negate position.z
  39695. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  39696. if (tPositions != null && tPositions.length > 0) {
  39697. for (var i = 0; i < tPositions.length; i += 3) {
  39698. tPositions[i + 2] = -tPositions[i + 2];
  39699. }
  39700. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  39701. }
  39702. // Negate normal.z
  39703. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  39704. if (tNormals != null && tNormals.length > 0) {
  39705. for (var i = 0; i < tNormals.length; i += 3) {
  39706. tNormals[i + 2] = -tNormals[i + 2];
  39707. }
  39708. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  39709. }
  39710. };
  39711. // Cache
  39712. /** @hidden */
  39713. Geometry.prototype._resetPointsArrayCache = function () {
  39714. this._positions = null;
  39715. };
  39716. /** @hidden */
  39717. Geometry.prototype._generatePointsArray = function () {
  39718. if (this._positions)
  39719. return true;
  39720. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39721. if (!data || data.length === 0) {
  39722. return false;
  39723. }
  39724. this._positions = [];
  39725. for (var index = 0; index < data.length; index += 3) {
  39726. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  39727. }
  39728. return true;
  39729. };
  39730. /**
  39731. * Gets a value indicating if the geometry is disposed
  39732. * @returns true if the geometry was disposed
  39733. */
  39734. Geometry.prototype.isDisposed = function () {
  39735. return this._isDisposed;
  39736. };
  39737. Geometry.prototype._disposeVertexArrayObjects = function () {
  39738. if (this._vertexArrayObjects) {
  39739. for (var kind in this._vertexArrayObjects) {
  39740. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  39741. }
  39742. this._vertexArrayObjects = {};
  39743. }
  39744. };
  39745. /**
  39746. * Free all associated resources
  39747. */
  39748. Geometry.prototype.dispose = function () {
  39749. var meshes = this._meshes;
  39750. var numOfMeshes = meshes.length;
  39751. var index;
  39752. for (index = 0; index < numOfMeshes; index++) {
  39753. this.releaseForMesh(meshes[index]);
  39754. }
  39755. this._meshes = [];
  39756. this._disposeVertexArrayObjects();
  39757. for (var kind in this._vertexBuffers) {
  39758. this._vertexBuffers[kind].dispose();
  39759. }
  39760. this._vertexBuffers = {};
  39761. this._totalVertices = 0;
  39762. if (this._indexBuffer) {
  39763. this._engine._releaseBuffer(this._indexBuffer);
  39764. }
  39765. this._indexBuffer = null;
  39766. this._indices = [];
  39767. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39768. this.delayLoadingFile = null;
  39769. this._delayLoadingFunction = null;
  39770. this._delayInfo = [];
  39771. this._boundingInfo = null;
  39772. this._scene.removeGeometry(this);
  39773. this._isDisposed = true;
  39774. };
  39775. /**
  39776. * Clone the current geometry into a new geometry
  39777. * @param id defines the unique ID of the new geometry
  39778. * @returns a new geometry object
  39779. */
  39780. Geometry.prototype.copy = function (id) {
  39781. var vertexData = new BABYLON.VertexData();
  39782. vertexData.indices = [];
  39783. var indices = this.getIndices();
  39784. if (indices) {
  39785. for (var index = 0; index < indices.length; index++) {
  39786. vertexData.indices.push(indices[index]);
  39787. }
  39788. }
  39789. var updatable = false;
  39790. var stopChecking = false;
  39791. var kind;
  39792. for (kind in this._vertexBuffers) {
  39793. // using slice() to make a copy of the array and not just reference it
  39794. var data = this.getVerticesData(kind);
  39795. if (data instanceof Float32Array) {
  39796. vertexData.set(new Float32Array(data), kind);
  39797. }
  39798. else {
  39799. vertexData.set(data.slice(0), kind);
  39800. }
  39801. if (!stopChecking) {
  39802. var vb = this.getVertexBuffer(kind);
  39803. if (vb) {
  39804. updatable = vb.isUpdatable();
  39805. stopChecking = !updatable;
  39806. }
  39807. }
  39808. }
  39809. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  39810. geometry.delayLoadState = this.delayLoadState;
  39811. geometry.delayLoadingFile = this.delayLoadingFile;
  39812. geometry._delayLoadingFunction = this._delayLoadingFunction;
  39813. for (kind in this._delayInfo) {
  39814. geometry._delayInfo = geometry._delayInfo || [];
  39815. geometry._delayInfo.push(kind);
  39816. }
  39817. // Bounding info
  39818. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39819. return geometry;
  39820. };
  39821. /**
  39822. * Serialize the current geometry info (and not the vertices data) into a JSON object
  39823. * @return a JSON representation of the current geometry data (without the vertices data)
  39824. */
  39825. Geometry.prototype.serialize = function () {
  39826. var serializationObject = {};
  39827. serializationObject.id = this.id;
  39828. serializationObject.updatable = this._updatable;
  39829. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  39830. serializationObject.tags = BABYLON.Tags.GetTags(this);
  39831. }
  39832. return serializationObject;
  39833. };
  39834. Geometry.prototype.toNumberArray = function (origin) {
  39835. if (Array.isArray(origin)) {
  39836. return origin;
  39837. }
  39838. else {
  39839. return Array.prototype.slice.call(origin);
  39840. }
  39841. };
  39842. /**
  39843. * Serialize all vertices data into a JSON oject
  39844. * @returns a JSON representation of the current geometry data
  39845. */
  39846. Geometry.prototype.serializeVerticeData = function () {
  39847. var serializationObject = this.serialize();
  39848. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  39849. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  39850. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  39851. serializationObject.positions._updatable = true;
  39852. }
  39853. }
  39854. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  39855. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  39856. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  39857. serializationObject.normals._updatable = true;
  39858. }
  39859. }
  39860. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  39861. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  39862. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  39863. serializationObject.tangets._updatable = true;
  39864. }
  39865. }
  39866. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39867. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  39868. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  39869. serializationObject.uvs._updatable = true;
  39870. }
  39871. }
  39872. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  39873. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  39874. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  39875. serializationObject.uv2s._updatable = true;
  39876. }
  39877. }
  39878. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  39879. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  39880. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  39881. serializationObject.uv3s._updatable = true;
  39882. }
  39883. }
  39884. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  39885. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  39886. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  39887. serializationObject.uv4s._updatable = true;
  39888. }
  39889. }
  39890. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  39891. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  39892. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  39893. serializationObject.uv5s._updatable = true;
  39894. }
  39895. }
  39896. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  39897. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  39898. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  39899. serializationObject.uv6s._updatable = true;
  39900. }
  39901. }
  39902. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  39903. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  39904. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  39905. serializationObject.colors._updatable = true;
  39906. }
  39907. }
  39908. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39909. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  39910. serializationObject.matricesIndices._isExpanded = true;
  39911. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39912. serializationObject.matricesIndices._updatable = true;
  39913. }
  39914. }
  39915. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39916. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  39917. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39918. serializationObject.matricesWeights._updatable = true;
  39919. }
  39920. }
  39921. serializationObject.indices = this.toNumberArray(this.getIndices());
  39922. return serializationObject;
  39923. };
  39924. // Statics
  39925. /**
  39926. * Extracts a clone of a mesh geometry
  39927. * @param mesh defines the source mesh
  39928. * @param id defines the unique ID of the new geometry object
  39929. * @returns the new geometry object
  39930. */
  39931. Geometry.ExtractFromMesh = function (mesh, id) {
  39932. var geometry = mesh._geometry;
  39933. if (!geometry) {
  39934. return null;
  39935. }
  39936. return geometry.copy(id);
  39937. };
  39938. /**
  39939. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  39940. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  39941. * Be aware Math.random() could cause collisions, but:
  39942. * "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"
  39943. * @returns a string containing a new GUID
  39944. */
  39945. Geometry.RandomId = function () {
  39946. return BABYLON.Tools.RandomId();
  39947. };
  39948. /** @hidden */
  39949. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  39950. var scene = mesh.getScene();
  39951. // Geometry
  39952. var geometryId = parsedGeometry.geometryId;
  39953. if (geometryId) {
  39954. var geometry = scene.getGeometryByID(geometryId);
  39955. if (geometry) {
  39956. geometry.applyToMesh(mesh);
  39957. }
  39958. }
  39959. else if (parsedGeometry instanceof ArrayBuffer) {
  39960. var binaryInfo = mesh._binaryInfo;
  39961. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  39962. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  39963. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  39964. }
  39965. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  39966. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  39967. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  39968. }
  39969. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  39970. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  39971. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  39972. }
  39973. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  39974. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  39975. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  39976. }
  39977. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  39978. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  39979. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  39980. }
  39981. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  39982. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  39983. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  39984. }
  39985. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  39986. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  39987. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  39988. }
  39989. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  39990. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  39991. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  39992. }
  39993. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  39994. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  39995. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  39996. }
  39997. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  39998. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  39999. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  40000. }
  40001. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  40002. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  40003. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  40004. }
  40005. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  40006. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  40007. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  40008. }
  40009. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  40010. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  40011. mesh.setIndices(indicesData, null);
  40012. }
  40013. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  40014. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  40015. mesh.subMeshes = [];
  40016. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  40017. var materialIndex = subMeshesData[(i * 5) + 0];
  40018. var verticesStart = subMeshesData[(i * 5) + 1];
  40019. var verticesCount = subMeshesData[(i * 5) + 2];
  40020. var indexStart = subMeshesData[(i * 5) + 3];
  40021. var indexCount = subMeshesData[(i * 5) + 4];
  40022. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  40023. }
  40024. }
  40025. }
  40026. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  40027. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  40028. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  40029. if (parsedGeometry.tangents) {
  40030. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  40031. }
  40032. if (parsedGeometry.uvs) {
  40033. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  40034. }
  40035. if (parsedGeometry.uvs2) {
  40036. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  40037. }
  40038. if (parsedGeometry.uvs3) {
  40039. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  40040. }
  40041. if (parsedGeometry.uvs4) {
  40042. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  40043. }
  40044. if (parsedGeometry.uvs5) {
  40045. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  40046. }
  40047. if (parsedGeometry.uvs6) {
  40048. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  40049. }
  40050. if (parsedGeometry.colors) {
  40051. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  40052. }
  40053. if (parsedGeometry.matricesIndices) {
  40054. if (!parsedGeometry.matricesIndices._isExpanded) {
  40055. var floatIndices = [];
  40056. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  40057. var matricesIndex = parsedGeometry.matricesIndices[i];
  40058. floatIndices.push(matricesIndex & 0x000000FF);
  40059. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  40060. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  40061. floatIndices.push(matricesIndex >> 24);
  40062. }
  40063. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  40064. }
  40065. else {
  40066. delete parsedGeometry.matricesIndices._isExpanded;
  40067. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  40068. }
  40069. }
  40070. if (parsedGeometry.matricesIndicesExtra) {
  40071. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  40072. var floatIndices = [];
  40073. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  40074. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  40075. floatIndices.push(matricesIndex & 0x000000FF);
  40076. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  40077. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  40078. floatIndices.push(matricesIndex >> 24);
  40079. }
  40080. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  40081. }
  40082. else {
  40083. delete parsedGeometry.matricesIndices._isExpanded;
  40084. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  40085. }
  40086. }
  40087. if (parsedGeometry.matricesWeights) {
  40088. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  40089. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  40090. }
  40091. if (parsedGeometry.matricesWeightsExtra) {
  40092. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  40093. }
  40094. mesh.setIndices(parsedGeometry.indices, null);
  40095. }
  40096. // SubMeshes
  40097. if (parsedGeometry.subMeshes) {
  40098. mesh.subMeshes = [];
  40099. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  40100. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  40101. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  40102. }
  40103. }
  40104. // Flat shading
  40105. if (mesh._shouldGenerateFlatShading) {
  40106. mesh.convertToFlatShadedMesh();
  40107. delete mesh._shouldGenerateFlatShading;
  40108. }
  40109. // Update
  40110. mesh.computeWorldMatrix(true);
  40111. // Octree
  40112. var sceneOctree = scene.selectionOctree;
  40113. if (sceneOctree !== undefined && sceneOctree !== null) {
  40114. sceneOctree.addMesh(mesh);
  40115. }
  40116. };
  40117. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  40118. var epsilon = 1e-3;
  40119. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  40120. return;
  40121. }
  40122. var noInfluenceBoneIndex = 0.0;
  40123. if (parsedGeometry.skeletonId > -1) {
  40124. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  40125. if (!skeleton) {
  40126. return;
  40127. }
  40128. noInfluenceBoneIndex = skeleton.bones.length;
  40129. }
  40130. else {
  40131. return;
  40132. }
  40133. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  40134. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  40135. var matricesWeights = parsedGeometry.matricesWeights;
  40136. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  40137. var influencers = parsedGeometry.numBoneInfluencer;
  40138. var size = matricesWeights.length;
  40139. for (var i = 0; i < size; i += 4) {
  40140. var weight = 0.0;
  40141. var firstZeroWeight = -1;
  40142. for (var j = 0; j < 4; j++) {
  40143. var w = matricesWeights[i + j];
  40144. weight += w;
  40145. if (w < epsilon && firstZeroWeight < 0) {
  40146. firstZeroWeight = j;
  40147. }
  40148. }
  40149. if (matricesWeightsExtra) {
  40150. for (var j = 0; j < 4; j++) {
  40151. var w = matricesWeightsExtra[i + j];
  40152. weight += w;
  40153. if (w < epsilon && firstZeroWeight < 0) {
  40154. firstZeroWeight = j + 4;
  40155. }
  40156. }
  40157. }
  40158. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  40159. firstZeroWeight = influencers - 1;
  40160. }
  40161. if (weight > epsilon) {
  40162. var mweight = 1.0 / weight;
  40163. for (var j = 0; j < 4; j++) {
  40164. matricesWeights[i + j] *= mweight;
  40165. }
  40166. if (matricesWeightsExtra) {
  40167. for (var j = 0; j < 4; j++) {
  40168. matricesWeightsExtra[i + j] *= mweight;
  40169. }
  40170. }
  40171. }
  40172. else {
  40173. if (firstZeroWeight >= 4) {
  40174. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  40175. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  40176. }
  40177. else {
  40178. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  40179. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  40180. }
  40181. }
  40182. }
  40183. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  40184. if (parsedGeometry.matricesWeightsExtra) {
  40185. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  40186. }
  40187. };
  40188. /**
  40189. * Create a new geometry from persisted data (Using .babylon file format)
  40190. * @param parsedVertexData defines the persisted data
  40191. * @param scene defines the hosting scene
  40192. * @param rootUrl defines the root url to use to load assets (like delayed data)
  40193. * @returns the new geometry object
  40194. */
  40195. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  40196. if (scene.getGeometryByID(parsedVertexData.id)) {
  40197. return null; // null since geometry could be something else than a box...
  40198. }
  40199. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  40200. if (BABYLON.Tags) {
  40201. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  40202. }
  40203. if (parsedVertexData.delayLoadingFile) {
  40204. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  40205. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  40206. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  40207. geometry._delayInfo = [];
  40208. if (parsedVertexData.hasUVs) {
  40209. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  40210. }
  40211. if (parsedVertexData.hasUVs2) {
  40212. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  40213. }
  40214. if (parsedVertexData.hasUVs3) {
  40215. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  40216. }
  40217. if (parsedVertexData.hasUVs4) {
  40218. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  40219. }
  40220. if (parsedVertexData.hasUVs5) {
  40221. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  40222. }
  40223. if (parsedVertexData.hasUVs6) {
  40224. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  40225. }
  40226. if (parsedVertexData.hasColors) {
  40227. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  40228. }
  40229. if (parsedVertexData.hasMatricesIndices) {
  40230. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  40231. }
  40232. if (parsedVertexData.hasMatricesWeights) {
  40233. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  40234. }
  40235. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  40236. }
  40237. else {
  40238. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  40239. }
  40240. scene.pushGeometry(geometry, true);
  40241. return geometry;
  40242. };
  40243. return Geometry;
  40244. }());
  40245. BABYLON.Geometry = Geometry;
  40246. // Primitives
  40247. /// Abstract class
  40248. /**
  40249. * Abstract class used to provide common services for all typed geometries
  40250. * @hidden
  40251. */
  40252. var _PrimitiveGeometry = /** @class */ (function (_super) {
  40253. __extends(_PrimitiveGeometry, _super);
  40254. /**
  40255. * Creates a new typed geometry
  40256. * @param id defines the unique ID of the geometry
  40257. * @param scene defines the hosting scene
  40258. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40259. * @param mesh defines the hosting mesh (can be null)
  40260. */
  40261. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  40262. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  40263. if (mesh === void 0) { mesh = null; }
  40264. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  40265. _this._canBeRegenerated = _canBeRegenerated;
  40266. _this._beingRegenerated = true;
  40267. _this.regenerate();
  40268. _this._beingRegenerated = false;
  40269. return _this;
  40270. }
  40271. /**
  40272. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  40273. * @returns true if the geometry can be regenerated
  40274. */
  40275. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  40276. return this._canBeRegenerated;
  40277. };
  40278. /**
  40279. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  40280. */
  40281. _PrimitiveGeometry.prototype.regenerate = function () {
  40282. if (!this._canBeRegenerated) {
  40283. return;
  40284. }
  40285. this._beingRegenerated = true;
  40286. this.setAllVerticesData(this._regenerateVertexData(), false);
  40287. this._beingRegenerated = false;
  40288. };
  40289. /**
  40290. * Clone the geometry
  40291. * @param id defines the unique ID of the new geometry
  40292. * @returns the new geometry
  40293. */
  40294. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  40295. return _super.prototype.copy.call(this, id);
  40296. };
  40297. // overrides
  40298. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  40299. if (!this._beingRegenerated) {
  40300. return;
  40301. }
  40302. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  40303. };
  40304. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  40305. if (!this._beingRegenerated) {
  40306. return;
  40307. }
  40308. _super.prototype.setVerticesData.call(this, kind, data, false);
  40309. };
  40310. // to override
  40311. /** @hidden */
  40312. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  40313. throw new Error("Abstract method");
  40314. };
  40315. _PrimitiveGeometry.prototype.copy = function (id) {
  40316. throw new Error("Must be overriden in sub-classes.");
  40317. };
  40318. _PrimitiveGeometry.prototype.serialize = function () {
  40319. var serializationObject = _super.prototype.serialize.call(this);
  40320. serializationObject.canBeRegenerated = this.canBeRegenerated();
  40321. return serializationObject;
  40322. };
  40323. return _PrimitiveGeometry;
  40324. }(Geometry));
  40325. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  40326. /**
  40327. * Creates a ribbon geometry
  40328. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  40329. */
  40330. var RibbonGeometry = /** @class */ (function (_super) {
  40331. __extends(RibbonGeometry, _super);
  40332. /**
  40333. * Creates a ribbon geometry
  40334. * @param id defines the unique ID of the geometry
  40335. * @param scene defines the hosting scene
  40336. * @param pathArray defines the array of paths to use
  40337. * @param closeArray defines if the last path and the first path must be joined
  40338. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  40339. * @param offset defines the offset between points
  40340. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40341. * @param mesh defines the hosting mesh (can be null)
  40342. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40343. */
  40344. function RibbonGeometry(id, scene,
  40345. /**
  40346. * Defines the array of paths to use
  40347. */
  40348. pathArray,
  40349. /**
  40350. * Defines if the last and first points of each path in your pathArray must be joined
  40351. */
  40352. closeArray,
  40353. /**
  40354. * Defines if the last and first points of each path in your pathArray must be joined
  40355. */
  40356. closePath,
  40357. /**
  40358. * Defines the offset between points
  40359. */
  40360. offset, canBeRegenerated, mesh,
  40361. /**
  40362. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40363. */
  40364. side) {
  40365. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40366. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40367. _this.pathArray = pathArray;
  40368. _this.closeArray = closeArray;
  40369. _this.closePath = closePath;
  40370. _this.offset = offset;
  40371. _this.side = side;
  40372. return _this;
  40373. }
  40374. /** @hidden */
  40375. RibbonGeometry.prototype._regenerateVertexData = function () {
  40376. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  40377. };
  40378. RibbonGeometry.prototype.copy = function (id) {
  40379. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  40380. };
  40381. return RibbonGeometry;
  40382. }(_PrimitiveGeometry));
  40383. BABYLON.RibbonGeometry = RibbonGeometry;
  40384. /**
  40385. * Creates a box geometry
  40386. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  40387. */
  40388. var BoxGeometry = /** @class */ (function (_super) {
  40389. __extends(BoxGeometry, _super);
  40390. /**
  40391. * Creates a box geometry
  40392. * @param id defines the unique ID of the geometry
  40393. * @param scene defines the hosting scene
  40394. * @param size defines the zise of the box (width, height and depth are the same)
  40395. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40396. * @param mesh defines the hosting mesh (can be null)
  40397. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40398. */
  40399. function BoxGeometry(id, scene,
  40400. /**
  40401. * Defines the zise of the box (width, height and depth are the same)
  40402. */
  40403. size, canBeRegenerated, mesh,
  40404. /**
  40405. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40406. */
  40407. side) {
  40408. if (mesh === void 0) { mesh = null; }
  40409. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40410. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40411. _this.size = size;
  40412. _this.side = side;
  40413. return _this;
  40414. }
  40415. BoxGeometry.prototype._regenerateVertexData = function () {
  40416. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  40417. };
  40418. BoxGeometry.prototype.copy = function (id) {
  40419. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  40420. };
  40421. BoxGeometry.prototype.serialize = function () {
  40422. var serializationObject = _super.prototype.serialize.call(this);
  40423. serializationObject.size = this.size;
  40424. return serializationObject;
  40425. };
  40426. BoxGeometry.Parse = function (parsedBox, scene) {
  40427. if (scene.getGeometryByID(parsedBox.id)) {
  40428. return null; // null since geometry could be something else than a box...
  40429. }
  40430. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  40431. if (BABYLON.Tags) {
  40432. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  40433. }
  40434. scene.pushGeometry(box, true);
  40435. return box;
  40436. };
  40437. return BoxGeometry;
  40438. }(_PrimitiveGeometry));
  40439. BABYLON.BoxGeometry = BoxGeometry;
  40440. /**
  40441. * Creates a sphere geometry
  40442. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  40443. */
  40444. var SphereGeometry = /** @class */ (function (_super) {
  40445. __extends(SphereGeometry, _super);
  40446. /**
  40447. * Create a new sphere geometry
  40448. * @param id defines the unique ID of the geometry
  40449. * @param scene defines the hosting scene
  40450. * @param segments defines the number of segments to use to create the sphere
  40451. * @param diameter defines the diameter of the sphere
  40452. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40453. * @param mesh defines the hosting mesh (can be null)
  40454. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40455. */
  40456. function SphereGeometry(id, scene,
  40457. /**
  40458. * Defines the number of segments to use to create the sphere
  40459. */
  40460. segments,
  40461. /**
  40462. * Defines the diameter of the sphere
  40463. */
  40464. diameter, canBeRegenerated, mesh,
  40465. /**
  40466. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40467. */
  40468. side) {
  40469. if (mesh === void 0) { mesh = null; }
  40470. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40471. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40472. _this.segments = segments;
  40473. _this.diameter = diameter;
  40474. _this.side = side;
  40475. return _this;
  40476. }
  40477. SphereGeometry.prototype._regenerateVertexData = function () {
  40478. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  40479. };
  40480. SphereGeometry.prototype.copy = function (id) {
  40481. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  40482. };
  40483. SphereGeometry.prototype.serialize = function () {
  40484. var serializationObject = _super.prototype.serialize.call(this);
  40485. serializationObject.segments = this.segments;
  40486. serializationObject.diameter = this.diameter;
  40487. return serializationObject;
  40488. };
  40489. SphereGeometry.Parse = function (parsedSphere, scene) {
  40490. if (scene.getGeometryByID(parsedSphere.id)) {
  40491. return null; // null since geometry could be something else than a sphere...
  40492. }
  40493. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  40494. if (BABYLON.Tags) {
  40495. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  40496. }
  40497. scene.pushGeometry(sphere, true);
  40498. return sphere;
  40499. };
  40500. return SphereGeometry;
  40501. }(_PrimitiveGeometry));
  40502. BABYLON.SphereGeometry = SphereGeometry;
  40503. /**
  40504. * Creates a disc geometry
  40505. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  40506. */
  40507. var DiscGeometry = /** @class */ (function (_super) {
  40508. __extends(DiscGeometry, _super);
  40509. /**
  40510. * Creates a new disc geometry
  40511. * @param id defines the unique ID of the geometry
  40512. * @param scene defines the hosting scene
  40513. * @param radius defines the radius of the disc
  40514. * @param tessellation defines the tesselation factor to apply to the disc
  40515. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40516. * @param mesh defines the hosting mesh (can be null)
  40517. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40518. */
  40519. function DiscGeometry(id, scene,
  40520. /**
  40521. * Defines the radius of the disc
  40522. */
  40523. radius,
  40524. /**
  40525. * Defines the tesselation factor to apply to the disc
  40526. */
  40527. tessellation, canBeRegenerated, mesh,
  40528. /**
  40529. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40530. */
  40531. side) {
  40532. if (mesh === void 0) { mesh = null; }
  40533. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40534. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40535. _this.radius = radius;
  40536. _this.tessellation = tessellation;
  40537. _this.side = side;
  40538. return _this;
  40539. }
  40540. DiscGeometry.prototype._regenerateVertexData = function () {
  40541. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  40542. };
  40543. DiscGeometry.prototype.copy = function (id) {
  40544. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  40545. };
  40546. return DiscGeometry;
  40547. }(_PrimitiveGeometry));
  40548. BABYLON.DiscGeometry = DiscGeometry;
  40549. /**
  40550. * Creates a new cylinder geometry
  40551. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  40552. */
  40553. var CylinderGeometry = /** @class */ (function (_super) {
  40554. __extends(CylinderGeometry, _super);
  40555. /**
  40556. * Creates a new cylinder geometry
  40557. * @param id defines the unique ID of the geometry
  40558. * @param scene defines the hosting scene
  40559. * @param height defines the height of the cylinder
  40560. * @param diameterTop defines the diameter of the cylinder's top cap
  40561. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  40562. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  40563. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  40564. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40565. * @param mesh defines the hosting mesh (can be null)
  40566. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40567. */
  40568. function CylinderGeometry(id, scene,
  40569. /**
  40570. * Defines the height of the cylinder
  40571. */
  40572. height,
  40573. /**
  40574. * Defines the diameter of the cylinder's top cap
  40575. */
  40576. diameterTop,
  40577. /**
  40578. * Defines the diameter of the cylinder's bottom cap
  40579. */
  40580. diameterBottom,
  40581. /**
  40582. * Defines the tessellation factor to apply to the cylinder
  40583. */
  40584. tessellation,
  40585. /**
  40586. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  40587. */
  40588. subdivisions, canBeRegenerated, mesh,
  40589. /**
  40590. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40591. */
  40592. side) {
  40593. if (subdivisions === void 0) { subdivisions = 1; }
  40594. if (mesh === void 0) { mesh = null; }
  40595. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40596. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40597. _this.height = height;
  40598. _this.diameterTop = diameterTop;
  40599. _this.diameterBottom = diameterBottom;
  40600. _this.tessellation = tessellation;
  40601. _this.subdivisions = subdivisions;
  40602. _this.side = side;
  40603. return _this;
  40604. }
  40605. CylinderGeometry.prototype._regenerateVertexData = function () {
  40606. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  40607. };
  40608. CylinderGeometry.prototype.copy = function (id) {
  40609. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  40610. };
  40611. CylinderGeometry.prototype.serialize = function () {
  40612. var serializationObject = _super.prototype.serialize.call(this);
  40613. serializationObject.height = this.height;
  40614. serializationObject.diameterTop = this.diameterTop;
  40615. serializationObject.diameterBottom = this.diameterBottom;
  40616. serializationObject.tessellation = this.tessellation;
  40617. return serializationObject;
  40618. };
  40619. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  40620. if (scene.getGeometryByID(parsedCylinder.id)) {
  40621. return null; // null since geometry could be something else than a cylinder...
  40622. }
  40623. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  40624. if (BABYLON.Tags) {
  40625. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  40626. }
  40627. scene.pushGeometry(cylinder, true);
  40628. return cylinder;
  40629. };
  40630. return CylinderGeometry;
  40631. }(_PrimitiveGeometry));
  40632. BABYLON.CylinderGeometry = CylinderGeometry;
  40633. /**
  40634. * Creates a new torus geometry
  40635. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  40636. */
  40637. var TorusGeometry = /** @class */ (function (_super) {
  40638. __extends(TorusGeometry, _super);
  40639. /**
  40640. * Creates a new torus geometry
  40641. * @param id defines the unique ID of the geometry
  40642. * @param scene defines the hosting scene
  40643. * @param diameter defines the diameter of the torus
  40644. * @param thickness defines the thickness of the torus (ie. internal diameter)
  40645. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  40646. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40647. * @param mesh defines the hosting mesh (can be null)
  40648. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40649. */
  40650. function TorusGeometry(id, scene,
  40651. /**
  40652. * Defines the diameter of the torus
  40653. */
  40654. diameter,
  40655. /**
  40656. * Defines the thickness of the torus (ie. internal diameter)
  40657. */
  40658. thickness,
  40659. /**
  40660. * Defines the tesselation factor to apply to the torus
  40661. */
  40662. tessellation, canBeRegenerated, mesh,
  40663. /**
  40664. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40665. */
  40666. side) {
  40667. if (mesh === void 0) { mesh = null; }
  40668. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40669. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40670. _this.diameter = diameter;
  40671. _this.thickness = thickness;
  40672. _this.tessellation = tessellation;
  40673. _this.side = side;
  40674. return _this;
  40675. }
  40676. TorusGeometry.prototype._regenerateVertexData = function () {
  40677. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  40678. };
  40679. TorusGeometry.prototype.copy = function (id) {
  40680. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  40681. };
  40682. TorusGeometry.prototype.serialize = function () {
  40683. var serializationObject = _super.prototype.serialize.call(this);
  40684. serializationObject.diameter = this.diameter;
  40685. serializationObject.thickness = this.thickness;
  40686. serializationObject.tessellation = this.tessellation;
  40687. return serializationObject;
  40688. };
  40689. TorusGeometry.Parse = function (parsedTorus, scene) {
  40690. if (scene.getGeometryByID(parsedTorus.id)) {
  40691. return null; // null since geometry could be something else than a torus...
  40692. }
  40693. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  40694. if (BABYLON.Tags) {
  40695. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  40696. }
  40697. scene.pushGeometry(torus, true);
  40698. return torus;
  40699. };
  40700. return TorusGeometry;
  40701. }(_PrimitiveGeometry));
  40702. BABYLON.TorusGeometry = TorusGeometry;
  40703. /**
  40704. * Creates a new ground geometry
  40705. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  40706. */
  40707. var GroundGeometry = /** @class */ (function (_super) {
  40708. __extends(GroundGeometry, _super);
  40709. /**
  40710. * Creates a new ground geometry
  40711. * @param id defines the unique ID of the geometry
  40712. * @param scene defines the hosting scene
  40713. * @param width defines the width of the ground
  40714. * @param height defines the height of the ground
  40715. * @param subdivisions defines the subdivisions to apply to the ground
  40716. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40717. * @param mesh defines the hosting mesh (can be null)
  40718. */
  40719. function GroundGeometry(id, scene,
  40720. /**
  40721. * Defines the width of the ground
  40722. */
  40723. width,
  40724. /**
  40725. * Defines the height of the ground
  40726. */
  40727. height,
  40728. /**
  40729. * Defines the subdivisions to apply to the ground
  40730. */
  40731. subdivisions, canBeRegenerated, mesh) {
  40732. if (mesh === void 0) { mesh = null; }
  40733. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40734. _this.width = width;
  40735. _this.height = height;
  40736. _this.subdivisions = subdivisions;
  40737. return _this;
  40738. }
  40739. GroundGeometry.prototype._regenerateVertexData = function () {
  40740. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  40741. };
  40742. GroundGeometry.prototype.copy = function (id) {
  40743. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  40744. };
  40745. GroundGeometry.prototype.serialize = function () {
  40746. var serializationObject = _super.prototype.serialize.call(this);
  40747. serializationObject.width = this.width;
  40748. serializationObject.height = this.height;
  40749. serializationObject.subdivisions = this.subdivisions;
  40750. return serializationObject;
  40751. };
  40752. GroundGeometry.Parse = function (parsedGround, scene) {
  40753. if (scene.getGeometryByID(parsedGround.id)) {
  40754. return null; // null since geometry could be something else than a ground...
  40755. }
  40756. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  40757. if (BABYLON.Tags) {
  40758. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  40759. }
  40760. scene.pushGeometry(ground, true);
  40761. return ground;
  40762. };
  40763. return GroundGeometry;
  40764. }(_PrimitiveGeometry));
  40765. BABYLON.GroundGeometry = GroundGeometry;
  40766. /**
  40767. * Creates a tiled ground geometry
  40768. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  40769. */
  40770. var TiledGroundGeometry = /** @class */ (function (_super) {
  40771. __extends(TiledGroundGeometry, _super);
  40772. /**
  40773. * Creates a tiled ground geometry
  40774. * @param id defines the unique ID of the geometry
  40775. * @param scene defines the hosting scene
  40776. * @param xmin defines the minimum value on X axis
  40777. * @param zmin defines the minimum value on Z axis
  40778. * @param xmax defines the maximum value on X axis
  40779. * @param zmax defines the maximum value on Z axis
  40780. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  40781. * @param precision defines the precision to use when computing the tiles
  40782. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40783. * @param mesh defines the hosting mesh (can be null)
  40784. */
  40785. function TiledGroundGeometry(id, scene,
  40786. /**
  40787. * Defines the minimum value on X axis
  40788. */
  40789. xmin,
  40790. /**
  40791. * Defines the minimum value on Z axis
  40792. */
  40793. zmin,
  40794. /**
  40795. * Defines the maximum value on X axis
  40796. */
  40797. xmax,
  40798. /**
  40799. * Defines the maximum value on Z axis
  40800. */
  40801. zmax,
  40802. /**
  40803. * Defines the subdivisions to apply to the ground
  40804. */
  40805. subdivisions,
  40806. /**
  40807. * Defines the precision to use when computing the tiles
  40808. */
  40809. precision, canBeRegenerated, mesh) {
  40810. if (mesh === void 0) { mesh = null; }
  40811. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40812. _this.xmin = xmin;
  40813. _this.zmin = zmin;
  40814. _this.xmax = xmax;
  40815. _this.zmax = zmax;
  40816. _this.subdivisions = subdivisions;
  40817. _this.precision = precision;
  40818. return _this;
  40819. }
  40820. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  40821. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  40822. };
  40823. TiledGroundGeometry.prototype.copy = function (id) {
  40824. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  40825. };
  40826. return TiledGroundGeometry;
  40827. }(_PrimitiveGeometry));
  40828. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  40829. /**
  40830. * Creates a plane geometry
  40831. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  40832. */
  40833. var PlaneGeometry = /** @class */ (function (_super) {
  40834. __extends(PlaneGeometry, _super);
  40835. /**
  40836. * Creates a plane geometry
  40837. * @param id defines the unique ID of the geometry
  40838. * @param scene defines the hosting scene
  40839. * @param size defines the size of the plane (width === height)
  40840. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40841. * @param mesh defines the hosting mesh (can be null)
  40842. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40843. */
  40844. function PlaneGeometry(id, scene,
  40845. /**
  40846. * Defines the size of the plane (width === height)
  40847. */
  40848. size, canBeRegenerated, mesh,
  40849. /**
  40850. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40851. */
  40852. side) {
  40853. if (mesh === void 0) { mesh = null; }
  40854. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40855. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40856. _this.size = size;
  40857. _this.side = side;
  40858. return _this;
  40859. }
  40860. PlaneGeometry.prototype._regenerateVertexData = function () {
  40861. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  40862. };
  40863. PlaneGeometry.prototype.copy = function (id) {
  40864. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  40865. };
  40866. PlaneGeometry.prototype.serialize = function () {
  40867. var serializationObject = _super.prototype.serialize.call(this);
  40868. serializationObject.size = this.size;
  40869. return serializationObject;
  40870. };
  40871. PlaneGeometry.Parse = function (parsedPlane, scene) {
  40872. if (scene.getGeometryByID(parsedPlane.id)) {
  40873. return null; // null since geometry could be something else than a ground...
  40874. }
  40875. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  40876. if (BABYLON.Tags) {
  40877. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  40878. }
  40879. scene.pushGeometry(plane, true);
  40880. return plane;
  40881. };
  40882. return PlaneGeometry;
  40883. }(_PrimitiveGeometry));
  40884. BABYLON.PlaneGeometry = PlaneGeometry;
  40885. /**
  40886. * Creates a torus knot geometry
  40887. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  40888. */
  40889. var TorusKnotGeometry = /** @class */ (function (_super) {
  40890. __extends(TorusKnotGeometry, _super);
  40891. /**
  40892. * Creates a torus knot geometry
  40893. * @param id defines the unique ID of the geometry
  40894. * @param scene defines the hosting scene
  40895. * @param radius defines the radius of the torus knot
  40896. * @param tube defines the thickness of the torus knot tube
  40897. * @param radialSegments defines the number of radial segments
  40898. * @param tubularSegments defines the number of tubular segments
  40899. * @param p defines the first number of windings
  40900. * @param q defines the second number of windings
  40901. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40902. * @param mesh defines the hosting mesh (can be null)
  40903. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40904. */
  40905. function TorusKnotGeometry(id, scene,
  40906. /**
  40907. * Defines the radius of the torus knot
  40908. */
  40909. radius,
  40910. /**
  40911. * Defines the thickness of the torus knot tube
  40912. */
  40913. tube,
  40914. /**
  40915. * Defines the number of radial segments
  40916. */
  40917. radialSegments,
  40918. /**
  40919. * Defines the number of tubular segments
  40920. */
  40921. tubularSegments,
  40922. /**
  40923. * Defines the first number of windings
  40924. */
  40925. p,
  40926. /**
  40927. * Defines the second number of windings
  40928. */
  40929. q, canBeRegenerated, mesh,
  40930. /**
  40931. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40932. */
  40933. side) {
  40934. if (mesh === void 0) { mesh = null; }
  40935. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40936. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40937. _this.radius = radius;
  40938. _this.tube = tube;
  40939. _this.radialSegments = radialSegments;
  40940. _this.tubularSegments = tubularSegments;
  40941. _this.p = p;
  40942. _this.q = q;
  40943. _this.side = side;
  40944. return _this;
  40945. }
  40946. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  40947. 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 });
  40948. };
  40949. TorusKnotGeometry.prototype.copy = function (id) {
  40950. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  40951. };
  40952. TorusKnotGeometry.prototype.serialize = function () {
  40953. var serializationObject = _super.prototype.serialize.call(this);
  40954. serializationObject.radius = this.radius;
  40955. serializationObject.tube = this.tube;
  40956. serializationObject.radialSegments = this.radialSegments;
  40957. serializationObject.tubularSegments = this.tubularSegments;
  40958. serializationObject.p = this.p;
  40959. serializationObject.q = this.q;
  40960. return serializationObject;
  40961. };
  40962. ;
  40963. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  40964. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  40965. return null; // null since geometry could be something else than a ground...
  40966. }
  40967. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  40968. if (BABYLON.Tags) {
  40969. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  40970. }
  40971. scene.pushGeometry(torusKnot, true);
  40972. return torusKnot;
  40973. };
  40974. return TorusKnotGeometry;
  40975. }(_PrimitiveGeometry));
  40976. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  40977. //}
  40978. })(BABYLON || (BABYLON = {}));
  40979. //# sourceMappingURL=babylon.geometry.js.map
  40980. var BABYLON;
  40981. (function (BABYLON) {
  40982. /**
  40983. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  40984. */
  40985. var PerformanceMonitor = /** @class */ (function () {
  40986. /**
  40987. * constructor
  40988. * @param frameSampleSize The number of samples required to saturate the sliding window
  40989. */
  40990. function PerformanceMonitor(frameSampleSize) {
  40991. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  40992. this._enabled = true;
  40993. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  40994. }
  40995. /**
  40996. * Samples current frame
  40997. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  40998. */
  40999. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  41000. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  41001. if (!this._enabled)
  41002. return;
  41003. if (this._lastFrameTimeMs != null) {
  41004. var dt = timeMs - this._lastFrameTimeMs;
  41005. this._rollingFrameTime.add(dt);
  41006. }
  41007. this._lastFrameTimeMs = timeMs;
  41008. };
  41009. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  41010. /**
  41011. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  41012. * @return Average frame time in milliseconds
  41013. */
  41014. get: function () {
  41015. return this._rollingFrameTime.average;
  41016. },
  41017. enumerable: true,
  41018. configurable: true
  41019. });
  41020. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  41021. /**
  41022. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  41023. * @return Frame time variance in milliseconds squared
  41024. */
  41025. get: function () {
  41026. return this._rollingFrameTime.variance;
  41027. },
  41028. enumerable: true,
  41029. configurable: true
  41030. });
  41031. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  41032. /**
  41033. * Returns the frame time of the most recent frame
  41034. * @return Frame time in milliseconds
  41035. */
  41036. get: function () {
  41037. return this._rollingFrameTime.history(0);
  41038. },
  41039. enumerable: true,
  41040. configurable: true
  41041. });
  41042. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  41043. /**
  41044. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  41045. * @return Framerate in frames per second
  41046. */
  41047. get: function () {
  41048. return 1000.0 / this._rollingFrameTime.average;
  41049. },
  41050. enumerable: true,
  41051. configurable: true
  41052. });
  41053. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  41054. /**
  41055. * Returns the average framerate in frames per second using the most recent frame time
  41056. * @return Framerate in frames per second
  41057. */
  41058. get: function () {
  41059. var history = this._rollingFrameTime.history(0);
  41060. if (history === 0) {
  41061. return 0;
  41062. }
  41063. return 1000.0 / history;
  41064. },
  41065. enumerable: true,
  41066. configurable: true
  41067. });
  41068. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  41069. /**
  41070. * Returns true if enough samples have been taken to completely fill the sliding window
  41071. * @return true if saturated
  41072. */
  41073. get: function () {
  41074. return this._rollingFrameTime.isSaturated();
  41075. },
  41076. enumerable: true,
  41077. configurable: true
  41078. });
  41079. /**
  41080. * Enables contributions to the sliding window sample set
  41081. */
  41082. PerformanceMonitor.prototype.enable = function () {
  41083. this._enabled = true;
  41084. };
  41085. /**
  41086. * Disables contributions to the sliding window sample set
  41087. * Samples will not be interpolated over the disabled period
  41088. */
  41089. PerformanceMonitor.prototype.disable = function () {
  41090. this._enabled = false;
  41091. //clear last sample to avoid interpolating over the disabled period when next enabled
  41092. this._lastFrameTimeMs = null;
  41093. };
  41094. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  41095. /**
  41096. * Returns true if sampling is enabled
  41097. * @return true if enabled
  41098. */
  41099. get: function () {
  41100. return this._enabled;
  41101. },
  41102. enumerable: true,
  41103. configurable: true
  41104. });
  41105. /**
  41106. * Resets performance monitor
  41107. */
  41108. PerformanceMonitor.prototype.reset = function () {
  41109. //clear last sample to avoid interpolating over the disabled period when next enabled
  41110. this._lastFrameTimeMs = null;
  41111. //wipe record
  41112. this._rollingFrameTime.reset();
  41113. };
  41114. return PerformanceMonitor;
  41115. }());
  41116. BABYLON.PerformanceMonitor = PerformanceMonitor;
  41117. /**
  41118. * RollingAverage
  41119. *
  41120. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  41121. */
  41122. var RollingAverage = /** @class */ (function () {
  41123. /**
  41124. * constructor
  41125. * @param length The number of samples required to saturate the sliding window
  41126. */
  41127. function RollingAverage(length) {
  41128. this._samples = new Array(length);
  41129. this.reset();
  41130. }
  41131. /**
  41132. * Adds a sample to the sample set
  41133. * @param v The sample value
  41134. */
  41135. RollingAverage.prototype.add = function (v) {
  41136. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  41137. var delta;
  41138. //we need to check if we've already wrapped round
  41139. if (this.isSaturated()) {
  41140. //remove bottom of stack from mean
  41141. var bottomValue = this._samples[this._pos];
  41142. delta = bottomValue - this.average;
  41143. this.average -= delta / (this._sampleCount - 1);
  41144. this._m2 -= delta * (bottomValue - this.average);
  41145. }
  41146. else {
  41147. this._sampleCount++;
  41148. }
  41149. //add new value to mean
  41150. delta = v - this.average;
  41151. this.average += delta / (this._sampleCount);
  41152. this._m2 += delta * (v - this.average);
  41153. //set the new variance
  41154. this.variance = this._m2 / (this._sampleCount - 1);
  41155. this._samples[this._pos] = v;
  41156. this._pos++;
  41157. this._pos %= this._samples.length; //positive wrap around
  41158. };
  41159. /**
  41160. * Returns previously added values or null if outside of history or outside the sliding window domain
  41161. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  41162. * @return Value previously recorded with add() or null if outside of range
  41163. */
  41164. RollingAverage.prototype.history = function (i) {
  41165. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  41166. return 0;
  41167. }
  41168. var i0 = this._wrapPosition(this._pos - 1.0);
  41169. return this._samples[this._wrapPosition(i0 - i)];
  41170. };
  41171. /**
  41172. * Returns true if enough samples have been taken to completely fill the sliding window
  41173. * @return true if sample-set saturated
  41174. */
  41175. RollingAverage.prototype.isSaturated = function () {
  41176. return this._sampleCount >= this._samples.length;
  41177. };
  41178. /**
  41179. * Resets the rolling average (equivalent to 0 samples taken so far)
  41180. */
  41181. RollingAverage.prototype.reset = function () {
  41182. this.average = 0;
  41183. this.variance = 0;
  41184. this._sampleCount = 0;
  41185. this._pos = 0;
  41186. this._m2 = 0;
  41187. };
  41188. /**
  41189. * Wraps a value around the sample range boundaries
  41190. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  41191. * @return Wrapped position in sample range
  41192. */
  41193. RollingAverage.prototype._wrapPosition = function (i) {
  41194. var max = this._samples.length;
  41195. return ((i % max) + max) % max;
  41196. };
  41197. return RollingAverage;
  41198. }());
  41199. BABYLON.RollingAverage = RollingAverage;
  41200. })(BABYLON || (BABYLON = {}));
  41201. //# sourceMappingURL=babylon.performanceMonitor.js.map
  41202. var BABYLON;
  41203. (function (BABYLON) {
  41204. /**
  41205. * "Static Class" containing the most commonly used helper while dealing with material for
  41206. * rendering purpose.
  41207. *
  41208. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  41209. *
  41210. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  41211. */
  41212. var MaterialHelper = /** @class */ (function () {
  41213. function MaterialHelper() {
  41214. }
  41215. /**
  41216. * Bind the current view position to an effect.
  41217. * @param effect The effect to be bound
  41218. * @param scene The scene the eyes position is used from
  41219. */
  41220. MaterialHelper.BindEyePosition = function (effect, scene) {
  41221. if (scene._forcedViewPosition) {
  41222. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  41223. return;
  41224. }
  41225. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  41226. };
  41227. /**
  41228. * Helps preparing the defines values about the UVs in used in the effect.
  41229. * UVs are shared as much as we can accross chanels in the shaders.
  41230. * @param texture The texture we are preparing the UVs for
  41231. * @param defines The defines to update
  41232. * @param key The chanel key "diffuse", "specular"... used in the shader
  41233. */
  41234. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  41235. defines._needUVs = true;
  41236. defines[key] = true;
  41237. if (texture.getTextureMatrix().isIdentity(true)) {
  41238. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  41239. if (texture.coordinatesIndex === 0) {
  41240. defines["MAINUV1"] = true;
  41241. }
  41242. else {
  41243. defines["MAINUV2"] = true;
  41244. }
  41245. }
  41246. else {
  41247. defines[key + "DIRECTUV"] = 0;
  41248. }
  41249. };
  41250. /**
  41251. * Binds a texture matrix value to its corrsponding uniform
  41252. * @param texture The texture to bind the matrix for
  41253. * @param uniformBuffer The uniform buffer receivin the data
  41254. * @param key The chanel key "diffuse", "specular"... used in the shader
  41255. */
  41256. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  41257. var matrix = texture.getTextureMatrix();
  41258. if (!matrix.isIdentity(true)) {
  41259. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  41260. }
  41261. };
  41262. /**
  41263. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  41264. * @param mesh defines the current mesh
  41265. * @param scene defines the current scene
  41266. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  41267. * @param pointsCloud defines if point cloud rendering has to be turned on
  41268. * @param fogEnabled defines if fog has to be turned on
  41269. * @param alphaTest defines if alpha testing has to be turned on
  41270. * @param defines defines the current list of defines
  41271. */
  41272. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  41273. if (defines._areMiscDirty) {
  41274. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  41275. defines["POINTSIZE"] = pointsCloud;
  41276. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  41277. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  41278. defines["ALPHATEST"] = alphaTest;
  41279. }
  41280. };
  41281. /**
  41282. * Helper used to prepare the list of defines associated with frame values for shader compilation
  41283. * @param scene defines the current scene
  41284. * @param engine defines the current engine
  41285. * @param defines specifies the list of active defines
  41286. * @param useInstances defines if instances have to be turned on
  41287. * @param useClipPlane defines if clip plane have to be turned on
  41288. */
  41289. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  41290. if (useClipPlane === void 0) { useClipPlane = null; }
  41291. var changed = false;
  41292. if (useClipPlane == null) {
  41293. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  41294. }
  41295. if (defines["CLIPPLANE"] !== useClipPlane) {
  41296. defines["CLIPPLANE"] = useClipPlane;
  41297. changed = true;
  41298. }
  41299. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  41300. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  41301. changed = true;
  41302. }
  41303. if (defines["INSTANCES"] !== useInstances) {
  41304. defines["INSTANCES"] = useInstances;
  41305. changed = true;
  41306. }
  41307. if (changed) {
  41308. defines.markAsUnprocessed();
  41309. }
  41310. };
  41311. /**
  41312. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  41313. * @param mesh The mesh containing the geometry data we will draw
  41314. * @param defines The defines to update
  41315. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  41316. * @param useBones Precise whether bones should be used or not (override mesh info)
  41317. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  41318. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  41319. * @returns false if defines are considered not dirty and have not been checked
  41320. */
  41321. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  41322. if (useMorphTargets === void 0) { useMorphTargets = false; }
  41323. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  41324. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  41325. return false;
  41326. }
  41327. defines._normals = defines._needNormals;
  41328. defines._uvs = defines._needUVs;
  41329. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  41330. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  41331. defines["TANGENT"] = true;
  41332. }
  41333. if (defines._needUVs) {
  41334. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  41335. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  41336. }
  41337. else {
  41338. defines["UV1"] = false;
  41339. defines["UV2"] = false;
  41340. }
  41341. if (useVertexColor) {
  41342. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  41343. defines["VERTEXCOLOR"] = hasVertexColors;
  41344. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  41345. }
  41346. if (useBones) {
  41347. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41348. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  41349. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  41350. }
  41351. else {
  41352. defines["NUM_BONE_INFLUENCERS"] = 0;
  41353. defines["BonesPerMesh"] = 0;
  41354. }
  41355. }
  41356. if (useMorphTargets) {
  41357. var manager = mesh.morphTargetManager;
  41358. if (manager) {
  41359. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  41360. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  41361. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  41362. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  41363. }
  41364. else {
  41365. defines["MORPHTARGETS_TANGENT"] = false;
  41366. defines["MORPHTARGETS_NORMAL"] = false;
  41367. defines["MORPHTARGETS"] = false;
  41368. defines["NUM_MORPH_INFLUENCERS"] = 0;
  41369. }
  41370. }
  41371. return true;
  41372. };
  41373. /**
  41374. * Prepares the defines related to the light information passed in parameter
  41375. * @param scene The scene we are intending to draw
  41376. * @param mesh The mesh the effect is compiling for
  41377. * @param defines The defines to update
  41378. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  41379. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  41380. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  41381. * @returns true if normals will be required for the rest of the effect
  41382. */
  41383. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  41384. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41385. if (disableLighting === void 0) { disableLighting = false; }
  41386. if (!defines._areLightsDirty) {
  41387. return defines._needNormals;
  41388. }
  41389. var lightIndex = 0;
  41390. var needNormals = false;
  41391. var needRebuild = false;
  41392. var lightmapMode = false;
  41393. var shadowEnabled = false;
  41394. var specularEnabled = false;
  41395. if (scene.lightsEnabled && !disableLighting) {
  41396. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  41397. var light = _a[_i];
  41398. needNormals = true;
  41399. if (defines["LIGHT" + lightIndex] === undefined) {
  41400. needRebuild = true;
  41401. }
  41402. defines["LIGHT" + lightIndex] = true;
  41403. defines["SPOTLIGHT" + lightIndex] = false;
  41404. defines["HEMILIGHT" + lightIndex] = false;
  41405. defines["POINTLIGHT" + lightIndex] = false;
  41406. defines["DIRLIGHT" + lightIndex] = false;
  41407. var type;
  41408. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  41409. type = "SPOTLIGHT" + lightIndex;
  41410. var spotLight = light;
  41411. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? true : false;
  41412. }
  41413. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  41414. type = "HEMILIGHT" + lightIndex;
  41415. }
  41416. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  41417. type = "POINTLIGHT" + lightIndex;
  41418. }
  41419. else {
  41420. type = "DIRLIGHT" + lightIndex;
  41421. }
  41422. defines[type] = true;
  41423. // Specular
  41424. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  41425. specularEnabled = true;
  41426. }
  41427. // Shadows
  41428. defines["SHADOW" + lightIndex] = false;
  41429. defines["SHADOWPCF" + lightIndex] = false;
  41430. defines["SHADOWPCSS" + lightIndex] = false;
  41431. defines["SHADOWPOISSON" + lightIndex] = false;
  41432. defines["SHADOWESM" + lightIndex] = false;
  41433. defines["SHADOWCUBE" + lightIndex] = false;
  41434. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  41435. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  41436. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  41437. var shadowGenerator = light.getShadowGenerator();
  41438. if (shadowGenerator) {
  41439. shadowEnabled = true;
  41440. shadowGenerator.prepareDefines(defines, lightIndex);
  41441. }
  41442. }
  41443. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  41444. lightmapMode = true;
  41445. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  41446. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  41447. }
  41448. else {
  41449. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  41450. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  41451. }
  41452. lightIndex++;
  41453. if (lightIndex === maxSimultaneousLights)
  41454. break;
  41455. }
  41456. }
  41457. defines["SPECULARTERM"] = specularEnabled;
  41458. defines["SHADOWS"] = shadowEnabled;
  41459. // Resetting all other lights if any
  41460. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  41461. if (defines["LIGHT" + index] !== undefined) {
  41462. defines["LIGHT" + index] = false;
  41463. defines["HEMILIGHT" + lightIndex] = false;
  41464. defines["POINTLIGHT" + lightIndex] = false;
  41465. defines["DIRLIGHT" + lightIndex] = false;
  41466. defines["SPOTLIGHT" + lightIndex] = false;
  41467. defines["SHADOW" + lightIndex] = false;
  41468. }
  41469. }
  41470. var caps = scene.getEngine().getCaps();
  41471. if (defines["SHADOWFLOAT"] === undefined) {
  41472. needRebuild = true;
  41473. }
  41474. defines["SHADOWFLOAT"] = shadowEnabled &&
  41475. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  41476. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  41477. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  41478. if (needRebuild) {
  41479. defines.rebuild();
  41480. }
  41481. return needNormals;
  41482. };
  41483. /**
  41484. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  41485. * that won t be acctive due to defines being turned off.
  41486. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  41487. * @param samplersList The samplers list
  41488. * @param defines The defines helping in the list generation
  41489. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  41490. */
  41491. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  41492. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41493. var uniformsList;
  41494. var uniformBuffersList = null;
  41495. if (uniformsListOrOptions.uniformsNames) {
  41496. var options = uniformsListOrOptions;
  41497. uniformsList = options.uniformsNames;
  41498. uniformBuffersList = options.uniformBuffersNames;
  41499. samplersList = options.samplers;
  41500. defines = options.defines;
  41501. maxSimultaneousLights = options.maxSimultaneousLights;
  41502. }
  41503. else {
  41504. uniformsList = uniformsListOrOptions;
  41505. if (!samplersList) {
  41506. samplersList = [];
  41507. }
  41508. }
  41509. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  41510. if (!defines["LIGHT" + lightIndex]) {
  41511. break;
  41512. }
  41513. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  41514. if (uniformBuffersList) {
  41515. uniformBuffersList.push("Light" + lightIndex);
  41516. }
  41517. samplersList.push("shadowSampler" + lightIndex);
  41518. samplersList.push("depthSampler" + lightIndex);
  41519. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  41520. samplersList.push("projectionLightSampler" + lightIndex);
  41521. uniformsList.push("textureProjectionMatrix" + lightIndex);
  41522. }
  41523. }
  41524. if (defines["NUM_MORPH_INFLUENCERS"]) {
  41525. uniformsList.push("morphTargetInfluences");
  41526. }
  41527. };
  41528. /**
  41529. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  41530. * @param defines The defines to update while falling back
  41531. * @param fallbacks The authorized effect fallbacks
  41532. * @param maxSimultaneousLights The maximum number of lights allowed
  41533. * @param rank the current rank of the Effect
  41534. * @returns The newly affected rank
  41535. */
  41536. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  41537. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41538. if (rank === void 0) { rank = 0; }
  41539. var lightFallbackRank = 0;
  41540. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  41541. if (!defines["LIGHT" + lightIndex]) {
  41542. break;
  41543. }
  41544. if (lightIndex > 0) {
  41545. lightFallbackRank = rank + lightIndex;
  41546. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  41547. }
  41548. if (!defines["SHADOWS"]) {
  41549. if (defines["SHADOW" + lightIndex]) {
  41550. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  41551. }
  41552. if (defines["SHADOWPCF" + lightIndex]) {
  41553. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  41554. }
  41555. if (defines["SHADOWPCSS" + lightIndex]) {
  41556. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  41557. }
  41558. if (defines["SHADOWPOISSON" + lightIndex]) {
  41559. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  41560. }
  41561. if (defines["SHADOWESM" + lightIndex]) {
  41562. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  41563. }
  41564. }
  41565. }
  41566. return lightFallbackRank++;
  41567. };
  41568. /**
  41569. * Prepares the list of attributes required for morph targets according to the effect defines.
  41570. * @param attribs The current list of supported attribs
  41571. * @param mesh The mesh to prepare the morph targets attributes for
  41572. * @param defines The current Defines of the effect
  41573. */
  41574. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  41575. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  41576. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  41577. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  41578. var manager = mesh.morphTargetManager;
  41579. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  41580. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  41581. for (var index = 0; index < influencers; index++) {
  41582. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  41583. if (normal) {
  41584. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  41585. }
  41586. if (tangent) {
  41587. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  41588. }
  41589. if (attribs.length > maxAttributesCount) {
  41590. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  41591. }
  41592. }
  41593. }
  41594. };
  41595. /**
  41596. * Prepares the list of attributes required for bones according to the effect defines.
  41597. * @param attribs The current list of supported attribs
  41598. * @param mesh The mesh to prepare the bones attributes for
  41599. * @param defines The current Defines of the effect
  41600. * @param fallbacks The current efffect fallback strategy
  41601. */
  41602. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  41603. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  41604. fallbacks.addCPUSkinningFallback(0, mesh);
  41605. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  41606. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  41607. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  41608. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  41609. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  41610. }
  41611. }
  41612. };
  41613. /**
  41614. * Prepares the list of attributes required for instances according to the effect defines.
  41615. * @param attribs The current list of supported attribs
  41616. * @param defines The current Defines of the effect
  41617. */
  41618. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  41619. if (defines["INSTANCES"]) {
  41620. attribs.push("world0");
  41621. attribs.push("world1");
  41622. attribs.push("world2");
  41623. attribs.push("world3");
  41624. }
  41625. };
  41626. /**
  41627. * Binds the light shadow information to the effect for the given mesh.
  41628. * @param light The light containing the generator
  41629. * @param scene The scene the lights belongs to
  41630. * @param mesh The mesh we are binding the information to render
  41631. * @param lightIndex The light index in the effect used to render the mesh
  41632. * @param effect The effect we are binding the data to
  41633. */
  41634. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  41635. if (light.shadowEnabled && mesh.receiveShadows) {
  41636. var shadowGenerator = light.getShadowGenerator();
  41637. if (shadowGenerator) {
  41638. shadowGenerator.bindShadowLight(lightIndex, effect);
  41639. }
  41640. }
  41641. };
  41642. /**
  41643. * Binds the light information to the effect.
  41644. * @param light The light containing the generator
  41645. * @param effect The effect we are binding the data to
  41646. * @param lightIndex The light index in the effect used to render
  41647. */
  41648. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  41649. light.transferToEffect(effect, lightIndex + "");
  41650. };
  41651. /**
  41652. * Binds the lights information from the scene to the effect for the given mesh.
  41653. * @param scene The scene the lights belongs to
  41654. * @param mesh The mesh we are binding the information to render
  41655. * @param effect The effect we are binding the data to
  41656. * @param defines The generated defines for the effect
  41657. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  41658. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  41659. */
  41660. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  41661. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41662. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  41663. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  41664. for (var i = 0; i < len; i++) {
  41665. var light = mesh._lightSources[i];
  41666. var iAsString = i.toString();
  41667. var scaledIntensity = light.getScaledIntensity();
  41668. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  41669. MaterialHelper.BindLightProperties(light, effect, i);
  41670. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  41671. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  41672. if (defines["SPECULARTERM"]) {
  41673. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  41674. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  41675. }
  41676. // Shadows
  41677. if (scene.shadowsEnabled) {
  41678. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  41679. }
  41680. light._uniformBuffer.update();
  41681. }
  41682. };
  41683. /**
  41684. * Binds the fog information from the scene to the effect for the given mesh.
  41685. * @param scene The scene the lights belongs to
  41686. * @param mesh The mesh we are binding the information to render
  41687. * @param effect The effect we are binding the data to
  41688. */
  41689. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  41690. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  41691. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  41692. effect.setColor3("vFogColor", scene.fogColor);
  41693. }
  41694. };
  41695. /**
  41696. * Binds the bones information from the mesh to the effect.
  41697. * @param mesh The mesh we are binding the information to render
  41698. * @param effect The effect we are binding the data to
  41699. */
  41700. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  41701. if (!effect || !mesh) {
  41702. return;
  41703. }
  41704. if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) {
  41705. mesh.computeBonesUsingShaders = false;
  41706. }
  41707. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41708. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  41709. if (matrices) {
  41710. effect.setMatrices("mBones", matrices);
  41711. }
  41712. }
  41713. };
  41714. /**
  41715. * Binds the morph targets information from the mesh to the effect.
  41716. * @param abstractMesh The mesh we are binding the information to render
  41717. * @param effect The effect we are binding the data to
  41718. */
  41719. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  41720. var manager = abstractMesh.morphTargetManager;
  41721. if (!abstractMesh || !manager) {
  41722. return;
  41723. }
  41724. effect.setFloatArray("morphTargetInfluences", manager.influences);
  41725. };
  41726. /**
  41727. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  41728. * @param defines The generated defines used in the effect
  41729. * @param effect The effect we are binding the data to
  41730. * @param scene The scene we are willing to render with logarithmic scale for
  41731. */
  41732. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  41733. if (defines["LOGARITHMICDEPTH"]) {
  41734. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  41735. }
  41736. };
  41737. /**
  41738. * Binds the clip plane information from the scene to the effect.
  41739. * @param scene The scene the clip plane information are extracted from
  41740. * @param effect The effect we are binding the data to
  41741. */
  41742. MaterialHelper.BindClipPlane = function (effect, scene) {
  41743. if (scene.clipPlane) {
  41744. var clipPlane = scene.clipPlane;
  41745. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41746. }
  41747. };
  41748. return MaterialHelper;
  41749. }());
  41750. BABYLON.MaterialHelper = MaterialHelper;
  41751. })(BABYLON || (BABYLON = {}));
  41752. //# sourceMappingURL=babylon.materialHelper.js.map
  41753. var BABYLON;
  41754. (function (BABYLON) {
  41755. var PushMaterial = /** @class */ (function (_super) {
  41756. __extends(PushMaterial, _super);
  41757. function PushMaterial(name, scene) {
  41758. var _this = _super.call(this, name, scene) || this;
  41759. _this._normalMatrix = new BABYLON.Matrix();
  41760. _this.storeEffectOnSubMeshes = true;
  41761. return _this;
  41762. }
  41763. PushMaterial.prototype.getEffect = function () {
  41764. return this._activeEffect;
  41765. };
  41766. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  41767. if (!mesh) {
  41768. return false;
  41769. }
  41770. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  41771. return true;
  41772. }
  41773. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  41774. };
  41775. /**
  41776. * Binds the given world matrix to the active effect
  41777. *
  41778. * @param world the matrix to bind
  41779. */
  41780. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  41781. this._activeEffect.setMatrix("world", world);
  41782. };
  41783. /**
  41784. * Binds the given normal matrix to the active effect
  41785. *
  41786. * @param normalMatrix the matrix to bind
  41787. */
  41788. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  41789. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  41790. };
  41791. PushMaterial.prototype.bind = function (world, mesh) {
  41792. if (!mesh) {
  41793. return;
  41794. }
  41795. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  41796. };
  41797. PushMaterial.prototype._afterBind = function (mesh, effect) {
  41798. if (effect === void 0) { effect = null; }
  41799. _super.prototype._afterBind.call(this, mesh);
  41800. this.getScene()._cachedEffect = effect;
  41801. };
  41802. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  41803. if (visibility === void 0) { visibility = 1; }
  41804. return scene.isCachedMaterialInvalid(this, effect, visibility);
  41805. };
  41806. return PushMaterial;
  41807. }(BABYLON.Material));
  41808. BABYLON.PushMaterial = PushMaterial;
  41809. })(BABYLON || (BABYLON = {}));
  41810. //# sourceMappingURL=babylon.pushMaterial.js.map
  41811. var BABYLON;
  41812. (function (BABYLON) {
  41813. /** @hidden */
  41814. var StandardMaterialDefines = /** @class */ (function (_super) {
  41815. __extends(StandardMaterialDefines, _super);
  41816. function StandardMaterialDefines() {
  41817. var _this = _super.call(this) || this;
  41818. _this.MAINUV1 = false;
  41819. _this.MAINUV2 = false;
  41820. _this.DIFFUSE = false;
  41821. _this.DIFFUSEDIRECTUV = 0;
  41822. _this.AMBIENT = false;
  41823. _this.AMBIENTDIRECTUV = 0;
  41824. _this.OPACITY = false;
  41825. _this.OPACITYDIRECTUV = 0;
  41826. _this.OPACITYRGB = false;
  41827. _this.REFLECTION = false;
  41828. _this.EMISSIVE = false;
  41829. _this.EMISSIVEDIRECTUV = 0;
  41830. _this.SPECULAR = false;
  41831. _this.SPECULARDIRECTUV = 0;
  41832. _this.BUMP = false;
  41833. _this.BUMPDIRECTUV = 0;
  41834. _this.PARALLAX = false;
  41835. _this.PARALLAXOCCLUSION = false;
  41836. _this.SPECULAROVERALPHA = false;
  41837. _this.CLIPPLANE = false;
  41838. _this.ALPHATEST = false;
  41839. _this.DEPTHPREPASS = false;
  41840. _this.ALPHAFROMDIFFUSE = false;
  41841. _this.POINTSIZE = false;
  41842. _this.FOG = false;
  41843. _this.SPECULARTERM = false;
  41844. _this.DIFFUSEFRESNEL = false;
  41845. _this.OPACITYFRESNEL = false;
  41846. _this.REFLECTIONFRESNEL = false;
  41847. _this.REFRACTIONFRESNEL = false;
  41848. _this.EMISSIVEFRESNEL = false;
  41849. _this.FRESNEL = false;
  41850. _this.NORMAL = false;
  41851. _this.UV1 = false;
  41852. _this.UV2 = false;
  41853. _this.VERTEXCOLOR = false;
  41854. _this.VERTEXALPHA = false;
  41855. _this.NUM_BONE_INFLUENCERS = 0;
  41856. _this.BonesPerMesh = 0;
  41857. _this.INSTANCES = false;
  41858. _this.GLOSSINESS = false;
  41859. _this.ROUGHNESS = false;
  41860. _this.EMISSIVEASILLUMINATION = false;
  41861. _this.LINKEMISSIVEWITHDIFFUSE = false;
  41862. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  41863. _this.LIGHTMAP = false;
  41864. _this.LIGHTMAPDIRECTUV = 0;
  41865. _this.OBJECTSPACE_NORMALMAP = false;
  41866. _this.USELIGHTMAPASSHADOWMAP = false;
  41867. _this.REFLECTIONMAP_3D = false;
  41868. _this.REFLECTIONMAP_SPHERICAL = false;
  41869. _this.REFLECTIONMAP_PLANAR = false;
  41870. _this.REFLECTIONMAP_CUBIC = false;
  41871. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  41872. _this.REFLECTIONMAP_PROJECTION = false;
  41873. _this.REFLECTIONMAP_SKYBOX = false;
  41874. _this.REFLECTIONMAP_EXPLICIT = false;
  41875. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  41876. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  41877. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  41878. _this.INVERTCUBICMAP = false;
  41879. _this.LOGARITHMICDEPTH = false;
  41880. _this.REFRACTION = false;
  41881. _this.REFRACTIONMAP_3D = false;
  41882. _this.REFLECTIONOVERALPHA = false;
  41883. _this.TWOSIDEDLIGHTING = false;
  41884. _this.SHADOWFLOAT = false;
  41885. _this.MORPHTARGETS = false;
  41886. _this.MORPHTARGETS_NORMAL = false;
  41887. _this.MORPHTARGETS_TANGENT = false;
  41888. _this.NUM_MORPH_INFLUENCERS = 0;
  41889. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  41890. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  41891. _this.IMAGEPROCESSING = false;
  41892. _this.VIGNETTE = false;
  41893. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  41894. _this.VIGNETTEBLENDMODEOPAQUE = false;
  41895. _this.TONEMAPPING = false;
  41896. _this.CONTRAST = false;
  41897. _this.COLORCURVES = false;
  41898. _this.COLORGRADING = false;
  41899. _this.COLORGRADING3D = false;
  41900. _this.SAMPLER3DGREENDEPTH = false;
  41901. _this.SAMPLER3DBGRMAP = false;
  41902. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  41903. /**
  41904. * If the reflection texture on this material is in linear color space
  41905. * @hidden
  41906. */
  41907. _this.IS_REFLECTION_LINEAR = false;
  41908. /**
  41909. * If the refraction texture on this material is in linear color space
  41910. * @hidden
  41911. */
  41912. _this.IS_REFRACTION_LINEAR = false;
  41913. _this.EXPOSURE = false;
  41914. _this.rebuild();
  41915. return _this;
  41916. }
  41917. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  41918. var modes = [
  41919. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  41920. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  41921. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  41922. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  41923. ];
  41924. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  41925. var mode = modes_1[_i];
  41926. this[mode] = (mode === modeToEnable);
  41927. }
  41928. };
  41929. return StandardMaterialDefines;
  41930. }(BABYLON.MaterialDefines));
  41931. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  41932. var StandardMaterial = /** @class */ (function (_super) {
  41933. __extends(StandardMaterial, _super);
  41934. function StandardMaterial(name, scene) {
  41935. var _this = _super.call(this, name, scene) || this;
  41936. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  41937. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  41938. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  41939. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41940. _this.specularPower = 64;
  41941. _this._useAlphaFromDiffuseTexture = false;
  41942. _this._useEmissiveAsIllumination = false;
  41943. _this._linkEmissiveWithDiffuse = false;
  41944. _this._useSpecularOverAlpha = false;
  41945. _this._useReflectionOverAlpha = false;
  41946. _this._disableLighting = false;
  41947. _this._useObjectSpaceNormalMap = false;
  41948. _this._useParallax = false;
  41949. _this._useParallaxOcclusion = false;
  41950. _this.parallaxScaleBias = 0.05;
  41951. _this._roughness = 0;
  41952. _this.indexOfRefraction = 0.98;
  41953. _this.invertRefractionY = true;
  41954. /**
  41955. * Defines the alpha limits in alpha test mode
  41956. */
  41957. _this.alphaCutOff = 0.4;
  41958. _this._useLightmapAsShadowmap = false;
  41959. _this._useReflectionFresnelFromSpecular = false;
  41960. _this._useGlossinessFromSpecularMapAlpha = false;
  41961. _this._maxSimultaneousLights = 4;
  41962. /**
  41963. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  41964. */
  41965. _this._invertNormalMapX = false;
  41966. /**
  41967. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  41968. */
  41969. _this._invertNormalMapY = false;
  41970. /**
  41971. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41972. */
  41973. _this._twoSidedLighting = false;
  41974. _this._renderTargets = new BABYLON.SmartArray(16);
  41975. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  41976. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  41977. // Setup the default processing configuration to the scene.
  41978. _this._attachImageProcessingConfiguration(null);
  41979. _this.getRenderTargetTextures = function () {
  41980. _this._renderTargets.reset();
  41981. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  41982. _this._renderTargets.push(_this._reflectionTexture);
  41983. }
  41984. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  41985. _this._renderTargets.push(_this._refractionTexture);
  41986. }
  41987. return _this._renderTargets;
  41988. };
  41989. return _this;
  41990. }
  41991. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  41992. /**
  41993. * Gets the image processing configuration used either in this material.
  41994. */
  41995. get: function () {
  41996. return this._imageProcessingConfiguration;
  41997. },
  41998. /**
  41999. * Sets the Default image processing configuration used either in the this material.
  42000. *
  42001. * If sets to null, the scene one is in use.
  42002. */
  42003. set: function (value) {
  42004. this._attachImageProcessingConfiguration(value);
  42005. // Ensure the effect will be rebuilt.
  42006. this._markAllSubMeshesAsTexturesDirty();
  42007. },
  42008. enumerable: true,
  42009. configurable: true
  42010. });
  42011. /**
  42012. * Attaches a new image processing configuration to the Standard Material.
  42013. * @param configuration
  42014. */
  42015. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  42016. var _this = this;
  42017. if (configuration === this._imageProcessingConfiguration) {
  42018. return;
  42019. }
  42020. // Detaches observer.
  42021. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42022. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42023. }
  42024. // Pick the scene configuration if needed.
  42025. if (!configuration) {
  42026. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  42027. }
  42028. else {
  42029. this._imageProcessingConfiguration = configuration;
  42030. }
  42031. // Attaches observer.
  42032. if (this._imageProcessingConfiguration) {
  42033. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  42034. _this._markAllSubMeshesAsImageProcessingDirty();
  42035. });
  42036. }
  42037. };
  42038. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  42039. /**
  42040. * Gets wether the color curves effect is enabled.
  42041. */
  42042. get: function () {
  42043. return this.imageProcessingConfiguration.colorCurvesEnabled;
  42044. },
  42045. /**
  42046. * Sets wether the color curves effect is enabled.
  42047. */
  42048. set: function (value) {
  42049. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  42050. },
  42051. enumerable: true,
  42052. configurable: true
  42053. });
  42054. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  42055. /**
  42056. * Gets wether the color grading effect is enabled.
  42057. */
  42058. get: function () {
  42059. return this.imageProcessingConfiguration.colorGradingEnabled;
  42060. },
  42061. /**
  42062. * Gets wether the color grading effect is enabled.
  42063. */
  42064. set: function (value) {
  42065. this.imageProcessingConfiguration.colorGradingEnabled = value;
  42066. },
  42067. enumerable: true,
  42068. configurable: true
  42069. });
  42070. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  42071. /**
  42072. * Gets wether tonemapping is enabled or not.
  42073. */
  42074. get: function () {
  42075. return this._imageProcessingConfiguration.toneMappingEnabled;
  42076. },
  42077. /**
  42078. * Sets wether tonemapping is enabled or not
  42079. */
  42080. set: function (value) {
  42081. this._imageProcessingConfiguration.toneMappingEnabled = value;
  42082. },
  42083. enumerable: true,
  42084. configurable: true
  42085. });
  42086. ;
  42087. ;
  42088. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  42089. /**
  42090. * The camera exposure used on this material.
  42091. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42092. * This corresponds to a photographic exposure.
  42093. */
  42094. get: function () {
  42095. return this._imageProcessingConfiguration.exposure;
  42096. },
  42097. /**
  42098. * The camera exposure used on this material.
  42099. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42100. * This corresponds to a photographic exposure.
  42101. */
  42102. set: function (value) {
  42103. this._imageProcessingConfiguration.exposure = value;
  42104. },
  42105. enumerable: true,
  42106. configurable: true
  42107. });
  42108. ;
  42109. ;
  42110. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  42111. /**
  42112. * Gets The camera contrast used on this material.
  42113. */
  42114. get: function () {
  42115. return this._imageProcessingConfiguration.contrast;
  42116. },
  42117. /**
  42118. * Sets The camera contrast used on this material.
  42119. */
  42120. set: function (value) {
  42121. this._imageProcessingConfiguration.contrast = value;
  42122. },
  42123. enumerable: true,
  42124. configurable: true
  42125. });
  42126. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  42127. /**
  42128. * Gets the Color Grading 2D Lookup Texture.
  42129. */
  42130. get: function () {
  42131. return this._imageProcessingConfiguration.colorGradingTexture;
  42132. },
  42133. /**
  42134. * Sets the Color Grading 2D Lookup Texture.
  42135. */
  42136. set: function (value) {
  42137. this._imageProcessingConfiguration.colorGradingTexture = value;
  42138. },
  42139. enumerable: true,
  42140. configurable: true
  42141. });
  42142. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  42143. /**
  42144. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42145. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42146. * 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;
  42147. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42148. */
  42149. get: function () {
  42150. return this._imageProcessingConfiguration.colorCurves;
  42151. },
  42152. /**
  42153. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42154. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42155. * 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;
  42156. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42157. */
  42158. set: function (value) {
  42159. this._imageProcessingConfiguration.colorCurves = value;
  42160. },
  42161. enumerable: true,
  42162. configurable: true
  42163. });
  42164. StandardMaterial.prototype.getClassName = function () {
  42165. return "StandardMaterial";
  42166. };
  42167. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  42168. get: function () {
  42169. return this._useLogarithmicDepth;
  42170. },
  42171. set: function (value) {
  42172. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  42173. this._markAllSubMeshesAsMiscDirty();
  42174. },
  42175. enumerable: true,
  42176. configurable: true
  42177. });
  42178. StandardMaterial.prototype.needAlphaBlending = function () {
  42179. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  42180. };
  42181. StandardMaterial.prototype.needAlphaTesting = function () {
  42182. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  42183. };
  42184. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  42185. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  42186. };
  42187. StandardMaterial.prototype.getAlphaTestTexture = function () {
  42188. return this._diffuseTexture;
  42189. };
  42190. /**
  42191. * Child classes can use it to update shaders
  42192. */
  42193. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  42194. if (useInstances === void 0) { useInstances = false; }
  42195. if (subMesh.effect && this.isFrozen) {
  42196. if (this._wasPreviouslyReady && subMesh.effect) {
  42197. return true;
  42198. }
  42199. }
  42200. if (!subMesh._materialDefines) {
  42201. subMesh._materialDefines = new StandardMaterialDefines();
  42202. }
  42203. var scene = this.getScene();
  42204. var defines = subMesh._materialDefines;
  42205. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  42206. if (defines._renderId === scene.getRenderId()) {
  42207. return true;
  42208. }
  42209. }
  42210. var engine = scene.getEngine();
  42211. // Lights
  42212. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  42213. // Textures
  42214. if (defines._areTexturesDirty) {
  42215. defines._needUVs = false;
  42216. defines.MAINUV1 = false;
  42217. defines.MAINUV2 = false;
  42218. if (scene.texturesEnabled) {
  42219. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42220. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  42221. return false;
  42222. }
  42223. else {
  42224. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  42225. }
  42226. }
  42227. else {
  42228. defines.DIFFUSE = false;
  42229. }
  42230. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42231. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  42232. return false;
  42233. }
  42234. else {
  42235. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  42236. }
  42237. }
  42238. else {
  42239. defines.AMBIENT = false;
  42240. }
  42241. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42242. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  42243. return false;
  42244. }
  42245. else {
  42246. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  42247. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  42248. }
  42249. }
  42250. else {
  42251. defines.OPACITY = false;
  42252. }
  42253. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42254. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  42255. return false;
  42256. }
  42257. else {
  42258. defines._needNormals = true;
  42259. defines.REFLECTION = true;
  42260. defines.ROUGHNESS = (this._roughness > 0);
  42261. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  42262. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  42263. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  42264. switch (this._reflectionTexture.coordinatesMode) {
  42265. case BABYLON.Texture.EXPLICIT_MODE:
  42266. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  42267. break;
  42268. case BABYLON.Texture.PLANAR_MODE:
  42269. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  42270. break;
  42271. case BABYLON.Texture.PROJECTION_MODE:
  42272. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  42273. break;
  42274. case BABYLON.Texture.SKYBOX_MODE:
  42275. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  42276. break;
  42277. case BABYLON.Texture.SPHERICAL_MODE:
  42278. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  42279. break;
  42280. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  42281. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  42282. break;
  42283. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  42284. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  42285. break;
  42286. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  42287. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  42288. break;
  42289. case BABYLON.Texture.CUBIC_MODE:
  42290. case BABYLON.Texture.INVCUBIC_MODE:
  42291. default:
  42292. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  42293. break;
  42294. }
  42295. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  42296. }
  42297. }
  42298. else {
  42299. defines.REFLECTION = false;
  42300. }
  42301. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42302. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  42303. return false;
  42304. }
  42305. else {
  42306. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  42307. }
  42308. }
  42309. else {
  42310. defines.EMISSIVE = false;
  42311. }
  42312. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42313. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  42314. return false;
  42315. }
  42316. else {
  42317. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  42318. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  42319. }
  42320. }
  42321. else {
  42322. defines.LIGHTMAP = false;
  42323. }
  42324. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42325. if (!this._specularTexture.isReadyOrNotBlocking()) {
  42326. return false;
  42327. }
  42328. else {
  42329. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  42330. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  42331. }
  42332. }
  42333. else {
  42334. defines.SPECULAR = false;
  42335. }
  42336. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  42337. // Bump texure can not be not blocking.
  42338. if (!this._bumpTexture.isReady()) {
  42339. return false;
  42340. }
  42341. else {
  42342. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  42343. defines.PARALLAX = this._useParallax;
  42344. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  42345. }
  42346. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  42347. }
  42348. else {
  42349. defines.BUMP = false;
  42350. }
  42351. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42352. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  42353. return false;
  42354. }
  42355. else {
  42356. defines._needUVs = true;
  42357. defines.REFRACTION = true;
  42358. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  42359. }
  42360. }
  42361. else {
  42362. defines.REFRACTION = false;
  42363. }
  42364. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  42365. }
  42366. else {
  42367. defines.DIFFUSE = false;
  42368. defines.AMBIENT = false;
  42369. defines.OPACITY = false;
  42370. defines.REFLECTION = false;
  42371. defines.EMISSIVE = false;
  42372. defines.LIGHTMAP = false;
  42373. defines.BUMP = false;
  42374. defines.REFRACTION = false;
  42375. }
  42376. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  42377. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  42378. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  42379. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  42380. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  42381. }
  42382. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  42383. if (!this._imageProcessingConfiguration.isReady()) {
  42384. return false;
  42385. }
  42386. this._imageProcessingConfiguration.prepareDefines(defines);
  42387. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  42388. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  42389. }
  42390. if (defines._areFresnelDirty) {
  42391. if (StandardMaterial.FresnelEnabled) {
  42392. // Fresnel
  42393. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  42394. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  42395. this._reflectionFresnelParameters) {
  42396. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  42397. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  42398. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  42399. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  42400. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  42401. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  42402. defines._needNormals = true;
  42403. defines.FRESNEL = true;
  42404. }
  42405. }
  42406. else {
  42407. defines.FRESNEL = false;
  42408. }
  42409. }
  42410. // Misc.
  42411. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  42412. // Attribs
  42413. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  42414. // Values that need to be evaluated on every frame
  42415. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  42416. // Get correct effect
  42417. if (defines.isDirty) {
  42418. defines.markAsProcessed();
  42419. scene.resetCachedMaterial();
  42420. // Fallbacks
  42421. var fallbacks = new BABYLON.EffectFallbacks();
  42422. if (defines.REFLECTION) {
  42423. fallbacks.addFallback(0, "REFLECTION");
  42424. }
  42425. if (defines.SPECULAR) {
  42426. fallbacks.addFallback(0, "SPECULAR");
  42427. }
  42428. if (defines.BUMP) {
  42429. fallbacks.addFallback(0, "BUMP");
  42430. }
  42431. if (defines.PARALLAX) {
  42432. fallbacks.addFallback(1, "PARALLAX");
  42433. }
  42434. if (defines.PARALLAXOCCLUSION) {
  42435. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  42436. }
  42437. if (defines.SPECULAROVERALPHA) {
  42438. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  42439. }
  42440. if (defines.FOG) {
  42441. fallbacks.addFallback(1, "FOG");
  42442. }
  42443. if (defines.POINTSIZE) {
  42444. fallbacks.addFallback(0, "POINTSIZE");
  42445. }
  42446. if (defines.LOGARITHMICDEPTH) {
  42447. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  42448. }
  42449. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  42450. if (defines.SPECULARTERM) {
  42451. fallbacks.addFallback(0, "SPECULARTERM");
  42452. }
  42453. if (defines.DIFFUSEFRESNEL) {
  42454. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  42455. }
  42456. if (defines.OPACITYFRESNEL) {
  42457. fallbacks.addFallback(2, "OPACITYFRESNEL");
  42458. }
  42459. if (defines.REFLECTIONFRESNEL) {
  42460. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  42461. }
  42462. if (defines.EMISSIVEFRESNEL) {
  42463. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  42464. }
  42465. if (defines.FRESNEL) {
  42466. fallbacks.addFallback(4, "FRESNEL");
  42467. }
  42468. //Attributes
  42469. var attribs = [BABYLON.VertexBuffer.PositionKind];
  42470. if (defines.NORMAL) {
  42471. attribs.push(BABYLON.VertexBuffer.NormalKind);
  42472. }
  42473. if (defines.UV1) {
  42474. attribs.push(BABYLON.VertexBuffer.UVKind);
  42475. }
  42476. if (defines.UV2) {
  42477. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  42478. }
  42479. if (defines.VERTEXCOLOR) {
  42480. attribs.push(BABYLON.VertexBuffer.ColorKind);
  42481. }
  42482. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  42483. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  42484. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  42485. var shaderName = "default";
  42486. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  42487. "vFogInfos", "vFogColor", "pointSize",
  42488. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  42489. "mBones",
  42490. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  42491. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  42492. "vReflectionPosition", "vReflectionSize",
  42493. "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff"
  42494. ];
  42495. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  42496. var uniformBuffers = ["Material", "Scene"];
  42497. if (BABYLON.ImageProcessingConfiguration) {
  42498. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  42499. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  42500. }
  42501. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  42502. uniformsNames: uniforms,
  42503. uniformBuffersNames: uniformBuffers,
  42504. samplers: samplers,
  42505. defines: defines,
  42506. maxSimultaneousLights: this._maxSimultaneousLights
  42507. });
  42508. if (this.customShaderNameResolve) {
  42509. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  42510. }
  42511. var join = defines.toString();
  42512. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  42513. attributes: attribs,
  42514. uniformsNames: uniforms,
  42515. uniformBuffersNames: uniformBuffers,
  42516. samplers: samplers,
  42517. defines: join,
  42518. fallbacks: fallbacks,
  42519. onCompiled: this.onCompiled,
  42520. onError: this.onError,
  42521. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  42522. }, engine), defines);
  42523. this.buildUniformLayout();
  42524. }
  42525. if (!subMesh.effect || !subMesh.effect.isReady()) {
  42526. return false;
  42527. }
  42528. defines._renderId = scene.getRenderId();
  42529. this._wasPreviouslyReady = true;
  42530. return true;
  42531. };
  42532. StandardMaterial.prototype.buildUniformLayout = function () {
  42533. // Order is important !
  42534. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  42535. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  42536. this._uniformBuffer.addUniform("opacityParts", 4);
  42537. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  42538. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  42539. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  42540. this._uniformBuffer.addUniform("refractionRightColor", 4);
  42541. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  42542. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  42543. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  42544. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  42545. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  42546. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  42547. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  42548. this._uniformBuffer.addUniform("vReflectionSize", 3);
  42549. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  42550. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  42551. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  42552. this._uniformBuffer.addUniform("vBumpInfos", 3);
  42553. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  42554. this._uniformBuffer.addUniform("ambientMatrix", 16);
  42555. this._uniformBuffer.addUniform("opacityMatrix", 16);
  42556. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  42557. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  42558. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  42559. this._uniformBuffer.addUniform("specularMatrix", 16);
  42560. this._uniformBuffer.addUniform("bumpMatrix", 16);
  42561. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  42562. this._uniformBuffer.addUniform("refractionMatrix", 16);
  42563. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  42564. this._uniformBuffer.addUniform("vSpecularColor", 4);
  42565. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  42566. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  42567. this._uniformBuffer.addUniform("pointSize", 1);
  42568. this._uniformBuffer.create();
  42569. };
  42570. StandardMaterial.prototype.unbind = function () {
  42571. if (this._activeEffect) {
  42572. var needFlag = false;
  42573. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  42574. this._activeEffect.setTexture("reflection2DSampler", null);
  42575. needFlag = true;
  42576. }
  42577. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  42578. this._activeEffect.setTexture("refraction2DSampler", null);
  42579. needFlag = true;
  42580. }
  42581. if (needFlag) {
  42582. this._markAllSubMeshesAsTexturesDirty();
  42583. }
  42584. }
  42585. _super.prototype.unbind.call(this);
  42586. };
  42587. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  42588. var scene = this.getScene();
  42589. var defines = subMesh._materialDefines;
  42590. if (!defines) {
  42591. return;
  42592. }
  42593. var effect = subMesh.effect;
  42594. if (!effect) {
  42595. return;
  42596. }
  42597. this._activeEffect = effect;
  42598. // Matrices
  42599. this.bindOnlyWorldMatrix(world);
  42600. // Normal Matrix
  42601. if (defines.OBJECTSPACE_NORMALMAP) {
  42602. world.toNormalMatrix(this._normalMatrix);
  42603. this.bindOnlyNormalMatrix(this._normalMatrix);
  42604. }
  42605. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  42606. // Bones
  42607. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  42608. if (mustRebind) {
  42609. this._uniformBuffer.bindToEffect(effect, "Material");
  42610. this.bindViewProjection(effect);
  42611. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  42612. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  42613. // Fresnel
  42614. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  42615. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  42616. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  42617. }
  42618. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  42619. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  42620. }
  42621. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  42622. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  42623. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  42624. }
  42625. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  42626. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  42627. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  42628. }
  42629. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  42630. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  42631. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  42632. }
  42633. }
  42634. // Textures
  42635. if (scene.texturesEnabled) {
  42636. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42637. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  42638. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  42639. if (this._diffuseTexture.hasAlpha) {
  42640. effect.setFloat("alphaCutOff", this.alphaCutOff);
  42641. }
  42642. }
  42643. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42644. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  42645. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  42646. }
  42647. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42648. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  42649. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  42650. }
  42651. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42652. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  42653. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  42654. if (this._reflectionTexture.boundingBoxSize) {
  42655. var cubeTexture = this._reflectionTexture;
  42656. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  42657. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  42658. }
  42659. }
  42660. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42661. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  42662. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  42663. }
  42664. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42665. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  42666. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  42667. }
  42668. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42669. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  42670. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  42671. }
  42672. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42673. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  42674. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  42675. if (scene._mirroredCameraPosition) {
  42676. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  42677. }
  42678. else {
  42679. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  42680. }
  42681. }
  42682. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42683. var depth = 1.0;
  42684. if (!this._refractionTexture.isCube) {
  42685. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  42686. if (this._refractionTexture.depth) {
  42687. depth = this._refractionTexture.depth;
  42688. }
  42689. }
  42690. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  42691. }
  42692. }
  42693. // Point size
  42694. if (this.pointsCloud) {
  42695. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  42696. }
  42697. if (defines.SPECULARTERM) {
  42698. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  42699. }
  42700. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  42701. // Diffuse
  42702. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  42703. }
  42704. // Textures
  42705. if (scene.texturesEnabled) {
  42706. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42707. effect.setTexture("diffuseSampler", this._diffuseTexture);
  42708. }
  42709. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42710. effect.setTexture("ambientSampler", this._ambientTexture);
  42711. }
  42712. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42713. effect.setTexture("opacitySampler", this._opacityTexture);
  42714. }
  42715. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42716. if (this._reflectionTexture.isCube) {
  42717. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  42718. }
  42719. else {
  42720. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  42721. }
  42722. }
  42723. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42724. effect.setTexture("emissiveSampler", this._emissiveTexture);
  42725. }
  42726. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42727. effect.setTexture("lightmapSampler", this._lightmapTexture);
  42728. }
  42729. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42730. effect.setTexture("specularSampler", this._specularTexture);
  42731. }
  42732. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42733. effect.setTexture("bumpSampler", this._bumpTexture);
  42734. }
  42735. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42736. var depth = 1.0;
  42737. if (this._refractionTexture.isCube) {
  42738. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  42739. }
  42740. else {
  42741. effect.setTexture("refraction2DSampler", this._refractionTexture);
  42742. }
  42743. }
  42744. }
  42745. // Clip plane
  42746. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  42747. // Colors
  42748. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  42749. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  42750. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  42751. }
  42752. if (mustRebind || !this.isFrozen) {
  42753. // Lights
  42754. if (scene.lightsEnabled && !this._disableLighting) {
  42755. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  42756. }
  42757. // View
  42758. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  42759. this.bindView(effect);
  42760. }
  42761. // Fog
  42762. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  42763. // Morph targets
  42764. if (defines.NUM_MORPH_INFLUENCERS) {
  42765. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  42766. }
  42767. // Log. depth
  42768. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  42769. // image processing
  42770. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  42771. this._imageProcessingConfiguration.bind(this._activeEffect);
  42772. }
  42773. }
  42774. this._uniformBuffer.update();
  42775. this._afterBind(mesh, this._activeEffect);
  42776. };
  42777. StandardMaterial.prototype.getAnimatables = function () {
  42778. var results = [];
  42779. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  42780. results.push(this._diffuseTexture);
  42781. }
  42782. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  42783. results.push(this._ambientTexture);
  42784. }
  42785. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  42786. results.push(this._opacityTexture);
  42787. }
  42788. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  42789. results.push(this._reflectionTexture);
  42790. }
  42791. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  42792. results.push(this._emissiveTexture);
  42793. }
  42794. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  42795. results.push(this._specularTexture);
  42796. }
  42797. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  42798. results.push(this._bumpTexture);
  42799. }
  42800. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  42801. results.push(this._lightmapTexture);
  42802. }
  42803. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  42804. results.push(this._refractionTexture);
  42805. }
  42806. return results;
  42807. };
  42808. StandardMaterial.prototype.getActiveTextures = function () {
  42809. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42810. if (this._diffuseTexture) {
  42811. activeTextures.push(this._diffuseTexture);
  42812. }
  42813. if (this._ambientTexture) {
  42814. activeTextures.push(this._ambientTexture);
  42815. }
  42816. if (this._opacityTexture) {
  42817. activeTextures.push(this._opacityTexture);
  42818. }
  42819. if (this._reflectionTexture) {
  42820. activeTextures.push(this._reflectionTexture);
  42821. }
  42822. if (this._emissiveTexture) {
  42823. activeTextures.push(this._emissiveTexture);
  42824. }
  42825. if (this._specularTexture) {
  42826. activeTextures.push(this._specularTexture);
  42827. }
  42828. if (this._bumpTexture) {
  42829. activeTextures.push(this._bumpTexture);
  42830. }
  42831. if (this._lightmapTexture) {
  42832. activeTextures.push(this._lightmapTexture);
  42833. }
  42834. if (this._refractionTexture) {
  42835. activeTextures.push(this._refractionTexture);
  42836. }
  42837. return activeTextures;
  42838. };
  42839. StandardMaterial.prototype.hasTexture = function (texture) {
  42840. if (_super.prototype.hasTexture.call(this, texture)) {
  42841. return true;
  42842. }
  42843. if (this._diffuseTexture === texture) {
  42844. return true;
  42845. }
  42846. if (this._ambientTexture === texture) {
  42847. return true;
  42848. }
  42849. if (this._opacityTexture === texture) {
  42850. return true;
  42851. }
  42852. if (this._reflectionTexture === texture) {
  42853. return true;
  42854. }
  42855. if (this._emissiveTexture === texture) {
  42856. return true;
  42857. }
  42858. if (this._specularTexture === texture) {
  42859. return true;
  42860. }
  42861. if (this._bumpTexture === texture) {
  42862. return true;
  42863. }
  42864. if (this._lightmapTexture === texture) {
  42865. return true;
  42866. }
  42867. if (this._refractionTexture === texture) {
  42868. return true;
  42869. }
  42870. return false;
  42871. };
  42872. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  42873. if (forceDisposeTextures) {
  42874. if (this._diffuseTexture) {
  42875. this._diffuseTexture.dispose();
  42876. }
  42877. if (this._ambientTexture) {
  42878. this._ambientTexture.dispose();
  42879. }
  42880. if (this._opacityTexture) {
  42881. this._opacityTexture.dispose();
  42882. }
  42883. if (this._reflectionTexture) {
  42884. this._reflectionTexture.dispose();
  42885. }
  42886. if (this._emissiveTexture) {
  42887. this._emissiveTexture.dispose();
  42888. }
  42889. if (this._specularTexture) {
  42890. this._specularTexture.dispose();
  42891. }
  42892. if (this._bumpTexture) {
  42893. this._bumpTexture.dispose();
  42894. }
  42895. if (this._lightmapTexture) {
  42896. this._lightmapTexture.dispose();
  42897. }
  42898. if (this._refractionTexture) {
  42899. this._refractionTexture.dispose();
  42900. }
  42901. }
  42902. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42903. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42904. }
  42905. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  42906. };
  42907. StandardMaterial.prototype.clone = function (name) {
  42908. var _this = this;
  42909. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  42910. result.name = name;
  42911. result.id = name;
  42912. return result;
  42913. };
  42914. StandardMaterial.prototype.serialize = function () {
  42915. return BABYLON.SerializationHelper.Serialize(this);
  42916. };
  42917. // Statics
  42918. StandardMaterial.Parse = function (source, scene, rootUrl) {
  42919. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  42920. };
  42921. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  42922. get: function () {
  42923. return StandardMaterial._DiffuseTextureEnabled;
  42924. },
  42925. set: function (value) {
  42926. if (StandardMaterial._DiffuseTextureEnabled === value) {
  42927. return;
  42928. }
  42929. StandardMaterial._DiffuseTextureEnabled = value;
  42930. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42931. },
  42932. enumerable: true,
  42933. configurable: true
  42934. });
  42935. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  42936. get: function () {
  42937. return StandardMaterial._AmbientTextureEnabled;
  42938. },
  42939. set: function (value) {
  42940. if (StandardMaterial._AmbientTextureEnabled === value) {
  42941. return;
  42942. }
  42943. StandardMaterial._AmbientTextureEnabled = value;
  42944. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42945. },
  42946. enumerable: true,
  42947. configurable: true
  42948. });
  42949. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  42950. get: function () {
  42951. return StandardMaterial._OpacityTextureEnabled;
  42952. },
  42953. set: function (value) {
  42954. if (StandardMaterial._OpacityTextureEnabled === value) {
  42955. return;
  42956. }
  42957. StandardMaterial._OpacityTextureEnabled = value;
  42958. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42959. },
  42960. enumerable: true,
  42961. configurable: true
  42962. });
  42963. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  42964. get: function () {
  42965. return StandardMaterial._ReflectionTextureEnabled;
  42966. },
  42967. set: function (value) {
  42968. if (StandardMaterial._ReflectionTextureEnabled === value) {
  42969. return;
  42970. }
  42971. StandardMaterial._ReflectionTextureEnabled = value;
  42972. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42973. },
  42974. enumerable: true,
  42975. configurable: true
  42976. });
  42977. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  42978. get: function () {
  42979. return StandardMaterial._EmissiveTextureEnabled;
  42980. },
  42981. set: function (value) {
  42982. if (StandardMaterial._EmissiveTextureEnabled === value) {
  42983. return;
  42984. }
  42985. StandardMaterial._EmissiveTextureEnabled = value;
  42986. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42987. },
  42988. enumerable: true,
  42989. configurable: true
  42990. });
  42991. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  42992. get: function () {
  42993. return StandardMaterial._SpecularTextureEnabled;
  42994. },
  42995. set: function (value) {
  42996. if (StandardMaterial._SpecularTextureEnabled === value) {
  42997. return;
  42998. }
  42999. StandardMaterial._SpecularTextureEnabled = value;
  43000. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43001. },
  43002. enumerable: true,
  43003. configurable: true
  43004. });
  43005. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  43006. get: function () {
  43007. return StandardMaterial._BumpTextureEnabled;
  43008. },
  43009. set: function (value) {
  43010. if (StandardMaterial._BumpTextureEnabled === value) {
  43011. return;
  43012. }
  43013. StandardMaterial._BumpTextureEnabled = value;
  43014. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43015. },
  43016. enumerable: true,
  43017. configurable: true
  43018. });
  43019. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  43020. get: function () {
  43021. return StandardMaterial._LightmapTextureEnabled;
  43022. },
  43023. set: function (value) {
  43024. if (StandardMaterial._LightmapTextureEnabled === value) {
  43025. return;
  43026. }
  43027. StandardMaterial._LightmapTextureEnabled = value;
  43028. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43029. },
  43030. enumerable: true,
  43031. configurable: true
  43032. });
  43033. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  43034. get: function () {
  43035. return StandardMaterial._RefractionTextureEnabled;
  43036. },
  43037. set: function (value) {
  43038. if (StandardMaterial._RefractionTextureEnabled === value) {
  43039. return;
  43040. }
  43041. StandardMaterial._RefractionTextureEnabled = value;
  43042. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43043. },
  43044. enumerable: true,
  43045. configurable: true
  43046. });
  43047. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  43048. get: function () {
  43049. return StandardMaterial._ColorGradingTextureEnabled;
  43050. },
  43051. set: function (value) {
  43052. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  43053. return;
  43054. }
  43055. StandardMaterial._ColorGradingTextureEnabled = value;
  43056. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43057. },
  43058. enumerable: true,
  43059. configurable: true
  43060. });
  43061. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  43062. get: function () {
  43063. return StandardMaterial._FresnelEnabled;
  43064. },
  43065. set: function (value) {
  43066. if (StandardMaterial._FresnelEnabled === value) {
  43067. return;
  43068. }
  43069. StandardMaterial._FresnelEnabled = value;
  43070. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  43071. },
  43072. enumerable: true,
  43073. configurable: true
  43074. });
  43075. // Flags used to enable or disable a type of texture for all Standard Materials
  43076. StandardMaterial._DiffuseTextureEnabled = true;
  43077. StandardMaterial._AmbientTextureEnabled = true;
  43078. StandardMaterial._OpacityTextureEnabled = true;
  43079. StandardMaterial._ReflectionTextureEnabled = true;
  43080. StandardMaterial._EmissiveTextureEnabled = true;
  43081. StandardMaterial._SpecularTextureEnabled = true;
  43082. StandardMaterial._BumpTextureEnabled = true;
  43083. StandardMaterial._LightmapTextureEnabled = true;
  43084. StandardMaterial._RefractionTextureEnabled = true;
  43085. StandardMaterial._ColorGradingTextureEnabled = true;
  43086. StandardMaterial._FresnelEnabled = true;
  43087. __decorate([
  43088. BABYLON.serializeAsTexture("diffuseTexture")
  43089. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  43090. __decorate([
  43091. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43092. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  43093. __decorate([
  43094. BABYLON.serializeAsTexture("ambientTexture")
  43095. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  43096. __decorate([
  43097. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43098. ], StandardMaterial.prototype, "ambientTexture", void 0);
  43099. __decorate([
  43100. BABYLON.serializeAsTexture("opacityTexture")
  43101. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  43102. __decorate([
  43103. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43104. ], StandardMaterial.prototype, "opacityTexture", void 0);
  43105. __decorate([
  43106. BABYLON.serializeAsTexture("reflectionTexture")
  43107. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  43108. __decorate([
  43109. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43110. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  43111. __decorate([
  43112. BABYLON.serializeAsTexture("emissiveTexture")
  43113. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  43114. __decorate([
  43115. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43116. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  43117. __decorate([
  43118. BABYLON.serializeAsTexture("specularTexture")
  43119. ], StandardMaterial.prototype, "_specularTexture", void 0);
  43120. __decorate([
  43121. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43122. ], StandardMaterial.prototype, "specularTexture", void 0);
  43123. __decorate([
  43124. BABYLON.serializeAsTexture("bumpTexture")
  43125. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  43126. __decorate([
  43127. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43128. ], StandardMaterial.prototype, "bumpTexture", void 0);
  43129. __decorate([
  43130. BABYLON.serializeAsTexture("lightmapTexture")
  43131. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  43132. __decorate([
  43133. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43134. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  43135. __decorate([
  43136. BABYLON.serializeAsTexture("refractionTexture")
  43137. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  43138. __decorate([
  43139. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43140. ], StandardMaterial.prototype, "refractionTexture", void 0);
  43141. __decorate([
  43142. BABYLON.serializeAsColor3("ambient")
  43143. ], StandardMaterial.prototype, "ambientColor", void 0);
  43144. __decorate([
  43145. BABYLON.serializeAsColor3("diffuse")
  43146. ], StandardMaterial.prototype, "diffuseColor", void 0);
  43147. __decorate([
  43148. BABYLON.serializeAsColor3("specular")
  43149. ], StandardMaterial.prototype, "specularColor", void 0);
  43150. __decorate([
  43151. BABYLON.serializeAsColor3("emissive")
  43152. ], StandardMaterial.prototype, "emissiveColor", void 0);
  43153. __decorate([
  43154. BABYLON.serialize()
  43155. ], StandardMaterial.prototype, "specularPower", void 0);
  43156. __decorate([
  43157. BABYLON.serialize("useAlphaFromDiffuseTexture")
  43158. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  43159. __decorate([
  43160. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43161. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  43162. __decorate([
  43163. BABYLON.serialize("useEmissiveAsIllumination")
  43164. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  43165. __decorate([
  43166. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43167. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  43168. __decorate([
  43169. BABYLON.serialize("linkEmissiveWithDiffuse")
  43170. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  43171. __decorate([
  43172. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43173. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  43174. __decorate([
  43175. BABYLON.serialize("useSpecularOverAlpha")
  43176. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  43177. __decorate([
  43178. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43179. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  43180. __decorate([
  43181. BABYLON.serialize("useReflectionOverAlpha")
  43182. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  43183. __decorate([
  43184. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43185. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  43186. __decorate([
  43187. BABYLON.serialize("disableLighting")
  43188. ], StandardMaterial.prototype, "_disableLighting", void 0);
  43189. __decorate([
  43190. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43191. ], StandardMaterial.prototype, "disableLighting", void 0);
  43192. __decorate([
  43193. BABYLON.serialize("useObjectSpaceNormalMap")
  43194. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  43195. __decorate([
  43196. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43197. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  43198. __decorate([
  43199. BABYLON.serialize("useParallax")
  43200. ], StandardMaterial.prototype, "_useParallax", void 0);
  43201. __decorate([
  43202. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43203. ], StandardMaterial.prototype, "useParallax", void 0);
  43204. __decorate([
  43205. BABYLON.serialize("useParallaxOcclusion")
  43206. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  43207. __decorate([
  43208. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43209. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  43210. __decorate([
  43211. BABYLON.serialize()
  43212. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  43213. __decorate([
  43214. BABYLON.serialize("roughness")
  43215. ], StandardMaterial.prototype, "_roughness", void 0);
  43216. __decorate([
  43217. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43218. ], StandardMaterial.prototype, "roughness", void 0);
  43219. __decorate([
  43220. BABYLON.serialize()
  43221. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  43222. __decorate([
  43223. BABYLON.serialize()
  43224. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  43225. __decorate([
  43226. BABYLON.serialize()
  43227. ], StandardMaterial.prototype, "alphaCutOff", void 0);
  43228. __decorate([
  43229. BABYLON.serialize("useLightmapAsShadowmap")
  43230. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  43231. __decorate([
  43232. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43233. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  43234. __decorate([
  43235. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  43236. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  43237. __decorate([
  43238. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43239. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  43240. __decorate([
  43241. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  43242. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  43243. __decorate([
  43244. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  43245. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  43246. __decorate([
  43247. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  43248. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  43249. __decorate([
  43250. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43251. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  43252. __decorate([
  43253. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  43254. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  43255. __decorate([
  43256. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43257. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  43258. __decorate([
  43259. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  43260. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  43261. __decorate([
  43262. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43263. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  43264. __decorate([
  43265. BABYLON.serialize("useReflectionFresnelFromSpecular")
  43266. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  43267. __decorate([
  43268. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43269. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  43270. __decorate([
  43271. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  43272. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  43273. __decorate([
  43274. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43275. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  43276. __decorate([
  43277. BABYLON.serialize("maxSimultaneousLights")
  43278. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  43279. __decorate([
  43280. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43281. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  43282. __decorate([
  43283. BABYLON.serialize("invertNormalMapX")
  43284. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  43285. __decorate([
  43286. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43287. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  43288. __decorate([
  43289. BABYLON.serialize("invertNormalMapY")
  43290. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  43291. __decorate([
  43292. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43293. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  43294. __decorate([
  43295. BABYLON.serialize("twoSidedLighting")
  43296. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  43297. __decorate([
  43298. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43299. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  43300. __decorate([
  43301. BABYLON.serialize()
  43302. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  43303. return StandardMaterial;
  43304. }(BABYLON.PushMaterial));
  43305. BABYLON.StandardMaterial = StandardMaterial;
  43306. })(BABYLON || (BABYLON = {}));
  43307. //# sourceMappingURL=babylon.standardMaterial.js.map
  43308. var BABYLON;
  43309. (function (BABYLON) {
  43310. /**
  43311. * Manages the defines for the PBR Material.
  43312. * @hiddenChildren
  43313. */
  43314. var PBRMaterialDefines = /** @class */ (function (_super) {
  43315. __extends(PBRMaterialDefines, _super);
  43316. /**
  43317. * Initializes the PBR Material defines.
  43318. */
  43319. function PBRMaterialDefines() {
  43320. var _this = _super.call(this) || this;
  43321. _this.PBR = true;
  43322. _this.MAINUV1 = false;
  43323. _this.MAINUV2 = false;
  43324. _this.UV1 = false;
  43325. _this.UV2 = false;
  43326. _this.ALBEDO = false;
  43327. _this.ALBEDODIRECTUV = 0;
  43328. _this.VERTEXCOLOR = false;
  43329. _this.AMBIENT = false;
  43330. _this.AMBIENTDIRECTUV = 0;
  43331. _this.AMBIENTINGRAYSCALE = false;
  43332. _this.OPACITY = false;
  43333. _this.VERTEXALPHA = false;
  43334. _this.OPACITYDIRECTUV = 0;
  43335. _this.OPACITYRGB = false;
  43336. _this.ALPHATEST = false;
  43337. _this.DEPTHPREPASS = false;
  43338. _this.ALPHABLEND = false;
  43339. _this.ALPHAFROMALBEDO = false;
  43340. _this.ALPHATESTVALUE = "0.5";
  43341. _this.SPECULAROVERALPHA = false;
  43342. _this.RADIANCEOVERALPHA = false;
  43343. _this.ALPHAFRESNEL = false;
  43344. _this.LINEARALPHAFRESNEL = false;
  43345. _this.PREMULTIPLYALPHA = false;
  43346. _this.EMISSIVE = false;
  43347. _this.EMISSIVEDIRECTUV = 0;
  43348. _this.REFLECTIVITY = false;
  43349. _this.REFLECTIVITYDIRECTUV = 0;
  43350. _this.SPECULARTERM = false;
  43351. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  43352. _this.MICROSURFACEAUTOMATIC = false;
  43353. _this.LODBASEDMICROSFURACE = false;
  43354. _this.MICROSURFACEMAP = false;
  43355. _this.MICROSURFACEMAPDIRECTUV = 0;
  43356. _this.METALLICWORKFLOW = false;
  43357. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  43358. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  43359. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  43360. _this.AOSTOREINMETALMAPRED = false;
  43361. _this.ENVIRONMENTBRDF = false;
  43362. _this.NORMAL = false;
  43363. _this.TANGENT = false;
  43364. _this.BUMP = false;
  43365. _this.BUMPDIRECTUV = 0;
  43366. _this.OBJECTSPACE_NORMALMAP = false;
  43367. _this.PARALLAX = false;
  43368. _this.PARALLAXOCCLUSION = false;
  43369. _this.NORMALXYSCALE = true;
  43370. _this.LIGHTMAP = false;
  43371. _this.LIGHTMAPDIRECTUV = 0;
  43372. _this.USELIGHTMAPASSHADOWMAP = false;
  43373. _this.GAMMALIGHTMAP = false;
  43374. _this.REFLECTION = false;
  43375. _this.REFLECTIONMAP_3D = false;
  43376. _this.REFLECTIONMAP_SPHERICAL = false;
  43377. _this.REFLECTIONMAP_PLANAR = false;
  43378. _this.REFLECTIONMAP_CUBIC = false;
  43379. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  43380. _this.REFLECTIONMAP_PROJECTION = false;
  43381. _this.REFLECTIONMAP_SKYBOX = false;
  43382. _this.REFLECTIONMAP_EXPLICIT = false;
  43383. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  43384. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  43385. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  43386. _this.INVERTCUBICMAP = false;
  43387. _this.USESPHERICALFROMREFLECTIONMAP = false;
  43388. _this.USESPHERICALINVERTEX = false;
  43389. _this.REFLECTIONMAP_OPPOSITEZ = false;
  43390. _this.LODINREFLECTIONALPHA = false;
  43391. _this.GAMMAREFLECTION = false;
  43392. _this.RGBDREFLECTION = false;
  43393. _this.RADIANCEOCCLUSION = false;
  43394. _this.HORIZONOCCLUSION = false;
  43395. _this.REFRACTION = false;
  43396. _this.REFRACTIONMAP_3D = false;
  43397. _this.REFRACTIONMAP_OPPOSITEZ = false;
  43398. _this.LODINREFRACTIONALPHA = false;
  43399. _this.GAMMAREFRACTION = false;
  43400. _this.RGBDREFRACTION = false;
  43401. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  43402. _this.INSTANCES = false;
  43403. _this.NUM_BONE_INFLUENCERS = 0;
  43404. _this.BonesPerMesh = 0;
  43405. _this.NONUNIFORMSCALING = false;
  43406. _this.MORPHTARGETS = false;
  43407. _this.MORPHTARGETS_NORMAL = false;
  43408. _this.MORPHTARGETS_TANGENT = false;
  43409. _this.NUM_MORPH_INFLUENCERS = 0;
  43410. _this.IMAGEPROCESSING = false;
  43411. _this.VIGNETTE = false;
  43412. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  43413. _this.VIGNETTEBLENDMODEOPAQUE = false;
  43414. _this.TONEMAPPING = false;
  43415. _this.CONTRAST = false;
  43416. _this.COLORCURVES = false;
  43417. _this.COLORGRADING = false;
  43418. _this.COLORGRADING3D = false;
  43419. _this.SAMPLER3DGREENDEPTH = false;
  43420. _this.SAMPLER3DBGRMAP = false;
  43421. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  43422. _this.EXPOSURE = false;
  43423. _this.USEPHYSICALLIGHTFALLOFF = false;
  43424. _this.TWOSIDEDLIGHTING = false;
  43425. _this.SHADOWFLOAT = false;
  43426. _this.CLIPPLANE = false;
  43427. _this.POINTSIZE = false;
  43428. _this.FOG = false;
  43429. _this.LOGARITHMICDEPTH = false;
  43430. _this.FORCENORMALFORWARD = false;
  43431. _this.SPECULARAA = false;
  43432. _this.UNLIT = false;
  43433. _this.rebuild();
  43434. return _this;
  43435. }
  43436. /**
  43437. * Resets the PBR Material defines.
  43438. */
  43439. PBRMaterialDefines.prototype.reset = function () {
  43440. _super.prototype.reset.call(this);
  43441. this.ALPHATESTVALUE = "0.5";
  43442. this.PBR = true;
  43443. };
  43444. return PBRMaterialDefines;
  43445. }(BABYLON.MaterialDefines));
  43446. /**
  43447. * The Physically based material base class of BJS.
  43448. *
  43449. * This offers the main features of a standard PBR material.
  43450. * For more information, please refer to the documentation :
  43451. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  43452. */
  43453. var PBRBaseMaterial = /** @class */ (function (_super) {
  43454. __extends(PBRBaseMaterial, _super);
  43455. /**
  43456. * Instantiates a new PBRMaterial instance.
  43457. *
  43458. * @param name The material name
  43459. * @param scene The scene the material will be use in.
  43460. */
  43461. function PBRBaseMaterial(name, scene) {
  43462. var _this = _super.call(this, name, scene) || this;
  43463. /**
  43464. * Intensity of the direct lights e.g. the four lights available in your scene.
  43465. * This impacts both the direct diffuse and specular highlights.
  43466. */
  43467. _this._directIntensity = 1.0;
  43468. /**
  43469. * Intensity of the emissive part of the material.
  43470. * This helps controlling the emissive effect without modifying the emissive color.
  43471. */
  43472. _this._emissiveIntensity = 1.0;
  43473. /**
  43474. * Intensity of the environment e.g. how much the environment will light the object
  43475. * either through harmonics for rough material or through the refelction for shiny ones.
  43476. */
  43477. _this._environmentIntensity = 1.0;
  43478. /**
  43479. * This is a special control allowing the reduction of the specular highlights coming from the
  43480. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  43481. */
  43482. _this._specularIntensity = 1.0;
  43483. /**
  43484. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  43485. */
  43486. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  43487. /**
  43488. * Debug Control allowing disabling the bump map on this material.
  43489. */
  43490. _this._disableBumpMap = false;
  43491. /**
  43492. * AKA Occlusion Texture Intensity in other nomenclature.
  43493. */
  43494. _this._ambientTextureStrength = 1.0;
  43495. /**
  43496. * The color of a material in ambient lighting.
  43497. */
  43498. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  43499. /**
  43500. * AKA Diffuse Color in other nomenclature.
  43501. */
  43502. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  43503. /**
  43504. * AKA Specular Color in other nomenclature.
  43505. */
  43506. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  43507. /**
  43508. * The color applied when light is reflected from a material.
  43509. */
  43510. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  43511. /**
  43512. * The color applied when light is emitted from a material.
  43513. */
  43514. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  43515. /**
  43516. * AKA Glossiness in other nomenclature.
  43517. */
  43518. _this._microSurface = 0.9;
  43519. /**
  43520. * source material index of refraction (IOR)' / 'destination material IOR.
  43521. */
  43522. _this._indexOfRefraction = 0.66;
  43523. /**
  43524. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  43525. */
  43526. _this._invertRefractionY = false;
  43527. /**
  43528. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  43529. * Materials half opaque for instance using refraction could benefit from this control.
  43530. */
  43531. _this._linkRefractionWithTransparency = false;
  43532. /**
  43533. * Specifies that the material will use the light map as a show map.
  43534. */
  43535. _this._useLightmapAsShadowmap = false;
  43536. /**
  43537. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  43538. * makes the reflect vector face the model (under horizon).
  43539. */
  43540. _this._useHorizonOcclusion = true;
  43541. /**
  43542. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  43543. * too much the area relying on ambient texture to define their ambient occlusion.
  43544. */
  43545. _this._useRadianceOcclusion = true;
  43546. /**
  43547. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  43548. */
  43549. _this._useAlphaFromAlbedoTexture = false;
  43550. /**
  43551. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  43552. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  43553. */
  43554. _this._useSpecularOverAlpha = true;
  43555. /**
  43556. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  43557. */
  43558. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  43559. /**
  43560. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  43561. */
  43562. _this._useRoughnessFromMetallicTextureAlpha = true;
  43563. /**
  43564. * Specifies if the metallic texture contains the roughness information in its green channel.
  43565. */
  43566. _this._useRoughnessFromMetallicTextureGreen = false;
  43567. /**
  43568. * Specifies if the metallic texture contains the metallness information in its blue channel.
  43569. */
  43570. _this._useMetallnessFromMetallicTextureBlue = false;
  43571. /**
  43572. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  43573. */
  43574. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  43575. /**
  43576. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  43577. */
  43578. _this._useAmbientInGrayScale = false;
  43579. /**
  43580. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  43581. * The material will try to infer what glossiness each pixel should be.
  43582. */
  43583. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  43584. /**
  43585. * BJS is using an harcoded light falloff based on a manually sets up range.
  43586. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  43587. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  43588. */
  43589. _this._usePhysicalLightFalloff = true;
  43590. /**
  43591. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  43592. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  43593. */
  43594. _this._useRadianceOverAlpha = true;
  43595. /**
  43596. * Allows using an object space normal map (instead of tangent space).
  43597. */
  43598. _this._useObjectSpaceNormalMap = false;
  43599. /**
  43600. * Allows using the bump map in parallax mode.
  43601. */
  43602. _this._useParallax = false;
  43603. /**
  43604. * Allows using the bump map in parallax occlusion mode.
  43605. */
  43606. _this._useParallaxOcclusion = false;
  43607. /**
  43608. * Controls the scale bias of the parallax mode.
  43609. */
  43610. _this._parallaxScaleBias = 0.05;
  43611. /**
  43612. * If sets to true, disables all the lights affecting the material.
  43613. */
  43614. _this._disableLighting = false;
  43615. /**
  43616. * Number of Simultaneous lights allowed on the material.
  43617. */
  43618. _this._maxSimultaneousLights = 4;
  43619. /**
  43620. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  43621. */
  43622. _this._invertNormalMapX = false;
  43623. /**
  43624. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  43625. */
  43626. _this._invertNormalMapY = false;
  43627. /**
  43628. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  43629. */
  43630. _this._twoSidedLighting = false;
  43631. /**
  43632. * Defines the alpha limits in alpha test mode.
  43633. */
  43634. _this._alphaCutOff = 0.4;
  43635. /**
  43636. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  43637. */
  43638. _this._forceAlphaTest = false;
  43639. /**
  43640. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43641. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  43642. */
  43643. _this._useAlphaFresnel = false;
  43644. /**
  43645. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43646. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  43647. */
  43648. _this._useLinearAlphaFresnel = false;
  43649. /**
  43650. * The transparency mode of the material.
  43651. */
  43652. _this._transparencyMode = null;
  43653. /**
  43654. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  43655. * from cos thetav and roughness:
  43656. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  43657. */
  43658. _this._environmentBRDFTexture = null;
  43659. /**
  43660. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  43661. */
  43662. _this._forceIrradianceInFragment = false;
  43663. /**
  43664. * Force normal to face away from face.
  43665. */
  43666. _this._forceNormalForward = false;
  43667. /**
  43668. * Enables specular anti aliasing in the PBR shader.
  43669. * It will both interacts on the Geometry for analytical and IBL lighting.
  43670. * It also prefilter the roughness map based on the bump values.
  43671. */
  43672. _this._enableSpecularAntiAliasing = false;
  43673. /**
  43674. * Stores the available render targets.
  43675. */
  43676. _this._renderTargets = new BABYLON.SmartArray(16);
  43677. /**
  43678. * Sets the global ambient color for the material used in lighting calculations.
  43679. */
  43680. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  43681. /**
  43682. * If set to true, no lighting calculations will be applied.
  43683. */
  43684. _this._unlit = false;
  43685. // Setup the default processing configuration to the scene.
  43686. _this._attachImageProcessingConfiguration(null);
  43687. _this.getRenderTargetTextures = function () {
  43688. _this._renderTargets.reset();
  43689. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  43690. _this._renderTargets.push(_this._reflectionTexture);
  43691. }
  43692. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  43693. _this._renderTargets.push(_this._refractionTexture);
  43694. }
  43695. return _this._renderTargets;
  43696. };
  43697. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  43698. return _this;
  43699. }
  43700. /**
  43701. * Attaches a new image processing configuration to the PBR Material.
  43702. * @param configuration
  43703. */
  43704. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  43705. var _this = this;
  43706. if (configuration === this._imageProcessingConfiguration) {
  43707. return;
  43708. }
  43709. // Detaches observer.
  43710. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43711. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43712. }
  43713. // Pick the scene configuration if needed.
  43714. if (!configuration) {
  43715. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  43716. }
  43717. else {
  43718. this._imageProcessingConfiguration = configuration;
  43719. }
  43720. // Attaches observer.
  43721. if (this._imageProcessingConfiguration) {
  43722. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  43723. _this._markAllSubMeshesAsImageProcessingDirty();
  43724. });
  43725. }
  43726. };
  43727. /**
  43728. * Gets the name of the material class.
  43729. */
  43730. PBRBaseMaterial.prototype.getClassName = function () {
  43731. return "PBRBaseMaterial";
  43732. };
  43733. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  43734. /**
  43735. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  43736. */
  43737. get: function () {
  43738. return this._useLogarithmicDepth;
  43739. },
  43740. /**
  43741. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  43742. */
  43743. set: function (value) {
  43744. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  43745. },
  43746. enumerable: true,
  43747. configurable: true
  43748. });
  43749. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  43750. /**
  43751. * Gets the current transparency mode.
  43752. */
  43753. get: function () {
  43754. return this._transparencyMode;
  43755. },
  43756. /**
  43757. * Sets the transparency mode of the material.
  43758. *
  43759. * | Value | Type | Description |
  43760. * | ----- | ----------------------------------- | ----------- |
  43761. * | 0 | OPAQUE | |
  43762. * | 1 | ALPHATEST | |
  43763. * | 2 | ALPHABLEND | |
  43764. * | 3 | ALPHATESTANDBLEND | |
  43765. *
  43766. */
  43767. set: function (value) {
  43768. if (this._transparencyMode === value) {
  43769. return;
  43770. }
  43771. this._transparencyMode = value;
  43772. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  43773. this._markAllSubMeshesAsTexturesAndMiscDirty();
  43774. },
  43775. enumerable: true,
  43776. configurable: true
  43777. });
  43778. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  43779. /**
  43780. * Returns true if alpha blending should be disabled.
  43781. */
  43782. get: function () {
  43783. return (this._linkRefractionWithTransparency ||
  43784. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  43785. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  43786. },
  43787. enumerable: true,
  43788. configurable: true
  43789. });
  43790. /**
  43791. * Specifies whether or not this material should be rendered in alpha blend mode.
  43792. */
  43793. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  43794. if (this._disableAlphaBlending) {
  43795. return false;
  43796. }
  43797. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  43798. };
  43799. /**
  43800. * Specifies if the mesh will require alpha blending.
  43801. * @param mesh - BJS mesh.
  43802. */
  43803. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  43804. if (this._disableAlphaBlending) {
  43805. return false;
  43806. }
  43807. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  43808. };
  43809. /**
  43810. * Specifies whether or not this material should be rendered in alpha test mode.
  43811. */
  43812. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  43813. if (this._forceAlphaTest) {
  43814. return true;
  43815. }
  43816. if (this._linkRefractionWithTransparency) {
  43817. return false;
  43818. }
  43819. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  43820. };
  43821. /**
  43822. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  43823. */
  43824. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  43825. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  43826. };
  43827. /**
  43828. * Gets the texture used for the alpha test.
  43829. */
  43830. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  43831. return this._albedoTexture;
  43832. };
  43833. /**
  43834. * Specifies that the submesh is ready to be used.
  43835. * @param mesh - BJS mesh.
  43836. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  43837. * @param useInstances - Specifies that instances should be used.
  43838. * @returns - boolean indicating that the submesh is ready or not.
  43839. */
  43840. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  43841. if (subMesh.effect && this.isFrozen) {
  43842. if (this._wasPreviouslyReady) {
  43843. return true;
  43844. }
  43845. }
  43846. if (!subMesh._materialDefines) {
  43847. subMesh._materialDefines = new PBRMaterialDefines();
  43848. }
  43849. var defines = subMesh._materialDefines;
  43850. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  43851. if (defines._renderId === this.getScene().getRenderId()) {
  43852. return true;
  43853. }
  43854. }
  43855. var scene = this.getScene();
  43856. var engine = scene.getEngine();
  43857. if (defines._areTexturesDirty) {
  43858. if (scene.texturesEnabled) {
  43859. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  43860. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  43861. return false;
  43862. }
  43863. }
  43864. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  43865. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  43866. return false;
  43867. }
  43868. }
  43869. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  43870. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  43871. return false;
  43872. }
  43873. }
  43874. var reflectionTexture = this._getReflectionTexture();
  43875. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43876. if (!reflectionTexture.isReadyOrNotBlocking()) {
  43877. return false;
  43878. }
  43879. }
  43880. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  43881. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  43882. return false;
  43883. }
  43884. }
  43885. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  43886. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  43887. return false;
  43888. }
  43889. }
  43890. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  43891. if (this._metallicTexture) {
  43892. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  43893. return false;
  43894. }
  43895. }
  43896. else if (this._reflectivityTexture) {
  43897. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  43898. return false;
  43899. }
  43900. }
  43901. if (this._microSurfaceTexture) {
  43902. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  43903. return false;
  43904. }
  43905. }
  43906. }
  43907. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  43908. // Bump texture cannot be not blocking.
  43909. if (!this._bumpTexture.isReady()) {
  43910. return false;
  43911. }
  43912. }
  43913. var refractionTexture = this._getRefractionTexture();
  43914. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  43915. if (!refractionTexture.isReadyOrNotBlocking()) {
  43916. return false;
  43917. }
  43918. }
  43919. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43920. // This is blocking.
  43921. if (!this._environmentBRDFTexture.isReady()) {
  43922. return false;
  43923. }
  43924. }
  43925. }
  43926. }
  43927. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  43928. if (!this._imageProcessingConfiguration.isReady()) {
  43929. return false;
  43930. }
  43931. }
  43932. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  43933. mesh.createNormals(true);
  43934. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  43935. }
  43936. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  43937. if (effect) {
  43938. scene.resetCachedMaterial();
  43939. subMesh.setEffect(effect, defines);
  43940. this.buildUniformLayout();
  43941. }
  43942. if (!subMesh.effect || !subMesh.effect.isReady()) {
  43943. return false;
  43944. }
  43945. defines._renderId = scene.getRenderId();
  43946. this._wasPreviouslyReady = true;
  43947. return true;
  43948. };
  43949. /**
  43950. * Specifies if the material uses metallic roughness workflow.
  43951. * @returns boolean specifiying if the material uses metallic roughness workflow.
  43952. */
  43953. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  43954. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  43955. return true;
  43956. }
  43957. return false;
  43958. };
  43959. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  43960. if (onCompiled === void 0) { onCompiled = null; }
  43961. if (onError === void 0) { onError = null; }
  43962. if (useInstances === void 0) { useInstances = null; }
  43963. if (useClipPlane === void 0) { useClipPlane = null; }
  43964. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  43965. if (!defines.isDirty) {
  43966. return null;
  43967. }
  43968. defines.markAsProcessed();
  43969. var scene = this.getScene();
  43970. var engine = scene.getEngine();
  43971. // Fallbacks
  43972. var fallbacks = new BABYLON.EffectFallbacks();
  43973. var fallbackRank = 0;
  43974. if (defines.USESPHERICALINVERTEX) {
  43975. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  43976. }
  43977. if (defines.FOG) {
  43978. fallbacks.addFallback(fallbackRank, "FOG");
  43979. }
  43980. if (defines.SPECULARAA) {
  43981. fallbacks.addFallback(fallbackRank, "SPECULARAA");
  43982. }
  43983. if (defines.POINTSIZE) {
  43984. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  43985. }
  43986. if (defines.LOGARITHMICDEPTH) {
  43987. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  43988. }
  43989. if (defines.PARALLAX) {
  43990. fallbacks.addFallback(fallbackRank, "PARALLAX");
  43991. }
  43992. if (defines.PARALLAXOCCLUSION) {
  43993. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  43994. }
  43995. if (defines.ENVIRONMENTBRDF) {
  43996. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  43997. }
  43998. if (defines.TANGENT) {
  43999. fallbacks.addFallback(fallbackRank++, "TANGENT");
  44000. }
  44001. if (defines.BUMP) {
  44002. fallbacks.addFallback(fallbackRank++, "BUMP");
  44003. }
  44004. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  44005. if (defines.SPECULARTERM) {
  44006. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  44007. }
  44008. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  44009. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  44010. }
  44011. if (defines.LIGHTMAP) {
  44012. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  44013. }
  44014. if (defines.NORMAL) {
  44015. fallbacks.addFallback(fallbackRank++, "NORMAL");
  44016. }
  44017. if (defines.AMBIENT) {
  44018. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  44019. }
  44020. if (defines.EMISSIVE) {
  44021. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  44022. }
  44023. if (defines.VERTEXCOLOR) {
  44024. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  44025. }
  44026. if (defines.NUM_BONE_INFLUENCERS > 0) {
  44027. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  44028. }
  44029. if (defines.MORPHTARGETS) {
  44030. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  44031. }
  44032. //Attributes
  44033. var attribs = [BABYLON.VertexBuffer.PositionKind];
  44034. if (defines.NORMAL) {
  44035. attribs.push(BABYLON.VertexBuffer.NormalKind);
  44036. }
  44037. if (defines.TANGENT) {
  44038. attribs.push(BABYLON.VertexBuffer.TangentKind);
  44039. }
  44040. if (defines.UV1) {
  44041. attribs.push(BABYLON.VertexBuffer.UVKind);
  44042. }
  44043. if (defines.UV2) {
  44044. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  44045. }
  44046. if (defines.VERTEXCOLOR) {
  44047. attribs.push(BABYLON.VertexBuffer.ColorKind);
  44048. }
  44049. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  44050. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  44051. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  44052. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  44053. "vFogInfos", "vFogColor", "pointSize",
  44054. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  44055. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  44056. "mBones",
  44057. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  44058. "vLightingIntensity",
  44059. "logarithmicDepthConstant",
  44060. "vSphericalX", "vSphericalY", "vSphericalZ",
  44061. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  44062. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  44063. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  44064. "vTangentSpaceParams"
  44065. ];
  44066. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  44067. "bumpSampler", "lightmapSampler", "opacitySampler",
  44068. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  44069. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  44070. "microSurfaceSampler", "environmentBrdfSampler"];
  44071. var uniformBuffers = ["Material", "Scene"];
  44072. if (BABYLON.ImageProcessingConfiguration) {
  44073. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  44074. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  44075. }
  44076. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  44077. uniformsNames: uniforms,
  44078. uniformBuffersNames: uniformBuffers,
  44079. samplers: samplers,
  44080. defines: defines,
  44081. maxSimultaneousLights: this._maxSimultaneousLights
  44082. });
  44083. var join = defines.toString();
  44084. return engine.createEffect("pbr", {
  44085. attributes: attribs,
  44086. uniformsNames: uniforms,
  44087. uniformBuffersNames: uniformBuffers,
  44088. samplers: samplers,
  44089. defines: join,
  44090. fallbacks: fallbacks,
  44091. onCompiled: onCompiled,
  44092. onError: onError,
  44093. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  44094. }, engine);
  44095. };
  44096. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  44097. if (useInstances === void 0) { useInstances = null; }
  44098. if (useClipPlane === void 0) { useClipPlane = null; }
  44099. var scene = this.getScene();
  44100. var engine = scene.getEngine();
  44101. // Lights
  44102. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  44103. defines._needNormals = true;
  44104. // Textures
  44105. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  44106. if (defines._areTexturesDirty) {
  44107. defines._needUVs = false;
  44108. if (scene.texturesEnabled) {
  44109. if (scene.getEngine().getCaps().textureLOD) {
  44110. defines.LODBASEDMICROSFURACE = true;
  44111. }
  44112. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44113. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  44114. }
  44115. else {
  44116. defines.ALBEDO = false;
  44117. }
  44118. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44119. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  44120. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  44121. }
  44122. else {
  44123. defines.AMBIENT = false;
  44124. }
  44125. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44126. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  44127. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  44128. }
  44129. else {
  44130. defines.OPACITY = false;
  44131. }
  44132. var reflectionTexture = this._getReflectionTexture();
  44133. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44134. defines.REFLECTION = true;
  44135. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  44136. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  44137. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  44138. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  44139. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  44140. defines.INVERTCUBICMAP = true;
  44141. }
  44142. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  44143. switch (reflectionTexture.coordinatesMode) {
  44144. case BABYLON.Texture.EXPLICIT_MODE:
  44145. defines.REFLECTIONMAP_EXPLICIT = true;
  44146. break;
  44147. case BABYLON.Texture.PLANAR_MODE:
  44148. defines.REFLECTIONMAP_PLANAR = true;
  44149. break;
  44150. case BABYLON.Texture.PROJECTION_MODE:
  44151. defines.REFLECTIONMAP_PROJECTION = true;
  44152. break;
  44153. case BABYLON.Texture.SKYBOX_MODE:
  44154. defines.REFLECTIONMAP_SKYBOX = true;
  44155. break;
  44156. case BABYLON.Texture.SPHERICAL_MODE:
  44157. defines.REFLECTIONMAP_SPHERICAL = true;
  44158. break;
  44159. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  44160. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  44161. break;
  44162. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  44163. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  44164. break;
  44165. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  44166. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  44167. break;
  44168. case BABYLON.Texture.CUBIC_MODE:
  44169. case BABYLON.Texture.INVCUBIC_MODE:
  44170. default:
  44171. defines.REFLECTIONMAP_CUBIC = true;
  44172. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  44173. break;
  44174. }
  44175. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  44176. if (reflectionTexture.sphericalPolynomial) {
  44177. defines.USESPHERICALFROMREFLECTIONMAP = true;
  44178. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  44179. defines.USESPHERICALINVERTEX = false;
  44180. }
  44181. else {
  44182. defines.USESPHERICALINVERTEX = true;
  44183. }
  44184. }
  44185. }
  44186. }
  44187. else {
  44188. defines.REFLECTION = false;
  44189. defines.REFLECTIONMAP_3D = false;
  44190. defines.REFLECTIONMAP_SPHERICAL = false;
  44191. defines.REFLECTIONMAP_PLANAR = false;
  44192. defines.REFLECTIONMAP_CUBIC = false;
  44193. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  44194. defines.REFLECTIONMAP_PROJECTION = false;
  44195. defines.REFLECTIONMAP_SKYBOX = false;
  44196. defines.REFLECTIONMAP_EXPLICIT = false;
  44197. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  44198. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  44199. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  44200. defines.INVERTCUBICMAP = false;
  44201. defines.USESPHERICALFROMREFLECTIONMAP = false;
  44202. defines.USESPHERICALINVERTEX = false;
  44203. defines.REFLECTIONMAP_OPPOSITEZ = false;
  44204. defines.LODINREFLECTIONALPHA = false;
  44205. defines.GAMMAREFLECTION = false;
  44206. defines.RGBDREFLECTION = false;
  44207. }
  44208. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44209. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  44210. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  44211. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  44212. }
  44213. else {
  44214. defines.LIGHTMAP = false;
  44215. }
  44216. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44217. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  44218. }
  44219. else {
  44220. defines.EMISSIVE = false;
  44221. }
  44222. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44223. if (this._metallicTexture) {
  44224. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  44225. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  44226. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  44227. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  44228. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  44229. }
  44230. else if (this._reflectivityTexture) {
  44231. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  44232. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  44233. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  44234. }
  44235. else {
  44236. defines.REFLECTIVITY = false;
  44237. }
  44238. if (this._microSurfaceTexture) {
  44239. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  44240. }
  44241. else {
  44242. defines.MICROSURFACEMAP = false;
  44243. }
  44244. }
  44245. else {
  44246. defines.REFLECTIVITY = false;
  44247. defines.MICROSURFACEMAP = false;
  44248. }
  44249. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44250. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  44251. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44252. defines.PARALLAX = true;
  44253. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  44254. }
  44255. else {
  44256. defines.PARALLAX = false;
  44257. }
  44258. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  44259. }
  44260. else {
  44261. defines.BUMP = false;
  44262. }
  44263. var refractionTexture = this._getRefractionTexture();
  44264. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44265. defines.REFRACTION = true;
  44266. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  44267. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  44268. defines.RGBDREFRACTION = refractionTexture.isRGBD;
  44269. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  44270. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  44271. if (this._linkRefractionWithTransparency) {
  44272. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  44273. }
  44274. }
  44275. else {
  44276. defines.REFRACTION = false;
  44277. }
  44278. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44279. defines.ENVIRONMENTBRDF = true;
  44280. }
  44281. else {
  44282. defines.ENVIRONMENTBRDF = false;
  44283. }
  44284. if (this._shouldUseAlphaFromAlbedoTexture()) {
  44285. defines.ALPHAFROMALBEDO = true;
  44286. }
  44287. else {
  44288. defines.ALPHAFROMALBEDO = false;
  44289. }
  44290. }
  44291. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  44292. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  44293. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  44294. if (!this.backFaceCulling && this._twoSidedLighting) {
  44295. defines.TWOSIDEDLIGHTING = true;
  44296. }
  44297. else {
  44298. defines.TWOSIDEDLIGHTING = false;
  44299. }
  44300. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  44301. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  44302. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  44303. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  44304. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  44305. defines.SPECULARAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  44306. }
  44307. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  44308. this._imageProcessingConfiguration.prepareDefines(defines);
  44309. }
  44310. defines.FORCENORMALFORWARD = this._forceNormalForward;
  44311. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  44312. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  44313. // Misc.
  44314. if (defines._areMiscDirty) {
  44315. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  44316. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  44317. }
  44318. // Values that need to be evaluated on every frame
  44319. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  44320. // Attribs
  44321. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  44322. };
  44323. /**
  44324. * Force shader compilation
  44325. */
  44326. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  44327. var _this = this;
  44328. var localOptions = __assign({ clipPlane: false }, options);
  44329. var defines = new PBRMaterialDefines();
  44330. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  44331. if (effect.isReady()) {
  44332. if (onCompiled) {
  44333. onCompiled(this);
  44334. }
  44335. }
  44336. else {
  44337. effect.onCompileObservable.add(function () {
  44338. if (onCompiled) {
  44339. onCompiled(_this);
  44340. }
  44341. });
  44342. }
  44343. };
  44344. /**
  44345. * Initializes the uniform buffer layout for the shader.
  44346. */
  44347. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  44348. // Order is important !
  44349. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  44350. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  44351. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  44352. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  44353. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  44354. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  44355. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  44356. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  44357. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  44358. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  44359. this._uniformBuffer.addUniform("vReflectionSize", 3);
  44360. this._uniformBuffer.addUniform("vBumpInfos", 3);
  44361. this._uniformBuffer.addUniform("albedoMatrix", 16);
  44362. this._uniformBuffer.addUniform("ambientMatrix", 16);
  44363. this._uniformBuffer.addUniform("opacityMatrix", 16);
  44364. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  44365. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  44366. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  44367. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  44368. this._uniformBuffer.addUniform("bumpMatrix", 16);
  44369. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  44370. this._uniformBuffer.addUniform("refractionMatrix", 16);
  44371. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  44372. this._uniformBuffer.addUniform("vReflectionColor", 3);
  44373. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  44374. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  44375. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  44376. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  44377. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  44378. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  44379. this._uniformBuffer.addUniform("pointSize", 1);
  44380. this._uniformBuffer.create();
  44381. };
  44382. /**
  44383. * Unbinds the textures.
  44384. */
  44385. PBRBaseMaterial.prototype.unbind = function () {
  44386. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  44387. this._uniformBuffer.setTexture("reflectionSampler", null);
  44388. }
  44389. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  44390. this._uniformBuffer.setTexture("refractionSampler", null);
  44391. }
  44392. _super.prototype.unbind.call(this);
  44393. };
  44394. /**
  44395. * Binds the submesh data.
  44396. * @param world - The world matrix.
  44397. * @param mesh - The BJS mesh.
  44398. * @param subMesh - A submesh of the BJS mesh.
  44399. */
  44400. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  44401. var scene = this.getScene();
  44402. var defines = subMesh._materialDefines;
  44403. if (!defines) {
  44404. return;
  44405. }
  44406. var effect = subMesh.effect;
  44407. if (!effect) {
  44408. return;
  44409. }
  44410. this._activeEffect = effect;
  44411. // Matrices
  44412. this.bindOnlyWorldMatrix(world);
  44413. // Normal Matrix
  44414. if (defines.OBJECTSPACE_NORMALMAP) {
  44415. world.toNormalMatrix(this._normalMatrix);
  44416. this.bindOnlyNormalMatrix(this._normalMatrix);
  44417. }
  44418. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  44419. // Bones
  44420. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  44421. var reflectionTexture = null;
  44422. if (mustRebind) {
  44423. this._uniformBuffer.bindToEffect(effect, "Material");
  44424. this.bindViewProjection(effect);
  44425. reflectionTexture = this._getReflectionTexture();
  44426. var refractionTexture = this._getRefractionTexture();
  44427. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  44428. // Texture uniforms
  44429. if (scene.texturesEnabled) {
  44430. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44431. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  44432. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  44433. }
  44434. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44435. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  44436. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  44437. }
  44438. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44439. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  44440. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  44441. }
  44442. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44443. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  44444. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  44445. if (reflectionTexture.boundingBoxSize) {
  44446. var cubeTexture = reflectionTexture;
  44447. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  44448. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  44449. }
  44450. var polynomials = reflectionTexture.sphericalPolynomial;
  44451. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  44452. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  44453. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  44454. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  44455. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  44456. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  44457. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  44458. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  44459. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  44460. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  44461. }
  44462. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  44463. }
  44464. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44465. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  44466. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  44467. }
  44468. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44469. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  44470. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  44471. }
  44472. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44473. if (this._metallicTexture) {
  44474. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  44475. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  44476. }
  44477. else if (this._reflectivityTexture) {
  44478. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  44479. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  44480. }
  44481. if (this._microSurfaceTexture) {
  44482. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  44483. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  44484. }
  44485. }
  44486. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44487. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  44488. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  44489. if (scene._mirroredCameraPosition) {
  44490. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  44491. }
  44492. else {
  44493. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  44494. }
  44495. }
  44496. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44497. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  44498. var depth = 1.0;
  44499. if (!refractionTexture.isCube) {
  44500. if (refractionTexture.depth) {
  44501. depth = refractionTexture.depth;
  44502. }
  44503. }
  44504. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  44505. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  44506. }
  44507. }
  44508. // Point size
  44509. if (this.pointsCloud) {
  44510. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  44511. }
  44512. // Colors
  44513. if (defines.METALLICWORKFLOW) {
  44514. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  44515. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  44516. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  44517. }
  44518. else {
  44519. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  44520. }
  44521. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  44522. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  44523. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  44524. // Misc
  44525. this._lightingInfos.x = this._directIntensity;
  44526. this._lightingInfos.y = this._emissiveIntensity;
  44527. this._lightingInfos.z = this._environmentIntensity;
  44528. this._lightingInfos.w = this._specularIntensity;
  44529. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  44530. }
  44531. // Textures
  44532. if (scene.texturesEnabled) {
  44533. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44534. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  44535. }
  44536. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44537. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  44538. }
  44539. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44540. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  44541. }
  44542. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44543. if (defines.LODBASEDMICROSFURACE) {
  44544. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  44545. }
  44546. else {
  44547. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  44548. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  44549. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  44550. }
  44551. }
  44552. if (defines.ENVIRONMENTBRDF) {
  44553. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  44554. }
  44555. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44556. if (defines.LODBASEDMICROSFURACE) {
  44557. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  44558. }
  44559. else {
  44560. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  44561. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  44562. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  44563. }
  44564. }
  44565. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44566. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  44567. }
  44568. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44569. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  44570. }
  44571. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44572. if (this._metallicTexture) {
  44573. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  44574. }
  44575. else if (this._reflectivityTexture) {
  44576. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  44577. }
  44578. if (this._microSurfaceTexture) {
  44579. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  44580. }
  44581. }
  44582. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44583. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  44584. }
  44585. }
  44586. // Clip plane
  44587. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  44588. // Colors
  44589. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  44590. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  44591. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  44592. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  44593. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  44594. }
  44595. if (mustRebind || !this.isFrozen) {
  44596. // Lights
  44597. if (scene.lightsEnabled && !this._disableLighting) {
  44598. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  44599. }
  44600. // View
  44601. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  44602. this.bindView(effect);
  44603. }
  44604. // Fog
  44605. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  44606. // Morph targets
  44607. if (defines.NUM_MORPH_INFLUENCERS) {
  44608. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  44609. }
  44610. // image processing
  44611. this._imageProcessingConfiguration.bind(this._activeEffect);
  44612. // Log. depth
  44613. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  44614. }
  44615. this._uniformBuffer.update();
  44616. this._afterBind(mesh, this._activeEffect);
  44617. };
  44618. /**
  44619. * Returns the animatable textures.
  44620. * @returns - Array of animatable textures.
  44621. */
  44622. PBRBaseMaterial.prototype.getAnimatables = function () {
  44623. var results = [];
  44624. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  44625. results.push(this._albedoTexture);
  44626. }
  44627. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  44628. results.push(this._ambientTexture);
  44629. }
  44630. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  44631. results.push(this._opacityTexture);
  44632. }
  44633. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  44634. results.push(this._reflectionTexture);
  44635. }
  44636. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  44637. results.push(this._emissiveTexture);
  44638. }
  44639. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  44640. results.push(this._metallicTexture);
  44641. }
  44642. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  44643. results.push(this._reflectivityTexture);
  44644. }
  44645. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  44646. results.push(this._bumpTexture);
  44647. }
  44648. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  44649. results.push(this._lightmapTexture);
  44650. }
  44651. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  44652. results.push(this._refractionTexture);
  44653. }
  44654. return results;
  44655. };
  44656. /**
  44657. * Returns the texture used for reflections.
  44658. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  44659. */
  44660. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  44661. if (this._reflectionTexture) {
  44662. return this._reflectionTexture;
  44663. }
  44664. return this.getScene().environmentTexture;
  44665. };
  44666. /**
  44667. * Returns the texture used for refraction or null if none is used.
  44668. * @returns - Refection texture if present. If no refraction texture and refraction
  44669. * is linked with transparency, returns environment texture. Otherwise, returns null.
  44670. */
  44671. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  44672. if (this._refractionTexture) {
  44673. return this._refractionTexture;
  44674. }
  44675. if (this._linkRefractionWithTransparency) {
  44676. return this.getScene().environmentTexture;
  44677. }
  44678. return null;
  44679. };
  44680. /**
  44681. * Disposes the resources of the material.
  44682. * @param forceDisposeEffect - Forces the disposal of effects.
  44683. * @param forceDisposeTextures - Forces the disposal of all textures.
  44684. */
  44685. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  44686. if (forceDisposeTextures) {
  44687. if (this._albedoTexture) {
  44688. this._albedoTexture.dispose();
  44689. }
  44690. if (this._ambientTexture) {
  44691. this._ambientTexture.dispose();
  44692. }
  44693. if (this._opacityTexture) {
  44694. this._opacityTexture.dispose();
  44695. }
  44696. if (this._reflectionTexture) {
  44697. this._reflectionTexture.dispose();
  44698. }
  44699. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  44700. this._environmentBRDFTexture.dispose();
  44701. }
  44702. if (this._emissiveTexture) {
  44703. this._emissiveTexture.dispose();
  44704. }
  44705. if (this._metallicTexture) {
  44706. this._metallicTexture.dispose();
  44707. }
  44708. if (this._reflectivityTexture) {
  44709. this._reflectivityTexture.dispose();
  44710. }
  44711. if (this._bumpTexture) {
  44712. this._bumpTexture.dispose();
  44713. }
  44714. if (this._lightmapTexture) {
  44715. this._lightmapTexture.dispose();
  44716. }
  44717. if (this._refractionTexture) {
  44718. this._refractionTexture.dispose();
  44719. }
  44720. }
  44721. this._renderTargets.dispose();
  44722. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44723. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44724. }
  44725. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  44726. };
  44727. /**
  44728. * Stores the reflectivity values based on metallic roughness workflow.
  44729. */
  44730. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  44731. __decorate([
  44732. BABYLON.serializeAsImageProcessingConfiguration()
  44733. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  44734. __decorate([
  44735. BABYLON.serialize()
  44736. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  44737. __decorate([
  44738. BABYLON.serialize()
  44739. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  44740. return PBRBaseMaterial;
  44741. }(BABYLON.PushMaterial));
  44742. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  44743. })(BABYLON || (BABYLON = {}));
  44744. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  44745. var BABYLON;
  44746. (function (BABYLON) {
  44747. /**
  44748. * The Physically based simple base material of BJS.
  44749. *
  44750. * This enables better naming and convention enforcements on top of the pbrMaterial.
  44751. * It is used as the base class for both the specGloss and metalRough conventions.
  44752. */
  44753. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  44754. __extends(PBRBaseSimpleMaterial, _super);
  44755. /**
  44756. * Instantiates a new PBRMaterial instance.
  44757. *
  44758. * @param name The material name
  44759. * @param scene The scene the material will be use in.
  44760. */
  44761. function PBRBaseSimpleMaterial(name, scene) {
  44762. var _this = _super.call(this, name, scene) || this;
  44763. /**
  44764. * Number of Simultaneous lights allowed on the material.
  44765. */
  44766. _this.maxSimultaneousLights = 4;
  44767. /**
  44768. * If sets to true, disables all the lights affecting the material.
  44769. */
  44770. _this.disableLighting = false;
  44771. /**
  44772. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  44773. */
  44774. _this.invertNormalMapX = false;
  44775. /**
  44776. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  44777. */
  44778. _this.invertNormalMapY = false;
  44779. /**
  44780. * Emissivie color used to self-illuminate the model.
  44781. */
  44782. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  44783. /**
  44784. * Occlusion Channel Strenght.
  44785. */
  44786. _this.occlusionStrength = 1.0;
  44787. _this.useLightmapAsShadowmap = false;
  44788. _this._useAlphaFromAlbedoTexture = true;
  44789. _this._useAmbientInGrayScale = true;
  44790. return _this;
  44791. }
  44792. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  44793. /**
  44794. * Gets the current double sided mode.
  44795. */
  44796. get: function () {
  44797. return this._twoSidedLighting;
  44798. },
  44799. /**
  44800. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44801. */
  44802. set: function (value) {
  44803. if (this._twoSidedLighting === value) {
  44804. return;
  44805. }
  44806. this._twoSidedLighting = value;
  44807. this.backFaceCulling = !value;
  44808. this._markAllSubMeshesAsTexturesDirty();
  44809. },
  44810. enumerable: true,
  44811. configurable: true
  44812. });
  44813. /**
  44814. * Return the active textures of the material.
  44815. */
  44816. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  44817. var activeTextures = _super.prototype.getActiveTextures.call(this);
  44818. if (this.environmentTexture) {
  44819. activeTextures.push(this.environmentTexture);
  44820. }
  44821. if (this.normalTexture) {
  44822. activeTextures.push(this.normalTexture);
  44823. }
  44824. if (this.emissiveTexture) {
  44825. activeTextures.push(this.emissiveTexture);
  44826. }
  44827. if (this.occlusionTexture) {
  44828. activeTextures.push(this.occlusionTexture);
  44829. }
  44830. if (this.lightmapTexture) {
  44831. activeTextures.push(this.lightmapTexture);
  44832. }
  44833. return activeTextures;
  44834. };
  44835. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  44836. if (_super.prototype.hasTexture.call(this, texture)) {
  44837. return true;
  44838. }
  44839. if (this.lightmapTexture === texture) {
  44840. return true;
  44841. }
  44842. return false;
  44843. };
  44844. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  44845. return "PBRBaseSimpleMaterial";
  44846. };
  44847. __decorate([
  44848. BABYLON.serialize(),
  44849. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44850. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  44851. __decorate([
  44852. BABYLON.serialize(),
  44853. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44854. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  44855. __decorate([
  44856. BABYLON.serializeAsTexture(),
  44857. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  44858. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  44859. __decorate([
  44860. BABYLON.serialize(),
  44861. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44862. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  44863. __decorate([
  44864. BABYLON.serialize(),
  44865. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44866. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  44867. __decorate([
  44868. BABYLON.serializeAsTexture(),
  44869. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  44870. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  44871. __decorate([
  44872. BABYLON.serializeAsColor3("emissive"),
  44873. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44874. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  44875. __decorate([
  44876. BABYLON.serializeAsTexture(),
  44877. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44878. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  44879. __decorate([
  44880. BABYLON.serialize(),
  44881. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  44882. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  44883. __decorate([
  44884. BABYLON.serializeAsTexture(),
  44885. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  44886. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  44887. __decorate([
  44888. BABYLON.serialize(),
  44889. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  44890. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  44891. __decorate([
  44892. BABYLON.serialize()
  44893. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  44894. __decorate([
  44895. BABYLON.serializeAsTexture(),
  44896. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  44897. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  44898. __decorate([
  44899. BABYLON.serialize(),
  44900. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44901. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  44902. return PBRBaseSimpleMaterial;
  44903. }(BABYLON.PBRBaseMaterial));
  44904. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  44905. })(BABYLON || (BABYLON = {}));
  44906. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  44907. var BABYLON;
  44908. (function (BABYLON) {
  44909. /**
  44910. * The Physically based material of BJS.
  44911. *
  44912. * This offers the main features of a standard PBR material.
  44913. * For more information, please refer to the documentation :
  44914. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  44915. */
  44916. var PBRMaterial = /** @class */ (function (_super) {
  44917. __extends(PBRMaterial, _super);
  44918. /**
  44919. * Instantiates a new PBRMaterial instance.
  44920. *
  44921. * @param name The material name
  44922. * @param scene The scene the material will be use in.
  44923. */
  44924. function PBRMaterial(name, scene) {
  44925. var _this = _super.call(this, name, scene) || this;
  44926. /**
  44927. * Intensity of the direct lights e.g. the four lights available in your scene.
  44928. * This impacts both the direct diffuse and specular highlights.
  44929. */
  44930. _this.directIntensity = 1.0;
  44931. /**
  44932. * Intensity of the emissive part of the material.
  44933. * This helps controlling the emissive effect without modifying the emissive color.
  44934. */
  44935. _this.emissiveIntensity = 1.0;
  44936. /**
  44937. * Intensity of the environment e.g. how much the environment will light the object
  44938. * either through harmonics for rough material or through the refelction for shiny ones.
  44939. */
  44940. _this.environmentIntensity = 1.0;
  44941. /**
  44942. * This is a special control allowing the reduction of the specular highlights coming from the
  44943. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  44944. */
  44945. _this.specularIntensity = 1.0;
  44946. /**
  44947. * Debug Control allowing disabling the bump map on this material.
  44948. */
  44949. _this.disableBumpMap = false;
  44950. /**
  44951. * AKA Occlusion Texture Intensity in other nomenclature.
  44952. */
  44953. _this.ambientTextureStrength = 1.0;
  44954. /**
  44955. * The color of a material in ambient lighting.
  44956. */
  44957. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  44958. /**
  44959. * AKA Diffuse Color in other nomenclature.
  44960. */
  44961. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  44962. /**
  44963. * AKA Specular Color in other nomenclature.
  44964. */
  44965. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  44966. /**
  44967. * The color reflected from the material.
  44968. */
  44969. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  44970. /**
  44971. * The color emitted from the material.
  44972. */
  44973. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  44974. /**
  44975. * AKA Glossiness in other nomenclature.
  44976. */
  44977. _this.microSurface = 1.0;
  44978. /**
  44979. * source material index of refraction (IOR)' / 'destination material IOR.
  44980. */
  44981. _this.indexOfRefraction = 0.66;
  44982. /**
  44983. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  44984. */
  44985. _this.invertRefractionY = false;
  44986. /**
  44987. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  44988. * Materials half opaque for instance using refraction could benefit from this control.
  44989. */
  44990. _this.linkRefractionWithTransparency = false;
  44991. _this.useLightmapAsShadowmap = false;
  44992. /**
  44993. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  44994. */
  44995. _this.useAlphaFromAlbedoTexture = false;
  44996. /**
  44997. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  44998. */
  44999. _this.forceAlphaTest = false;
  45000. /**
  45001. * Defines the alpha limits in alpha test mode.
  45002. */
  45003. _this.alphaCutOff = 0.4;
  45004. /**
  45005. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  45006. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  45007. */
  45008. _this.useSpecularOverAlpha = true;
  45009. /**
  45010. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  45011. */
  45012. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  45013. /**
  45014. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  45015. */
  45016. _this.useRoughnessFromMetallicTextureAlpha = true;
  45017. /**
  45018. * Specifies if the metallic texture contains the roughness information in its green channel.
  45019. */
  45020. _this.useRoughnessFromMetallicTextureGreen = false;
  45021. /**
  45022. * Specifies if the metallic texture contains the metallness information in its blue channel.
  45023. */
  45024. _this.useMetallnessFromMetallicTextureBlue = false;
  45025. /**
  45026. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  45027. */
  45028. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  45029. /**
  45030. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  45031. */
  45032. _this.useAmbientInGrayScale = false;
  45033. /**
  45034. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  45035. * The material will try to infer what glossiness each pixel should be.
  45036. */
  45037. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  45038. /**
  45039. * BJS is using an harcoded light falloff based on a manually sets up range.
  45040. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  45041. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  45042. */
  45043. _this.usePhysicalLightFalloff = true;
  45044. /**
  45045. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  45046. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  45047. */
  45048. _this.useRadianceOverAlpha = true;
  45049. /**
  45050. * Allows using an object space normal map (instead of tangent space).
  45051. */
  45052. _this.useObjectSpaceNormalMap = false;
  45053. /**
  45054. * Allows using the bump map in parallax mode.
  45055. */
  45056. _this.useParallax = false;
  45057. /**
  45058. * Allows using the bump map in parallax occlusion mode.
  45059. */
  45060. _this.useParallaxOcclusion = false;
  45061. /**
  45062. * Controls the scale bias of the parallax mode.
  45063. */
  45064. _this.parallaxScaleBias = 0.05;
  45065. /**
  45066. * If sets to true, disables all the lights affecting the material.
  45067. */
  45068. _this.disableLighting = false;
  45069. /**
  45070. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  45071. */
  45072. _this.forceIrradianceInFragment = false;
  45073. /**
  45074. * Number of Simultaneous lights allowed on the material.
  45075. */
  45076. _this.maxSimultaneousLights = 4;
  45077. /**
  45078. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  45079. */
  45080. _this.invertNormalMapX = false;
  45081. /**
  45082. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  45083. */
  45084. _this.invertNormalMapY = false;
  45085. /**
  45086. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45087. */
  45088. _this.twoSidedLighting = false;
  45089. /**
  45090. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45091. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  45092. */
  45093. _this.useAlphaFresnel = false;
  45094. /**
  45095. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45096. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  45097. */
  45098. _this.useLinearAlphaFresnel = false;
  45099. /**
  45100. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45101. * And/Or occlude the blended part.
  45102. */
  45103. _this.environmentBRDFTexture = null;
  45104. /**
  45105. * Force normal to face away from face.
  45106. */
  45107. _this.forceNormalForward = false;
  45108. /**
  45109. * Enables specular anti aliasing in the PBR shader.
  45110. * It will both interacts on the Geometry for analytical and IBL lighting.
  45111. * It also prefilter the roughness map based on the bump values.
  45112. */
  45113. _this.enableSpecularAntiAliasing = false;
  45114. /**
  45115. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  45116. * makes the reflect vector face the model (under horizon).
  45117. */
  45118. _this.useHorizonOcclusion = true;
  45119. /**
  45120. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  45121. * too much the area relying on ambient texture to define their ambient occlusion.
  45122. */
  45123. _this.useRadianceOcclusion = true;
  45124. /**
  45125. * If set to true, no lighting calculations will be applied.
  45126. */
  45127. _this.unlit = false;
  45128. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  45129. return _this;
  45130. }
  45131. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  45132. /**
  45133. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  45134. */
  45135. get: function () {
  45136. return this._PBRMATERIAL_OPAQUE;
  45137. },
  45138. enumerable: true,
  45139. configurable: true
  45140. });
  45141. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  45142. /**
  45143. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  45144. */
  45145. get: function () {
  45146. return this._PBRMATERIAL_ALPHATEST;
  45147. },
  45148. enumerable: true,
  45149. configurable: true
  45150. });
  45151. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  45152. /**
  45153. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45154. */
  45155. get: function () {
  45156. return this._PBRMATERIAL_ALPHABLEND;
  45157. },
  45158. enumerable: true,
  45159. configurable: true
  45160. });
  45161. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  45162. /**
  45163. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45164. * They are also discarded below the alpha cutoff threshold to improve performances.
  45165. */
  45166. get: function () {
  45167. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  45168. },
  45169. enumerable: true,
  45170. configurable: true
  45171. });
  45172. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  45173. /**
  45174. * Gets the image processing configuration used either in this material.
  45175. */
  45176. get: function () {
  45177. return this._imageProcessingConfiguration;
  45178. },
  45179. /**
  45180. * Sets the Default image processing configuration used either in the this material.
  45181. *
  45182. * If sets to null, the scene one is in use.
  45183. */
  45184. set: function (value) {
  45185. this._attachImageProcessingConfiguration(value);
  45186. // Ensure the effect will be rebuilt.
  45187. this._markAllSubMeshesAsTexturesDirty();
  45188. },
  45189. enumerable: true,
  45190. configurable: true
  45191. });
  45192. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  45193. /**
  45194. * Gets wether the color curves effect is enabled.
  45195. */
  45196. get: function () {
  45197. return this.imageProcessingConfiguration.colorCurvesEnabled;
  45198. },
  45199. /**
  45200. * Sets wether the color curves effect is enabled.
  45201. */
  45202. set: function (value) {
  45203. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  45204. },
  45205. enumerable: true,
  45206. configurable: true
  45207. });
  45208. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  45209. /**
  45210. * Gets wether the color grading effect is enabled.
  45211. */
  45212. get: function () {
  45213. return this.imageProcessingConfiguration.colorGradingEnabled;
  45214. },
  45215. /**
  45216. * Gets wether the color grading effect is enabled.
  45217. */
  45218. set: function (value) {
  45219. this.imageProcessingConfiguration.colorGradingEnabled = value;
  45220. },
  45221. enumerable: true,
  45222. configurable: true
  45223. });
  45224. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  45225. /**
  45226. * Gets wether tonemapping is enabled or not.
  45227. */
  45228. get: function () {
  45229. return this._imageProcessingConfiguration.toneMappingEnabled;
  45230. },
  45231. /**
  45232. * Sets wether tonemapping is enabled or not
  45233. */
  45234. set: function (value) {
  45235. this._imageProcessingConfiguration.toneMappingEnabled = value;
  45236. },
  45237. enumerable: true,
  45238. configurable: true
  45239. });
  45240. ;
  45241. ;
  45242. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  45243. /**
  45244. * The camera exposure used on this material.
  45245. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45246. * This corresponds to a photographic exposure.
  45247. */
  45248. get: function () {
  45249. return this._imageProcessingConfiguration.exposure;
  45250. },
  45251. /**
  45252. * The camera exposure used on this material.
  45253. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45254. * This corresponds to a photographic exposure.
  45255. */
  45256. set: function (value) {
  45257. this._imageProcessingConfiguration.exposure = value;
  45258. },
  45259. enumerable: true,
  45260. configurable: true
  45261. });
  45262. ;
  45263. ;
  45264. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  45265. /**
  45266. * Gets The camera contrast used on this material.
  45267. */
  45268. get: function () {
  45269. return this._imageProcessingConfiguration.contrast;
  45270. },
  45271. /**
  45272. * Sets The camera contrast used on this material.
  45273. */
  45274. set: function (value) {
  45275. this._imageProcessingConfiguration.contrast = value;
  45276. },
  45277. enumerable: true,
  45278. configurable: true
  45279. });
  45280. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  45281. /**
  45282. * Gets the Color Grading 2D Lookup Texture.
  45283. */
  45284. get: function () {
  45285. return this._imageProcessingConfiguration.colorGradingTexture;
  45286. },
  45287. /**
  45288. * Sets the Color Grading 2D Lookup Texture.
  45289. */
  45290. set: function (value) {
  45291. this._imageProcessingConfiguration.colorGradingTexture = value;
  45292. },
  45293. enumerable: true,
  45294. configurable: true
  45295. });
  45296. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  45297. /**
  45298. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45299. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45300. * 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;
  45301. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45302. */
  45303. get: function () {
  45304. return this._imageProcessingConfiguration.colorCurves;
  45305. },
  45306. /**
  45307. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45308. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45309. * 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;
  45310. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45311. */
  45312. set: function (value) {
  45313. this._imageProcessingConfiguration.colorCurves = value;
  45314. },
  45315. enumerable: true,
  45316. configurable: true
  45317. });
  45318. /**
  45319. * Returns the name of this material class.
  45320. */
  45321. PBRMaterial.prototype.getClassName = function () {
  45322. return "PBRMaterial";
  45323. };
  45324. /**
  45325. * Returns an array of the actively used textures.
  45326. * @returns - Array of BaseTextures
  45327. */
  45328. PBRMaterial.prototype.getActiveTextures = function () {
  45329. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45330. if (this._albedoTexture) {
  45331. activeTextures.push(this._albedoTexture);
  45332. }
  45333. if (this._ambientTexture) {
  45334. activeTextures.push(this._ambientTexture);
  45335. }
  45336. if (this._opacityTexture) {
  45337. activeTextures.push(this._opacityTexture);
  45338. }
  45339. if (this._reflectionTexture) {
  45340. activeTextures.push(this._reflectionTexture);
  45341. }
  45342. if (this._emissiveTexture) {
  45343. activeTextures.push(this._emissiveTexture);
  45344. }
  45345. if (this._reflectivityTexture) {
  45346. activeTextures.push(this._reflectivityTexture);
  45347. }
  45348. if (this._metallicTexture) {
  45349. activeTextures.push(this._metallicTexture);
  45350. }
  45351. if (this._microSurfaceTexture) {
  45352. activeTextures.push(this._microSurfaceTexture);
  45353. }
  45354. if (this._bumpTexture) {
  45355. activeTextures.push(this._bumpTexture);
  45356. }
  45357. if (this._lightmapTexture) {
  45358. activeTextures.push(this._lightmapTexture);
  45359. }
  45360. if (this._refractionTexture) {
  45361. activeTextures.push(this._refractionTexture);
  45362. }
  45363. return activeTextures;
  45364. };
  45365. /**
  45366. * Checks to see if a texture is used in the material.
  45367. * @param texture - Base texture to use.
  45368. * @returns - Boolean specifying if a texture is used in the material.
  45369. */
  45370. PBRMaterial.prototype.hasTexture = function (texture) {
  45371. if (_super.prototype.hasTexture.call(this, texture)) {
  45372. return true;
  45373. }
  45374. if (this._albedoTexture === texture) {
  45375. return true;
  45376. }
  45377. if (this._ambientTexture === texture) {
  45378. return true;
  45379. }
  45380. if (this._opacityTexture === texture) {
  45381. return true;
  45382. }
  45383. if (this._reflectionTexture === texture) {
  45384. return true;
  45385. }
  45386. if (this._reflectivityTexture === texture) {
  45387. return true;
  45388. }
  45389. if (this._metallicTexture === texture) {
  45390. return true;
  45391. }
  45392. if (this._microSurfaceTexture === texture) {
  45393. return true;
  45394. }
  45395. if (this._bumpTexture === texture) {
  45396. return true;
  45397. }
  45398. if (this._lightmapTexture === texture) {
  45399. return true;
  45400. }
  45401. if (this._refractionTexture === texture) {
  45402. return true;
  45403. }
  45404. return false;
  45405. };
  45406. /**
  45407. * Makes a duplicate of the current material.
  45408. * @param name - name to use for the new material.
  45409. */
  45410. PBRMaterial.prototype.clone = function (name) {
  45411. var _this = this;
  45412. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  45413. clone.id = name;
  45414. clone.name = name;
  45415. return clone;
  45416. };
  45417. /**
  45418. * Serializes this PBR Material.
  45419. * @returns - An object with the serialized material.
  45420. */
  45421. PBRMaterial.prototype.serialize = function () {
  45422. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45423. serializationObject.customType = "BABYLON.PBRMaterial";
  45424. return serializationObject;
  45425. };
  45426. // Statics
  45427. /**
  45428. * Parses a PBR Material from a serialized object.
  45429. * @param source - Serialized object.
  45430. * @param scene - BJS scene instance.
  45431. * @param rootUrl - url for the scene object
  45432. * @returns - PBRMaterial
  45433. */
  45434. PBRMaterial.Parse = function (source, scene, rootUrl) {
  45435. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  45436. };
  45437. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  45438. /**
  45439. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  45440. */
  45441. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  45442. /**
  45443. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45444. */
  45445. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  45446. /**
  45447. * 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.
  45448. * They are also discarded below the alpha cutoff threshold to improve performances.
  45449. */
  45450. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  45451. __decorate([
  45452. BABYLON.serialize(),
  45453. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45454. ], PBRMaterial.prototype, "directIntensity", void 0);
  45455. __decorate([
  45456. BABYLON.serialize(),
  45457. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45458. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  45459. __decorate([
  45460. BABYLON.serialize(),
  45461. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45462. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  45463. __decorate([
  45464. BABYLON.serialize(),
  45465. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45466. ], PBRMaterial.prototype, "specularIntensity", void 0);
  45467. __decorate([
  45468. BABYLON.serialize(),
  45469. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45470. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  45471. __decorate([
  45472. BABYLON.serializeAsTexture(),
  45473. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45474. ], PBRMaterial.prototype, "albedoTexture", void 0);
  45475. __decorate([
  45476. BABYLON.serializeAsTexture(),
  45477. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45478. ], PBRMaterial.prototype, "ambientTexture", void 0);
  45479. __decorate([
  45480. BABYLON.serialize(),
  45481. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45482. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  45483. __decorate([
  45484. BABYLON.serializeAsTexture(),
  45485. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45486. ], PBRMaterial.prototype, "opacityTexture", void 0);
  45487. __decorate([
  45488. BABYLON.serializeAsTexture(),
  45489. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45490. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  45491. __decorate([
  45492. BABYLON.serializeAsTexture(),
  45493. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45494. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  45495. __decorate([
  45496. BABYLON.serializeAsTexture(),
  45497. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45498. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  45499. __decorate([
  45500. BABYLON.serializeAsTexture(),
  45501. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45502. ], PBRMaterial.prototype, "metallicTexture", void 0);
  45503. __decorate([
  45504. BABYLON.serialize(),
  45505. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45506. ], PBRMaterial.prototype, "metallic", void 0);
  45507. __decorate([
  45508. BABYLON.serialize(),
  45509. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45510. ], PBRMaterial.prototype, "roughness", void 0);
  45511. __decorate([
  45512. BABYLON.serializeAsTexture(),
  45513. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45514. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  45515. __decorate([
  45516. BABYLON.serializeAsTexture(),
  45517. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45518. ], PBRMaterial.prototype, "bumpTexture", void 0);
  45519. __decorate([
  45520. BABYLON.serializeAsTexture(),
  45521. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  45522. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  45523. __decorate([
  45524. BABYLON.serializeAsTexture(),
  45525. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45526. ], PBRMaterial.prototype, "refractionTexture", void 0);
  45527. __decorate([
  45528. BABYLON.serializeAsColor3("ambient"),
  45529. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45530. ], PBRMaterial.prototype, "ambientColor", void 0);
  45531. __decorate([
  45532. BABYLON.serializeAsColor3("albedo"),
  45533. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45534. ], PBRMaterial.prototype, "albedoColor", void 0);
  45535. __decorate([
  45536. BABYLON.serializeAsColor3("reflectivity"),
  45537. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45538. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  45539. __decorate([
  45540. BABYLON.serializeAsColor3("reflection"),
  45541. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45542. ], PBRMaterial.prototype, "reflectionColor", void 0);
  45543. __decorate([
  45544. BABYLON.serializeAsColor3("emissive"),
  45545. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45546. ], PBRMaterial.prototype, "emissiveColor", void 0);
  45547. __decorate([
  45548. BABYLON.serialize(),
  45549. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45550. ], PBRMaterial.prototype, "microSurface", void 0);
  45551. __decorate([
  45552. BABYLON.serialize(),
  45553. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45554. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  45555. __decorate([
  45556. BABYLON.serialize(),
  45557. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45558. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  45559. __decorate([
  45560. BABYLON.serialize(),
  45561. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45562. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  45563. __decorate([
  45564. BABYLON.serialize(),
  45565. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45566. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45567. __decorate([
  45568. BABYLON.serialize(),
  45569. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45570. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  45571. __decorate([
  45572. BABYLON.serialize(),
  45573. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45574. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  45575. __decorate([
  45576. BABYLON.serialize(),
  45577. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45578. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  45579. __decorate([
  45580. BABYLON.serialize(),
  45581. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45582. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  45583. __decorate([
  45584. BABYLON.serialize(),
  45585. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45586. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  45587. __decorate([
  45588. BABYLON.serialize(),
  45589. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45590. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  45591. __decorate([
  45592. BABYLON.serialize(),
  45593. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45594. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  45595. __decorate([
  45596. BABYLON.serialize(),
  45597. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45598. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  45599. __decorate([
  45600. BABYLON.serialize(),
  45601. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45602. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  45603. __decorate([
  45604. BABYLON.serialize(),
  45605. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45606. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  45607. __decorate([
  45608. BABYLON.serialize(),
  45609. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45610. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  45611. __decorate([
  45612. BABYLON.serialize(),
  45613. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45614. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  45615. __decorate([
  45616. BABYLON.serialize(),
  45617. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45618. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  45619. __decorate([
  45620. BABYLON.serialize(),
  45621. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45622. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  45623. __decorate([
  45624. BABYLON.serialize(),
  45625. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45626. ], PBRMaterial.prototype, "useParallax", void 0);
  45627. __decorate([
  45628. BABYLON.serialize(),
  45629. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45630. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  45631. __decorate([
  45632. BABYLON.serialize(),
  45633. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45634. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  45635. __decorate([
  45636. BABYLON.serialize(),
  45637. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45638. ], PBRMaterial.prototype, "disableLighting", void 0);
  45639. __decorate([
  45640. BABYLON.serialize(),
  45641. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45642. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  45643. __decorate([
  45644. BABYLON.serialize(),
  45645. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45646. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  45647. __decorate([
  45648. BABYLON.serialize(),
  45649. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45650. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  45651. __decorate([
  45652. BABYLON.serialize(),
  45653. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45654. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  45655. __decorate([
  45656. BABYLON.serialize(),
  45657. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45658. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  45659. __decorate([
  45660. BABYLON.serialize(),
  45661. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45662. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  45663. __decorate([
  45664. BABYLON.serialize(),
  45665. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45666. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  45667. __decorate([
  45668. BABYLON.serializeAsTexture(),
  45669. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45670. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  45671. __decorate([
  45672. BABYLON.serialize(),
  45673. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45674. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  45675. __decorate([
  45676. BABYLON.serialize(),
  45677. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45678. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  45679. __decorate([
  45680. BABYLON.serialize(),
  45681. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45682. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  45683. __decorate([
  45684. BABYLON.serialize(),
  45685. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45686. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  45687. __decorate([
  45688. BABYLON.serialize(),
  45689. BABYLON.expandToProperty("_markAllSubMeshesAsMiscDirty")
  45690. ], PBRMaterial.prototype, "unlit", void 0);
  45691. return PBRMaterial;
  45692. }(BABYLON.PBRBaseMaterial));
  45693. BABYLON.PBRMaterial = PBRMaterial;
  45694. })(BABYLON || (BABYLON = {}));
  45695. //# sourceMappingURL=babylon.pbrMaterial.js.map
  45696. var BABYLON;
  45697. (function (BABYLON) {
  45698. /**
  45699. * The PBR material of BJS following the metal roughness convention.
  45700. *
  45701. * This fits to the PBR convention in the GLTF definition:
  45702. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  45703. */
  45704. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  45705. __extends(PBRMetallicRoughnessMaterial, _super);
  45706. /**
  45707. * Instantiates a new PBRMetalRoughnessMaterial instance.
  45708. *
  45709. * @param name The material name
  45710. * @param scene The scene the material will be use in.
  45711. */
  45712. function PBRMetallicRoughnessMaterial(name, scene) {
  45713. var _this = _super.call(this, name, scene) || this;
  45714. _this._useRoughnessFromMetallicTextureAlpha = false;
  45715. _this._useRoughnessFromMetallicTextureGreen = true;
  45716. _this._useMetallnessFromMetallicTextureBlue = true;
  45717. _this.metallic = 1.0;
  45718. _this.roughness = 1.0;
  45719. return _this;
  45720. }
  45721. /**
  45722. * Return the currrent class name of the material.
  45723. */
  45724. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  45725. return "PBRMetallicRoughnessMaterial";
  45726. };
  45727. /**
  45728. * Return the active textures of the material.
  45729. */
  45730. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  45731. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45732. if (this.baseTexture) {
  45733. activeTextures.push(this.baseTexture);
  45734. }
  45735. if (this.metallicRoughnessTexture) {
  45736. activeTextures.push(this.metallicRoughnessTexture);
  45737. }
  45738. return activeTextures;
  45739. };
  45740. /**
  45741. * Checks to see if a texture is used in the material.
  45742. * @param texture - Base texture to use.
  45743. * @returns - Boolean specifying if a texture is used in the material.
  45744. */
  45745. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  45746. if (_super.prototype.hasTexture.call(this, texture)) {
  45747. return true;
  45748. }
  45749. if (this.baseTexture === texture) {
  45750. return true;
  45751. }
  45752. if (this.metallicRoughnessTexture === texture) {
  45753. return true;
  45754. }
  45755. return false;
  45756. };
  45757. /**
  45758. * Makes a duplicate of the current material.
  45759. * @param name - name to use for the new material.
  45760. */
  45761. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  45762. var _this = this;
  45763. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  45764. clone.id = name;
  45765. clone.name = name;
  45766. return clone;
  45767. };
  45768. /**
  45769. * Serialize the material to a parsable JSON object.
  45770. */
  45771. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  45772. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45773. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  45774. return serializationObject;
  45775. };
  45776. /**
  45777. * Parses a JSON object correponding to the serialize function.
  45778. */
  45779. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  45780. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  45781. };
  45782. __decorate([
  45783. BABYLON.serializeAsColor3(),
  45784. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  45785. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  45786. __decorate([
  45787. BABYLON.serializeAsTexture(),
  45788. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  45789. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  45790. __decorate([
  45791. BABYLON.serialize(),
  45792. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45793. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  45794. __decorate([
  45795. BABYLON.serialize(),
  45796. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45797. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  45798. __decorate([
  45799. BABYLON.serializeAsTexture(),
  45800. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  45801. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  45802. return PBRMetallicRoughnessMaterial;
  45803. }(BABYLON.PBRBaseSimpleMaterial));
  45804. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  45805. })(BABYLON || (BABYLON = {}));
  45806. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  45807. var BABYLON;
  45808. (function (BABYLON) {
  45809. /**
  45810. * The PBR material of BJS following the specular glossiness convention.
  45811. *
  45812. * This fits to the PBR convention in the GLTF definition:
  45813. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  45814. */
  45815. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  45816. __extends(PBRSpecularGlossinessMaterial, _super);
  45817. /**
  45818. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  45819. *
  45820. * @param name The material name
  45821. * @param scene The scene the material will be use in.
  45822. */
  45823. function PBRSpecularGlossinessMaterial(name, scene) {
  45824. var _this = _super.call(this, name, scene) || this;
  45825. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  45826. return _this;
  45827. }
  45828. /**
  45829. * Return the currrent class name of the material.
  45830. */
  45831. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  45832. return "PBRSpecularGlossinessMaterial";
  45833. };
  45834. /**
  45835. * Return the active textures of the material.
  45836. */
  45837. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  45838. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45839. if (this.diffuseTexture) {
  45840. activeTextures.push(this.diffuseTexture);
  45841. }
  45842. if (this.specularGlossinessTexture) {
  45843. activeTextures.push(this.specularGlossinessTexture);
  45844. }
  45845. return activeTextures;
  45846. };
  45847. /**
  45848. * Checks to see if a texture is used in the material.
  45849. * @param texture - Base texture to use.
  45850. * @returns - Boolean specifying if a texture is used in the material.
  45851. */
  45852. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  45853. if (_super.prototype.hasTexture.call(this, texture)) {
  45854. return true;
  45855. }
  45856. if (this.diffuseTexture === texture) {
  45857. return true;
  45858. }
  45859. if (this.specularGlossinessTexture === texture) {
  45860. return true;
  45861. }
  45862. return false;
  45863. };
  45864. /**
  45865. * Makes a duplicate of the current material.
  45866. * @param name - name to use for the new material.
  45867. */
  45868. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  45869. var _this = this;
  45870. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  45871. clone.id = name;
  45872. clone.name = name;
  45873. return clone;
  45874. };
  45875. /**
  45876. * Serialize the material to a parsable JSON object.
  45877. */
  45878. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  45879. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45880. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  45881. return serializationObject;
  45882. };
  45883. /**
  45884. * Parses a JSON object correponding to the serialize function.
  45885. */
  45886. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  45887. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  45888. };
  45889. __decorate([
  45890. BABYLON.serializeAsColor3("diffuse"),
  45891. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  45892. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  45893. __decorate([
  45894. BABYLON.serializeAsTexture(),
  45895. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  45896. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  45897. __decorate([
  45898. BABYLON.serializeAsColor3("specular"),
  45899. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  45900. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  45901. __decorate([
  45902. BABYLON.serialize(),
  45903. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  45904. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  45905. __decorate([
  45906. BABYLON.serializeAsTexture(),
  45907. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  45908. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  45909. return PBRSpecularGlossinessMaterial;
  45910. }(BABYLON.PBRBaseSimpleMaterial));
  45911. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  45912. })(BABYLON || (BABYLON = {}));
  45913. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  45914. var BABYLON;
  45915. (function (BABYLON) {
  45916. BABYLON.CameraInputTypes = {};
  45917. var CameraInputsManager = /** @class */ (function () {
  45918. function CameraInputsManager(camera) {
  45919. this.attached = {};
  45920. this.camera = camera;
  45921. this.checkInputs = function () { };
  45922. }
  45923. /**
  45924. * Add an input method to a camera.
  45925. * builtin inputs example: camera.inputs.addGamepad();
  45926. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  45927. * @param input camera input method
  45928. */
  45929. CameraInputsManager.prototype.add = function (input) {
  45930. var type = input.getSimpleName();
  45931. if (this.attached[type]) {
  45932. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  45933. return;
  45934. }
  45935. this.attached[type] = input;
  45936. input.camera = this.camera;
  45937. //for checkInputs, we are dynamically creating a function
  45938. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  45939. if (input.checkInputs) {
  45940. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  45941. }
  45942. if (this.attachedElement) {
  45943. input.attachControl(this.attachedElement);
  45944. }
  45945. };
  45946. /**
  45947. * Remove a specific input method from a camera
  45948. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  45949. * @param inputToRemove camera input method
  45950. */
  45951. CameraInputsManager.prototype.remove = function (inputToRemove) {
  45952. for (var cam in this.attached) {
  45953. var input = this.attached[cam];
  45954. if (input === inputToRemove) {
  45955. input.detachControl(this.attachedElement);
  45956. input.camera = null;
  45957. delete this.attached[cam];
  45958. this.rebuildInputCheck();
  45959. }
  45960. }
  45961. };
  45962. CameraInputsManager.prototype.removeByType = function (inputType) {
  45963. for (var cam in this.attached) {
  45964. var input = this.attached[cam];
  45965. if (input.getClassName() === inputType) {
  45966. input.detachControl(this.attachedElement);
  45967. input.camera = null;
  45968. delete this.attached[cam];
  45969. this.rebuildInputCheck();
  45970. }
  45971. }
  45972. };
  45973. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  45974. var current = this.checkInputs;
  45975. return function () {
  45976. current();
  45977. fn();
  45978. };
  45979. };
  45980. CameraInputsManager.prototype.attachInput = function (input) {
  45981. if (this.attachedElement) {
  45982. input.attachControl(this.attachedElement, this.noPreventDefault);
  45983. }
  45984. };
  45985. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  45986. if (noPreventDefault === void 0) { noPreventDefault = false; }
  45987. if (this.attachedElement) {
  45988. return;
  45989. }
  45990. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  45991. this.attachedElement = element;
  45992. this.noPreventDefault = noPreventDefault;
  45993. for (var cam in this.attached) {
  45994. this.attached[cam].attachControl(element, noPreventDefault);
  45995. }
  45996. };
  45997. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  45998. if (disconnect === void 0) { disconnect = false; }
  45999. if (this.attachedElement !== element) {
  46000. return;
  46001. }
  46002. for (var cam in this.attached) {
  46003. this.attached[cam].detachControl(element);
  46004. if (disconnect) {
  46005. this.attached[cam].camera = null;
  46006. }
  46007. }
  46008. this.attachedElement = null;
  46009. };
  46010. CameraInputsManager.prototype.rebuildInputCheck = function () {
  46011. this.checkInputs = function () { };
  46012. for (var cam in this.attached) {
  46013. var input = this.attached[cam];
  46014. if (input.checkInputs) {
  46015. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  46016. }
  46017. }
  46018. };
  46019. /**
  46020. * Remove all attached input methods from a camera
  46021. */
  46022. CameraInputsManager.prototype.clear = function () {
  46023. if (this.attachedElement) {
  46024. this.detachElement(this.attachedElement, true);
  46025. }
  46026. this.attached = {};
  46027. this.attachedElement = null;
  46028. this.checkInputs = function () { };
  46029. };
  46030. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  46031. var inputs = {};
  46032. for (var cam in this.attached) {
  46033. var input = this.attached[cam];
  46034. var res = BABYLON.SerializationHelper.Serialize(input);
  46035. inputs[input.getClassName()] = res;
  46036. }
  46037. serializedCamera.inputsmgr = inputs;
  46038. };
  46039. CameraInputsManager.prototype.parse = function (parsedCamera) {
  46040. var parsedInputs = parsedCamera.inputsmgr;
  46041. if (parsedInputs) {
  46042. this.clear();
  46043. for (var n in parsedInputs) {
  46044. var construct = BABYLON.CameraInputTypes[n];
  46045. if (construct) {
  46046. var parsedinput = parsedInputs[n];
  46047. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  46048. this.add(input);
  46049. }
  46050. }
  46051. }
  46052. else {
  46053. //2016-03-08 this part is for managing backward compatibility
  46054. for (var n in this.attached) {
  46055. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  46056. if (construct) {
  46057. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  46058. this.remove(this.attached[n]);
  46059. this.add(input);
  46060. }
  46061. }
  46062. }
  46063. };
  46064. return CameraInputsManager;
  46065. }());
  46066. BABYLON.CameraInputsManager = CameraInputsManager;
  46067. })(BABYLON || (BABYLON = {}));
  46068. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  46069. var BABYLON;
  46070. (function (BABYLON) {
  46071. var TargetCamera = /** @class */ (function (_super) {
  46072. __extends(TargetCamera, _super);
  46073. function TargetCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  46074. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  46075. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  46076. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  46077. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  46078. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  46079. _this.speed = 2.0;
  46080. _this.noRotationConstraint = false;
  46081. _this.lockedTarget = null;
  46082. _this._currentTarget = BABYLON.Vector3.Zero();
  46083. _this._viewMatrix = BABYLON.Matrix.Zero();
  46084. _this._camMatrix = BABYLON.Matrix.Zero();
  46085. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  46086. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  46087. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  46088. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  46089. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  46090. _this._globalCurrentTarget = BABYLON.Vector3.Zero();
  46091. _this._globalCurrentUpVector = BABYLON.Vector3.Zero();
  46092. return _this;
  46093. }
  46094. TargetCamera.prototype.getFrontPosition = function (distance) {
  46095. this.getWorldMatrix();
  46096. var direction = this.getTarget().subtract(this.position);
  46097. direction.normalize();
  46098. direction.scaleInPlace(distance);
  46099. return this.globalPosition.add(direction);
  46100. };
  46101. TargetCamera.prototype._getLockedTargetPosition = function () {
  46102. if (!this.lockedTarget) {
  46103. return null;
  46104. }
  46105. if (this.lockedTarget.absolutePosition) {
  46106. this.lockedTarget.computeWorldMatrix();
  46107. }
  46108. return this.lockedTarget.absolutePosition || this.lockedTarget;
  46109. };
  46110. TargetCamera.prototype.storeState = function () {
  46111. this._storedPosition = this.position.clone();
  46112. this._storedRotation = this.rotation.clone();
  46113. if (this.rotationQuaternion) {
  46114. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  46115. }
  46116. return _super.prototype.storeState.call(this);
  46117. };
  46118. /**
  46119. * Restored camera state. You must call storeState() first
  46120. */
  46121. TargetCamera.prototype._restoreStateValues = function () {
  46122. if (!_super.prototype._restoreStateValues.call(this)) {
  46123. return false;
  46124. }
  46125. this.position = this._storedPosition.clone();
  46126. this.rotation = this._storedRotation.clone();
  46127. if (this.rotationQuaternion) {
  46128. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  46129. }
  46130. this.cameraDirection.copyFromFloats(0, 0, 0);
  46131. this.cameraRotation.copyFromFloats(0, 0);
  46132. return true;
  46133. };
  46134. // Cache
  46135. TargetCamera.prototype._initCache = function () {
  46136. _super.prototype._initCache.call(this);
  46137. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46138. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46139. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46140. };
  46141. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  46142. if (!ignoreParentClass) {
  46143. _super.prototype._updateCache.call(this);
  46144. }
  46145. var lockedTargetPosition = this._getLockedTargetPosition();
  46146. if (!lockedTargetPosition) {
  46147. this._cache.lockedTarget = null;
  46148. }
  46149. else {
  46150. if (!this._cache.lockedTarget) {
  46151. this._cache.lockedTarget = lockedTargetPosition.clone();
  46152. }
  46153. else {
  46154. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  46155. }
  46156. }
  46157. this._cache.rotation.copyFrom(this.rotation);
  46158. if (this.rotationQuaternion)
  46159. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46160. };
  46161. // Synchronized
  46162. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  46163. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  46164. return false;
  46165. }
  46166. var lockedTargetPosition = this._getLockedTargetPosition();
  46167. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  46168. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  46169. };
  46170. // Methods
  46171. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  46172. var engine = this.getEngine();
  46173. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  46174. };
  46175. // Target
  46176. TargetCamera.prototype.setTarget = function (target) {
  46177. this.upVector.normalize();
  46178. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  46179. this._camMatrix.invert();
  46180. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  46181. var vDir = target.subtract(this.position);
  46182. if (vDir.x >= 0.0) {
  46183. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  46184. }
  46185. else {
  46186. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  46187. }
  46188. this.rotation.z = 0;
  46189. if (isNaN(this.rotation.x)) {
  46190. this.rotation.x = 0;
  46191. }
  46192. if (isNaN(this.rotation.y)) {
  46193. this.rotation.y = 0;
  46194. }
  46195. if (isNaN(this.rotation.z)) {
  46196. this.rotation.z = 0;
  46197. }
  46198. if (this.rotationQuaternion) {
  46199. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46200. }
  46201. };
  46202. /**
  46203. * Return the current target position of the camera. This value is expressed in local space.
  46204. */
  46205. TargetCamera.prototype.getTarget = function () {
  46206. return this._currentTarget;
  46207. };
  46208. TargetCamera.prototype._decideIfNeedsToMove = function () {
  46209. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  46210. };
  46211. TargetCamera.prototype._updatePosition = function () {
  46212. if (this.parent) {
  46213. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  46214. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  46215. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  46216. return;
  46217. }
  46218. this.position.addInPlace(this.cameraDirection);
  46219. };
  46220. TargetCamera.prototype._checkInputs = function () {
  46221. var needToMove = this._decideIfNeedsToMove();
  46222. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  46223. // Move
  46224. if (needToMove) {
  46225. this._updatePosition();
  46226. }
  46227. // Rotate
  46228. if (needToRotate) {
  46229. this.rotation.x += this.cameraRotation.x;
  46230. this.rotation.y += this.cameraRotation.y;
  46231. //rotate, if quaternion is set and rotation was used
  46232. if (this.rotationQuaternion) {
  46233. var len = this.rotation.lengthSquared();
  46234. if (len) {
  46235. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46236. }
  46237. }
  46238. if (!this.noRotationConstraint) {
  46239. var limit = (Math.PI / 2) * 0.95;
  46240. if (this.rotation.x > limit)
  46241. this.rotation.x = limit;
  46242. if (this.rotation.x < -limit)
  46243. this.rotation.x = -limit;
  46244. }
  46245. }
  46246. // Inertia
  46247. if (needToMove) {
  46248. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  46249. this.cameraDirection.x = 0;
  46250. }
  46251. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  46252. this.cameraDirection.y = 0;
  46253. }
  46254. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  46255. this.cameraDirection.z = 0;
  46256. }
  46257. this.cameraDirection.scaleInPlace(this.inertia);
  46258. }
  46259. if (needToRotate) {
  46260. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  46261. this.cameraRotation.x = 0;
  46262. }
  46263. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  46264. this.cameraRotation.y = 0;
  46265. }
  46266. this.cameraRotation.scaleInPlace(this.inertia);
  46267. }
  46268. _super.prototype._checkInputs.call(this);
  46269. };
  46270. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  46271. if (this.rotationQuaternion) {
  46272. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  46273. }
  46274. else {
  46275. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  46276. }
  46277. //update the up vector!
  46278. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  46279. };
  46280. TargetCamera.prototype._getViewMatrix = function () {
  46281. if (this.lockedTarget) {
  46282. this.setTarget(this._getLockedTargetPosition());
  46283. }
  46284. // Compute
  46285. this._updateCameraRotationMatrix();
  46286. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  46287. // Computing target and final matrix
  46288. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  46289. this._computeViewMatrix(this.position, this._currentTarget, this._currentUpVector);
  46290. return this._viewMatrix;
  46291. };
  46292. TargetCamera.prototype._computeViewMatrix = function (position, target, up) {
  46293. if (this.parent) {
  46294. var parentWorldMatrix = this.parent.getWorldMatrix();
  46295. BABYLON.Vector3.TransformCoordinatesToRef(this.position, parentWorldMatrix, this._globalPosition);
  46296. BABYLON.Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._globalCurrentTarget);
  46297. BABYLON.Vector3.TransformNormalToRef(up, parentWorldMatrix, this._globalCurrentUpVector);
  46298. this._markSyncedWithParent();
  46299. }
  46300. else {
  46301. this._globalPosition.copyFrom(this.position);
  46302. this._globalCurrentTarget.copyFrom(target);
  46303. this._globalCurrentUpVector.copyFrom(up);
  46304. }
  46305. if (this.getScene().useRightHandedSystem) {
  46306. BABYLON.Matrix.LookAtRHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  46307. }
  46308. else {
  46309. BABYLON.Matrix.LookAtLHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  46310. }
  46311. };
  46312. /**
  46313. * @override
  46314. * Override Camera.createRigCamera
  46315. */
  46316. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  46317. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  46318. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  46319. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  46320. if (!this.rotationQuaternion) {
  46321. this.rotationQuaternion = new BABYLON.Quaternion();
  46322. }
  46323. rigCamera._cameraRigParams = {};
  46324. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  46325. }
  46326. return rigCamera;
  46327. }
  46328. return null;
  46329. };
  46330. /**
  46331. * @override
  46332. * Override Camera._updateRigCameras
  46333. */
  46334. TargetCamera.prototype._updateRigCameras = function () {
  46335. var camLeft = this._rigCameras[0];
  46336. var camRight = this._rigCameras[1];
  46337. switch (this.cameraRigMode) {
  46338. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  46339. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  46340. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  46341. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  46342. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  46343. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  46344. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  46345. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  46346. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  46347. camLeft.setTarget(this.getTarget());
  46348. camRight.setTarget(this.getTarget());
  46349. break;
  46350. case BABYLON.Camera.RIG_MODE_VR:
  46351. if (camLeft.rotationQuaternion) {
  46352. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46353. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46354. }
  46355. else {
  46356. camLeft.rotation.copyFrom(this.rotation);
  46357. camRight.rotation.copyFrom(this.rotation);
  46358. }
  46359. camLeft.position.copyFrom(this.position);
  46360. camRight.position.copyFrom(this.position);
  46361. break;
  46362. }
  46363. _super.prototype._updateRigCameras.call(this);
  46364. };
  46365. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  46366. if (!this._rigCamTransformMatrix) {
  46367. this._rigCamTransformMatrix = new BABYLON.Matrix();
  46368. }
  46369. var target = this.getTarget();
  46370. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  46371. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  46372. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  46373. };
  46374. TargetCamera.prototype.getClassName = function () {
  46375. return "TargetCamera";
  46376. };
  46377. __decorate([
  46378. BABYLON.serializeAsVector3()
  46379. ], TargetCamera.prototype, "rotation", void 0);
  46380. __decorate([
  46381. BABYLON.serialize()
  46382. ], TargetCamera.prototype, "speed", void 0);
  46383. __decorate([
  46384. BABYLON.serializeAsMeshReference("lockedTargetId")
  46385. ], TargetCamera.prototype, "lockedTarget", void 0);
  46386. return TargetCamera;
  46387. }(BABYLON.Camera));
  46388. BABYLON.TargetCamera = TargetCamera;
  46389. })(BABYLON || (BABYLON = {}));
  46390. //# sourceMappingURL=babylon.targetCamera.js.map
  46391. var BABYLON;
  46392. (function (BABYLON) {
  46393. var FreeCameraMouseInput = /** @class */ (function () {
  46394. function FreeCameraMouseInput(touchEnabled) {
  46395. if (touchEnabled === void 0) { touchEnabled = true; }
  46396. this.touchEnabled = touchEnabled;
  46397. this.buttons = [0, 1, 2];
  46398. this.angularSensibility = 2000.0;
  46399. this.previousPosition = null;
  46400. }
  46401. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  46402. var _this = this;
  46403. var engine = this.camera.getEngine();
  46404. if (!this._pointerInput) {
  46405. this._pointerInput = function (p, s) {
  46406. var evt = p.event;
  46407. if (engine.isInVRExclusivePointerMode) {
  46408. return;
  46409. }
  46410. if (!_this.touchEnabled && evt.pointerType === "touch") {
  46411. return;
  46412. }
  46413. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  46414. return;
  46415. }
  46416. var srcElement = (evt.srcElement || evt.target);
  46417. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  46418. try {
  46419. srcElement.setPointerCapture(evt.pointerId);
  46420. }
  46421. catch (e) {
  46422. //Nothing to do with the error. Execution will continue.
  46423. }
  46424. _this.previousPosition = {
  46425. x: evt.clientX,
  46426. y: evt.clientY
  46427. };
  46428. if (!noPreventDefault) {
  46429. evt.preventDefault();
  46430. element.focus();
  46431. }
  46432. }
  46433. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  46434. try {
  46435. srcElement.releasePointerCapture(evt.pointerId);
  46436. }
  46437. catch (e) {
  46438. //Nothing to do with the error.
  46439. }
  46440. _this.previousPosition = null;
  46441. if (!noPreventDefault) {
  46442. evt.preventDefault();
  46443. }
  46444. }
  46445. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  46446. if (!_this.previousPosition || engine.isPointerLock) {
  46447. return;
  46448. }
  46449. var offsetX = evt.clientX - _this.previousPosition.x;
  46450. if (_this.camera.getScene().useRightHandedSystem)
  46451. offsetX *= -1;
  46452. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  46453. offsetX *= -1;
  46454. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46455. var offsetY = evt.clientY - _this.previousPosition.y;
  46456. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46457. _this.previousPosition = {
  46458. x: evt.clientX,
  46459. y: evt.clientY
  46460. };
  46461. if (!noPreventDefault) {
  46462. evt.preventDefault();
  46463. }
  46464. }
  46465. };
  46466. }
  46467. this._onMouseMove = function (evt) {
  46468. if (!engine.isPointerLock) {
  46469. return;
  46470. }
  46471. if (engine.isInVRExclusivePointerMode) {
  46472. return;
  46473. }
  46474. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  46475. if (_this.camera.getScene().useRightHandedSystem)
  46476. offsetX *= -1;
  46477. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  46478. offsetX *= -1;
  46479. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46480. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  46481. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46482. _this.previousPosition = null;
  46483. if (!noPreventDefault) {
  46484. evt.preventDefault();
  46485. }
  46486. };
  46487. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  46488. element.addEventListener("mousemove", this._onMouseMove, false);
  46489. };
  46490. FreeCameraMouseInput.prototype.detachControl = function (element) {
  46491. if (this._observer && element) {
  46492. this.camera.getScene().onPointerObservable.remove(this._observer);
  46493. if (this._onMouseMove) {
  46494. element.removeEventListener("mousemove", this._onMouseMove);
  46495. }
  46496. this._observer = null;
  46497. this._onMouseMove = null;
  46498. this.previousPosition = null;
  46499. }
  46500. };
  46501. FreeCameraMouseInput.prototype.getClassName = function () {
  46502. return "FreeCameraMouseInput";
  46503. };
  46504. FreeCameraMouseInput.prototype.getSimpleName = function () {
  46505. return "mouse";
  46506. };
  46507. __decorate([
  46508. BABYLON.serialize()
  46509. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  46510. __decorate([
  46511. BABYLON.serialize()
  46512. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  46513. return FreeCameraMouseInput;
  46514. }());
  46515. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  46516. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  46517. })(BABYLON || (BABYLON = {}));
  46518. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  46519. var BABYLON;
  46520. (function (BABYLON) {
  46521. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  46522. function FreeCameraKeyboardMoveInput() {
  46523. this._keys = new Array();
  46524. this.keysUp = [38];
  46525. this.keysDown = [40];
  46526. this.keysLeft = [37];
  46527. this.keysRight = [39];
  46528. }
  46529. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  46530. var _this = this;
  46531. if (this._onCanvasBlurObserver) {
  46532. return;
  46533. }
  46534. this._scene = this.camera.getScene();
  46535. this._engine = this._scene.getEngine();
  46536. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  46537. _this._keys = [];
  46538. });
  46539. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  46540. var evt = info.event;
  46541. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  46542. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46543. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46544. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46545. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46546. var index = _this._keys.indexOf(evt.keyCode);
  46547. if (index === -1) {
  46548. _this._keys.push(evt.keyCode);
  46549. }
  46550. if (!noPreventDefault) {
  46551. evt.preventDefault();
  46552. }
  46553. }
  46554. }
  46555. else {
  46556. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46557. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46558. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46559. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46560. var index = _this._keys.indexOf(evt.keyCode);
  46561. if (index >= 0) {
  46562. _this._keys.splice(index, 1);
  46563. }
  46564. if (!noPreventDefault) {
  46565. evt.preventDefault();
  46566. }
  46567. }
  46568. }
  46569. });
  46570. };
  46571. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  46572. if (this._scene) {
  46573. if (this._onKeyboardObserver) {
  46574. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  46575. }
  46576. if (this._onCanvasBlurObserver) {
  46577. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  46578. }
  46579. this._onKeyboardObserver = null;
  46580. this._onCanvasBlurObserver = null;
  46581. }
  46582. this._keys = [];
  46583. };
  46584. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  46585. if (this._onKeyboardObserver) {
  46586. var camera = this.camera;
  46587. // Keyboard
  46588. for (var index = 0; index < this._keys.length; index++) {
  46589. var keyCode = this._keys[index];
  46590. var speed = camera._computeLocalCameraSpeed();
  46591. if (this.keysLeft.indexOf(keyCode) !== -1) {
  46592. camera._localDirection.copyFromFloats(-speed, 0, 0);
  46593. }
  46594. else if (this.keysUp.indexOf(keyCode) !== -1) {
  46595. camera._localDirection.copyFromFloats(0, 0, speed);
  46596. }
  46597. else if (this.keysRight.indexOf(keyCode) !== -1) {
  46598. camera._localDirection.copyFromFloats(speed, 0, 0);
  46599. }
  46600. else if (this.keysDown.indexOf(keyCode) !== -1) {
  46601. camera._localDirection.copyFromFloats(0, 0, -speed);
  46602. }
  46603. if (camera.getScene().useRightHandedSystem) {
  46604. camera._localDirection.z *= -1;
  46605. }
  46606. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  46607. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  46608. camera.cameraDirection.addInPlace(camera._transformedDirection);
  46609. }
  46610. }
  46611. };
  46612. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  46613. return "FreeCameraKeyboardMoveInput";
  46614. };
  46615. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  46616. this._keys = [];
  46617. };
  46618. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  46619. return "keyboard";
  46620. };
  46621. __decorate([
  46622. BABYLON.serialize()
  46623. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  46624. __decorate([
  46625. BABYLON.serialize()
  46626. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  46627. __decorate([
  46628. BABYLON.serialize()
  46629. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  46630. __decorate([
  46631. BABYLON.serialize()
  46632. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  46633. return FreeCameraKeyboardMoveInput;
  46634. }());
  46635. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  46636. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  46637. })(BABYLON || (BABYLON = {}));
  46638. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  46639. var BABYLON;
  46640. (function (BABYLON) {
  46641. var FreeCameraInputsManager = /** @class */ (function (_super) {
  46642. __extends(FreeCameraInputsManager, _super);
  46643. function FreeCameraInputsManager(camera) {
  46644. return _super.call(this, camera) || this;
  46645. }
  46646. FreeCameraInputsManager.prototype.addKeyboard = function () {
  46647. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  46648. return this;
  46649. };
  46650. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  46651. if (touchEnabled === void 0) { touchEnabled = true; }
  46652. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  46653. return this;
  46654. };
  46655. FreeCameraInputsManager.prototype.addGamepad = function () {
  46656. this.add(new BABYLON.FreeCameraGamepadInput());
  46657. return this;
  46658. };
  46659. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  46660. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  46661. return this;
  46662. };
  46663. FreeCameraInputsManager.prototype.addTouch = function () {
  46664. this.add(new BABYLON.FreeCameraTouchInput());
  46665. return this;
  46666. };
  46667. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  46668. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  46669. return this;
  46670. };
  46671. return FreeCameraInputsManager;
  46672. }(BABYLON.CameraInputsManager));
  46673. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  46674. })(BABYLON || (BABYLON = {}));
  46675. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  46676. var BABYLON;
  46677. (function (BABYLON) {
  46678. var FreeCamera = /** @class */ (function (_super) {
  46679. __extends(FreeCamera, _super);
  46680. function FreeCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  46681. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  46682. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  46683. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  46684. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  46685. _this.checkCollisions = false;
  46686. _this.applyGravity = false;
  46687. _this._needMoveForGravity = false;
  46688. _this._oldPosition = BABYLON.Vector3.Zero();
  46689. _this._diffPosition = BABYLON.Vector3.Zero();
  46690. _this._newPosition = BABYLON.Vector3.Zero();
  46691. // Collisions
  46692. _this._collisionMask = -1;
  46693. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  46694. if (collidedMesh === void 0) { collidedMesh = null; }
  46695. //TODO move this to the collision coordinator!
  46696. if (_this.getScene().workerCollisions)
  46697. newPosition.multiplyInPlace(_this._collider._radius);
  46698. var updatePosition = function (newPos) {
  46699. _this._newPosition.copyFrom(newPos);
  46700. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  46701. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  46702. _this.position.addInPlace(_this._diffPosition);
  46703. if (_this.onCollide && collidedMesh) {
  46704. _this.onCollide(collidedMesh);
  46705. }
  46706. }
  46707. };
  46708. updatePosition(newPosition);
  46709. };
  46710. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  46711. _this.inputs.addKeyboard().addMouse();
  46712. return _this;
  46713. }
  46714. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  46715. //-- begin properties for backward compatibility for inputs
  46716. /**
  46717. * Gets the input sensibility for a mouse input. (default is 2000.0)
  46718. * Higher values reduce sensitivity.
  46719. */
  46720. get: function () {
  46721. var mouse = this.inputs.attached["mouse"];
  46722. if (mouse)
  46723. return mouse.angularSensibility;
  46724. return 0;
  46725. },
  46726. /**
  46727. * Sets the input sensibility for a mouse input. (default is 2000.0)
  46728. * Higher values reduce sensitivity.
  46729. */
  46730. set: function (value) {
  46731. var mouse = this.inputs.attached["mouse"];
  46732. if (mouse)
  46733. mouse.angularSensibility = value;
  46734. },
  46735. enumerable: true,
  46736. configurable: true
  46737. });
  46738. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  46739. get: function () {
  46740. var keyboard = this.inputs.attached["keyboard"];
  46741. if (keyboard)
  46742. return keyboard.keysUp;
  46743. return [];
  46744. },
  46745. set: function (value) {
  46746. var keyboard = this.inputs.attached["keyboard"];
  46747. if (keyboard)
  46748. keyboard.keysUp = value;
  46749. },
  46750. enumerable: true,
  46751. configurable: true
  46752. });
  46753. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  46754. get: function () {
  46755. var keyboard = this.inputs.attached["keyboard"];
  46756. if (keyboard)
  46757. return keyboard.keysDown;
  46758. return [];
  46759. },
  46760. set: function (value) {
  46761. var keyboard = this.inputs.attached["keyboard"];
  46762. if (keyboard)
  46763. keyboard.keysDown = value;
  46764. },
  46765. enumerable: true,
  46766. configurable: true
  46767. });
  46768. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  46769. get: function () {
  46770. var keyboard = this.inputs.attached["keyboard"];
  46771. if (keyboard)
  46772. return keyboard.keysLeft;
  46773. return [];
  46774. },
  46775. set: function (value) {
  46776. var keyboard = this.inputs.attached["keyboard"];
  46777. if (keyboard)
  46778. keyboard.keysLeft = value;
  46779. },
  46780. enumerable: true,
  46781. configurable: true
  46782. });
  46783. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  46784. get: function () {
  46785. var keyboard = this.inputs.attached["keyboard"];
  46786. if (keyboard)
  46787. return keyboard.keysRight;
  46788. return [];
  46789. },
  46790. set: function (value) {
  46791. var keyboard = this.inputs.attached["keyboard"];
  46792. if (keyboard)
  46793. keyboard.keysRight = value;
  46794. },
  46795. enumerable: true,
  46796. configurable: true
  46797. });
  46798. // Controls
  46799. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  46800. this.inputs.attachElement(element, noPreventDefault);
  46801. };
  46802. FreeCamera.prototype.detachControl = function (element) {
  46803. this.inputs.detachElement(element);
  46804. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  46805. this.cameraRotation = new BABYLON.Vector2(0, 0);
  46806. };
  46807. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  46808. get: function () {
  46809. return this._collisionMask;
  46810. },
  46811. set: function (mask) {
  46812. this._collisionMask = !isNaN(mask) ? mask : -1;
  46813. },
  46814. enumerable: true,
  46815. configurable: true
  46816. });
  46817. FreeCamera.prototype._collideWithWorld = function (displacement) {
  46818. var globalPosition;
  46819. if (this.parent) {
  46820. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  46821. }
  46822. else {
  46823. globalPosition = this.position;
  46824. }
  46825. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  46826. this._oldPosition.addInPlace(this.ellipsoidOffset);
  46827. if (!this._collider) {
  46828. this._collider = new BABYLON.Collider();
  46829. }
  46830. this._collider._radius = this.ellipsoid;
  46831. this._collider.collisionMask = this._collisionMask;
  46832. //no need for clone, as long as gravity is not on.
  46833. var actualDisplacement = displacement;
  46834. //add gravity to the direction to prevent the dual-collision checking
  46835. if (this.applyGravity) {
  46836. //this prevents mending with cameraDirection, a global variable of the free camera class.
  46837. actualDisplacement = displacement.add(this.getScene().gravity);
  46838. }
  46839. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  46840. };
  46841. FreeCamera.prototype._checkInputs = function () {
  46842. if (!this._localDirection) {
  46843. this._localDirection = BABYLON.Vector3.Zero();
  46844. this._transformedDirection = BABYLON.Vector3.Zero();
  46845. }
  46846. this.inputs.checkInputs();
  46847. _super.prototype._checkInputs.call(this);
  46848. };
  46849. FreeCamera.prototype._decideIfNeedsToMove = function () {
  46850. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  46851. };
  46852. FreeCamera.prototype._updatePosition = function () {
  46853. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  46854. this._collideWithWorld(this.cameraDirection);
  46855. }
  46856. else {
  46857. _super.prototype._updatePosition.call(this);
  46858. }
  46859. };
  46860. FreeCamera.prototype.dispose = function () {
  46861. this.inputs.clear();
  46862. _super.prototype.dispose.call(this);
  46863. };
  46864. FreeCamera.prototype.getClassName = function () {
  46865. return "FreeCamera";
  46866. };
  46867. __decorate([
  46868. BABYLON.serializeAsVector3()
  46869. ], FreeCamera.prototype, "ellipsoid", void 0);
  46870. __decorate([
  46871. BABYLON.serializeAsVector3()
  46872. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  46873. __decorate([
  46874. BABYLON.serialize()
  46875. ], FreeCamera.prototype, "checkCollisions", void 0);
  46876. __decorate([
  46877. BABYLON.serialize()
  46878. ], FreeCamera.prototype, "applyGravity", void 0);
  46879. return FreeCamera;
  46880. }(BABYLON.TargetCamera));
  46881. BABYLON.FreeCamera = FreeCamera;
  46882. })(BABYLON || (BABYLON = {}));
  46883. //# sourceMappingURL=babylon.freeCamera.js.map
  46884. var BABYLON;
  46885. (function (BABYLON) {
  46886. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  46887. function ArcRotateCameraKeyboardMoveInput() {
  46888. this._keys = new Array();
  46889. this.keysUp = [38];
  46890. this.keysDown = [40];
  46891. this.keysLeft = [37];
  46892. this.keysRight = [39];
  46893. this.keysReset = [220];
  46894. this.panningSensibility = 50.0;
  46895. this.zoomingSensibility = 25.0;
  46896. this.useAltToZoom = true;
  46897. }
  46898. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  46899. var _this = this;
  46900. if (this._onCanvasBlurObserver) {
  46901. return;
  46902. }
  46903. this._scene = this.camera.getScene();
  46904. this._engine = this._scene.getEngine();
  46905. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  46906. _this._keys = [];
  46907. });
  46908. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  46909. var evt = info.event;
  46910. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  46911. _this._ctrlPressed = evt.ctrlKey;
  46912. _this._altPressed = evt.altKey;
  46913. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46914. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46915. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46916. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  46917. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  46918. var index = _this._keys.indexOf(evt.keyCode);
  46919. if (index === -1) {
  46920. _this._keys.push(evt.keyCode);
  46921. }
  46922. if (evt.preventDefault) {
  46923. if (!noPreventDefault) {
  46924. evt.preventDefault();
  46925. }
  46926. }
  46927. }
  46928. }
  46929. else {
  46930. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46931. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46932. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46933. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  46934. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  46935. var index = _this._keys.indexOf(evt.keyCode);
  46936. if (index >= 0) {
  46937. _this._keys.splice(index, 1);
  46938. }
  46939. if (evt.preventDefault) {
  46940. if (!noPreventDefault) {
  46941. evt.preventDefault();
  46942. }
  46943. }
  46944. }
  46945. }
  46946. });
  46947. };
  46948. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  46949. if (this._scene) {
  46950. if (this._onKeyboardObserver) {
  46951. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  46952. }
  46953. if (this._onCanvasBlurObserver) {
  46954. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  46955. }
  46956. this._onKeyboardObserver = null;
  46957. this._onCanvasBlurObserver = null;
  46958. }
  46959. this._keys = [];
  46960. };
  46961. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  46962. if (this._onKeyboardObserver) {
  46963. var camera = this.camera;
  46964. for (var index = 0; index < this._keys.length; index++) {
  46965. var keyCode = this._keys[index];
  46966. if (this.keysLeft.indexOf(keyCode) !== -1) {
  46967. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46968. camera.inertialPanningX -= 1 / this.panningSensibility;
  46969. }
  46970. else {
  46971. camera.inertialAlphaOffset -= 0.01;
  46972. }
  46973. }
  46974. else if (this.keysUp.indexOf(keyCode) !== -1) {
  46975. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46976. camera.inertialPanningY += 1 / this.panningSensibility;
  46977. }
  46978. else if (this._altPressed && this.useAltToZoom) {
  46979. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  46980. }
  46981. else {
  46982. camera.inertialBetaOffset -= 0.01;
  46983. }
  46984. }
  46985. else if (this.keysRight.indexOf(keyCode) !== -1) {
  46986. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46987. camera.inertialPanningX += 1 / this.panningSensibility;
  46988. }
  46989. else {
  46990. camera.inertialAlphaOffset += 0.01;
  46991. }
  46992. }
  46993. else if (this.keysDown.indexOf(keyCode) !== -1) {
  46994. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46995. camera.inertialPanningY -= 1 / this.panningSensibility;
  46996. }
  46997. else if (this._altPressed && this.useAltToZoom) {
  46998. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  46999. }
  47000. else {
  47001. camera.inertialBetaOffset += 0.01;
  47002. }
  47003. }
  47004. else if (this.keysReset.indexOf(keyCode) !== -1) {
  47005. camera.restoreState();
  47006. }
  47007. }
  47008. }
  47009. };
  47010. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  47011. return "ArcRotateCameraKeyboardMoveInput";
  47012. };
  47013. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  47014. return "keyboard";
  47015. };
  47016. __decorate([
  47017. BABYLON.serialize()
  47018. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  47019. __decorate([
  47020. BABYLON.serialize()
  47021. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  47022. __decorate([
  47023. BABYLON.serialize()
  47024. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  47025. __decorate([
  47026. BABYLON.serialize()
  47027. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  47028. __decorate([
  47029. BABYLON.serialize()
  47030. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  47031. __decorate([
  47032. BABYLON.serialize()
  47033. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  47034. __decorate([
  47035. BABYLON.serialize()
  47036. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  47037. __decorate([
  47038. BABYLON.serialize()
  47039. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  47040. return ArcRotateCameraKeyboardMoveInput;
  47041. }());
  47042. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  47043. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  47044. })(BABYLON || (BABYLON = {}));
  47045. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  47046. var BABYLON;
  47047. (function (BABYLON) {
  47048. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  47049. function ArcRotateCameraMouseWheelInput() {
  47050. this.wheelPrecision = 3.0;
  47051. /**
  47052. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  47053. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  47054. */
  47055. this.wheelDeltaPercentage = 0;
  47056. }
  47057. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  47058. var _this = this;
  47059. this._wheel = function (p, s) {
  47060. //sanity check - this should be a PointerWheel event.
  47061. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  47062. return;
  47063. var event = p.event;
  47064. var delta = 0;
  47065. if (event.wheelDelta) {
  47066. if (_this.wheelDeltaPercentage) {
  47067. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  47068. if (event.wheelDelta > 0) {
  47069. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  47070. }
  47071. else {
  47072. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  47073. }
  47074. }
  47075. else {
  47076. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  47077. }
  47078. }
  47079. else if (event.detail) {
  47080. delta = -event.detail / _this.wheelPrecision;
  47081. }
  47082. if (delta)
  47083. _this.camera.inertialRadiusOffset += delta;
  47084. if (event.preventDefault) {
  47085. if (!noPreventDefault) {
  47086. event.preventDefault();
  47087. }
  47088. }
  47089. };
  47090. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  47091. };
  47092. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  47093. if (this._observer && element) {
  47094. this.camera.getScene().onPointerObservable.remove(this._observer);
  47095. this._observer = null;
  47096. this._wheel = null;
  47097. }
  47098. };
  47099. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  47100. return "ArcRotateCameraMouseWheelInput";
  47101. };
  47102. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  47103. return "mousewheel";
  47104. };
  47105. __decorate([
  47106. BABYLON.serialize()
  47107. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  47108. __decorate([
  47109. BABYLON.serialize()
  47110. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  47111. return ArcRotateCameraMouseWheelInput;
  47112. }());
  47113. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  47114. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  47115. })(BABYLON || (BABYLON = {}));
  47116. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  47117. var BABYLON;
  47118. (function (BABYLON) {
  47119. var ArcRotateCameraPointersInput = /** @class */ (function () {
  47120. function ArcRotateCameraPointersInput() {
  47121. this.buttons = [0, 1, 2];
  47122. this.angularSensibilityX = 1000.0;
  47123. this.angularSensibilityY = 1000.0;
  47124. this.pinchPrecision = 12.0;
  47125. /**
  47126. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  47127. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  47128. */
  47129. this.pinchDeltaPercentage = 0;
  47130. this.panningSensibility = 1000.0;
  47131. this.multiTouchPanning = true;
  47132. this.multiTouchPanAndZoom = true;
  47133. this._isPanClick = false;
  47134. this.pinchInwards = true;
  47135. }
  47136. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  47137. var _this = this;
  47138. var engine = this.camera.getEngine();
  47139. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  47140. var pointA = null;
  47141. var pointB = null;
  47142. var previousPinchSquaredDistance = 0;
  47143. var initialDistance = 0;
  47144. var twoFingerActivityCount = 0;
  47145. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  47146. this._pointerInput = function (p, s) {
  47147. var evt = p.event;
  47148. var isTouch = p.event.pointerType === "touch";
  47149. if (engine.isInVRExclusivePointerMode) {
  47150. return;
  47151. }
  47152. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  47153. return;
  47154. }
  47155. var srcElement = (evt.srcElement || evt.target);
  47156. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  47157. try {
  47158. srcElement.setPointerCapture(evt.pointerId);
  47159. }
  47160. catch (e) {
  47161. //Nothing to do with the error. Execution will continue.
  47162. }
  47163. // Manage panning with pan button click
  47164. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  47165. // manage pointers
  47166. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  47167. if (pointA === null) {
  47168. pointA = cacheSoloPointer;
  47169. }
  47170. else if (pointB === null) {
  47171. pointB = cacheSoloPointer;
  47172. }
  47173. if (!noPreventDefault) {
  47174. evt.preventDefault();
  47175. element.focus();
  47176. }
  47177. }
  47178. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  47179. _this.camera.restoreState();
  47180. }
  47181. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  47182. try {
  47183. srcElement.releasePointerCapture(evt.pointerId);
  47184. }
  47185. catch (e) {
  47186. //Nothing to do with the error.
  47187. }
  47188. cacheSoloPointer = null;
  47189. previousPinchSquaredDistance = 0;
  47190. previousMultiTouchPanPosition.isPaning = false;
  47191. previousMultiTouchPanPosition.isPinching = false;
  47192. twoFingerActivityCount = 0;
  47193. initialDistance = 0;
  47194. if (!isTouch) {
  47195. pointB = null; // Mouse and pen are mono pointer
  47196. }
  47197. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  47198. //but emptying completly pointers collection is required to fix a bug on iPhone :
  47199. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  47200. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  47201. if (engine._badOS) {
  47202. pointA = pointB = null;
  47203. }
  47204. else {
  47205. //only remove the impacted pointer in case of multitouch allowing on most
  47206. //platforms switching from rotate to zoom and pan seamlessly.
  47207. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  47208. pointA = pointB;
  47209. pointB = null;
  47210. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47211. }
  47212. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  47213. pointB = null;
  47214. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47215. }
  47216. else {
  47217. pointA = pointB = null;
  47218. }
  47219. }
  47220. if (!noPreventDefault) {
  47221. evt.preventDefault();
  47222. }
  47223. }
  47224. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  47225. if (!noPreventDefault) {
  47226. evt.preventDefault();
  47227. }
  47228. // One button down
  47229. if (pointA && pointB === null && cacheSoloPointer) {
  47230. if (_this.panningSensibility !== 0 &&
  47231. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  47232. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  47233. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  47234. }
  47235. else {
  47236. var offsetX = evt.clientX - cacheSoloPointer.x;
  47237. var offsetY = evt.clientY - cacheSoloPointer.y;
  47238. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47239. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47240. }
  47241. cacheSoloPointer.x = evt.clientX;
  47242. cacheSoloPointer.y = evt.clientY;
  47243. }
  47244. // Two buttons down: pinch/pan
  47245. else if (pointA && pointB) {
  47246. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  47247. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  47248. ed.x = evt.clientX;
  47249. ed.y = evt.clientY;
  47250. var direction = _this.pinchInwards ? 1 : -1;
  47251. var distX = pointA.x - pointB.x;
  47252. var distY = pointA.y - pointB.y;
  47253. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  47254. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  47255. if (previousPinchSquaredDistance === 0) {
  47256. initialDistance = pinchDistance;
  47257. previousPinchSquaredDistance = pinchSquaredDistance;
  47258. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  47259. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  47260. return;
  47261. }
  47262. if (_this.multiTouchPanAndZoom) {
  47263. if (_this.pinchDeltaPercentage) {
  47264. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47265. }
  47266. else {
  47267. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47268. (_this.pinchPrecision *
  47269. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47270. direction);
  47271. }
  47272. if (_this.panningSensibility !== 0) {
  47273. var pointersCenterX = (pointA.x + pointB.x) / 2;
  47274. var pointersCenterY = (pointA.y + pointB.y) / 2;
  47275. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  47276. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  47277. previousMultiTouchPanPosition.x = pointersCenterX;
  47278. previousMultiTouchPanPosition.y = pointersCenterY;
  47279. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  47280. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  47281. }
  47282. }
  47283. else {
  47284. twoFingerActivityCount++;
  47285. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  47286. if (_this.pinchDeltaPercentage) {
  47287. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47288. }
  47289. else {
  47290. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47291. (_this.pinchPrecision *
  47292. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47293. direction);
  47294. }
  47295. previousMultiTouchPanPosition.isPaning = false;
  47296. previousMultiTouchPanPosition.isPinching = true;
  47297. }
  47298. else {
  47299. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  47300. if (!previousMultiTouchPanPosition.isPaning) {
  47301. previousMultiTouchPanPosition.isPaning = true;
  47302. previousMultiTouchPanPosition.isPinching = false;
  47303. previousMultiTouchPanPosition.x = ed.x;
  47304. previousMultiTouchPanPosition.y = ed.y;
  47305. return;
  47306. }
  47307. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  47308. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  47309. }
  47310. }
  47311. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  47312. previousMultiTouchPanPosition.x = ed.x;
  47313. previousMultiTouchPanPosition.y = ed.y;
  47314. }
  47315. }
  47316. previousPinchSquaredDistance = pinchSquaredDistance;
  47317. }
  47318. }
  47319. };
  47320. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  47321. this._onContextMenu = function (evt) {
  47322. evt.preventDefault();
  47323. };
  47324. if (!this.camera._useCtrlForPanning) {
  47325. element.addEventListener("contextmenu", this._onContextMenu, false);
  47326. }
  47327. this._onLostFocus = function () {
  47328. //this._keys = [];
  47329. pointA = pointB = null;
  47330. previousPinchSquaredDistance = 0;
  47331. previousMultiTouchPanPosition.isPaning = false;
  47332. previousMultiTouchPanPosition.isPinching = false;
  47333. twoFingerActivityCount = 0;
  47334. cacheSoloPointer = null;
  47335. initialDistance = 0;
  47336. };
  47337. this._onMouseMove = function (evt) {
  47338. if (!engine.isPointerLock) {
  47339. return;
  47340. }
  47341. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  47342. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  47343. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47344. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47345. if (!noPreventDefault) {
  47346. evt.preventDefault();
  47347. }
  47348. };
  47349. this._onGestureStart = function (e) {
  47350. if (window.MSGesture === undefined) {
  47351. return;
  47352. }
  47353. if (!_this._MSGestureHandler) {
  47354. _this._MSGestureHandler = new MSGesture();
  47355. _this._MSGestureHandler.target = element;
  47356. }
  47357. _this._MSGestureHandler.addPointer(e.pointerId);
  47358. };
  47359. this._onGesture = function (e) {
  47360. _this.camera.radius *= e.scale;
  47361. if (e.preventDefault) {
  47362. if (!noPreventDefault) {
  47363. e.stopPropagation();
  47364. e.preventDefault();
  47365. }
  47366. }
  47367. };
  47368. element.addEventListener("mousemove", this._onMouseMove, false);
  47369. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  47370. element.addEventListener("MSGestureChange", this._onGesture, false);
  47371. BABYLON.Tools.RegisterTopRootEvents([
  47372. { name: "blur", handler: this._onLostFocus }
  47373. ]);
  47374. };
  47375. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  47376. if (this._onLostFocus) {
  47377. BABYLON.Tools.UnregisterTopRootEvents([
  47378. { name: "blur", handler: this._onLostFocus }
  47379. ]);
  47380. }
  47381. if (element && this._observer) {
  47382. this.camera.getScene().onPointerObservable.remove(this._observer);
  47383. this._observer = null;
  47384. if (this._onContextMenu) {
  47385. element.removeEventListener("contextmenu", this._onContextMenu);
  47386. }
  47387. if (this._onMouseMove) {
  47388. element.removeEventListener("mousemove", this._onMouseMove);
  47389. }
  47390. if (this._onGestureStart) {
  47391. element.removeEventListener("MSPointerDown", this._onGestureStart);
  47392. }
  47393. if (this._onGesture) {
  47394. element.removeEventListener("MSGestureChange", this._onGesture);
  47395. }
  47396. this._isPanClick = false;
  47397. this.pinchInwards = true;
  47398. this._onMouseMove = null;
  47399. this._onGestureStart = null;
  47400. this._onGesture = null;
  47401. this._MSGestureHandler = null;
  47402. this._onLostFocus = null;
  47403. this._onContextMenu = null;
  47404. }
  47405. };
  47406. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  47407. return "ArcRotateCameraPointersInput";
  47408. };
  47409. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  47410. return "pointers";
  47411. };
  47412. __decorate([
  47413. BABYLON.serialize()
  47414. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  47415. __decorate([
  47416. BABYLON.serialize()
  47417. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  47418. __decorate([
  47419. BABYLON.serialize()
  47420. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  47421. __decorate([
  47422. BABYLON.serialize()
  47423. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  47424. __decorate([
  47425. BABYLON.serialize()
  47426. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  47427. __decorate([
  47428. BABYLON.serialize()
  47429. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  47430. __decorate([
  47431. BABYLON.serialize()
  47432. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  47433. __decorate([
  47434. BABYLON.serialize()
  47435. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  47436. return ArcRotateCameraPointersInput;
  47437. }());
  47438. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  47439. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  47440. })(BABYLON || (BABYLON = {}));
  47441. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  47442. var BABYLON;
  47443. (function (BABYLON) {
  47444. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  47445. __extends(ArcRotateCameraInputsManager, _super);
  47446. function ArcRotateCameraInputsManager(camera) {
  47447. return _super.call(this, camera) || this;
  47448. }
  47449. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  47450. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  47451. return this;
  47452. };
  47453. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  47454. this.add(new BABYLON.ArcRotateCameraPointersInput());
  47455. return this;
  47456. };
  47457. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  47458. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  47459. return this;
  47460. };
  47461. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  47462. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  47463. return this;
  47464. };
  47465. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  47466. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  47467. return this;
  47468. };
  47469. return ArcRotateCameraInputsManager;
  47470. }(BABYLON.CameraInputsManager));
  47471. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  47472. })(BABYLON || (BABYLON = {}));
  47473. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  47474. var BABYLON;
  47475. (function (BABYLON) {
  47476. var ArcRotateCamera = /** @class */ (function (_super) {
  47477. __extends(ArcRotateCamera, _super);
  47478. function ArcRotateCamera(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive) {
  47479. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47480. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene, setActiveOnSceneIfNoneActive) || this;
  47481. _this.inertialAlphaOffset = 0;
  47482. _this.inertialBetaOffset = 0;
  47483. _this.inertialRadiusOffset = 0;
  47484. _this.lowerAlphaLimit = null;
  47485. _this.upperAlphaLimit = null;
  47486. _this.lowerBetaLimit = 0.01;
  47487. _this.upperBetaLimit = Math.PI;
  47488. _this.lowerRadiusLimit = null;
  47489. _this.upperRadiusLimit = null;
  47490. _this.inertialPanningX = 0;
  47491. _this.inertialPanningY = 0;
  47492. _this.pinchToPanMaxDistance = 20;
  47493. _this.panningDistanceLimit = null;
  47494. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  47495. _this.panningInertia = 0.9;
  47496. //-- end properties for backward compatibility for inputs
  47497. _this.zoomOnFactor = 1;
  47498. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  47499. _this.allowUpsideDown = true;
  47500. _this._viewMatrix = new BABYLON.Matrix();
  47501. // Panning
  47502. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  47503. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  47504. _this.checkCollisions = false;
  47505. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  47506. _this._previousPosition = BABYLON.Vector3.Zero();
  47507. _this._collisionVelocity = BABYLON.Vector3.Zero();
  47508. _this._newPosition = BABYLON.Vector3.Zero();
  47509. _this._computationVector = BABYLON.Vector3.Zero();
  47510. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  47511. if (collidedMesh === void 0) { collidedMesh = null; }
  47512. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  47513. newPosition.multiplyInPlace(_this._collider._radius);
  47514. }
  47515. if (!collidedMesh) {
  47516. _this._previousPosition.copyFrom(_this.position);
  47517. }
  47518. else {
  47519. _this.setPosition(newPosition);
  47520. if (_this.onCollide) {
  47521. _this.onCollide(collidedMesh);
  47522. }
  47523. }
  47524. // Recompute because of constraints
  47525. var cosa = Math.cos(_this.alpha);
  47526. var sina = Math.sin(_this.alpha);
  47527. var cosb = Math.cos(_this.beta);
  47528. var sinb = Math.sin(_this.beta);
  47529. if (sinb === 0) {
  47530. sinb = 0.0001;
  47531. }
  47532. var target = _this._getTargetPosition();
  47533. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  47534. target.addToRef(_this._computationVector, _this._newPosition);
  47535. _this.position.copyFrom(_this._newPosition);
  47536. var up = _this.upVector;
  47537. if (_this.allowUpsideDown && _this.beta < 0) {
  47538. up = up.clone();
  47539. up = up.negate();
  47540. }
  47541. _this._computeViewMatrix(_this.position, target, up);
  47542. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  47543. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  47544. _this._collisionTriggered = false;
  47545. };
  47546. _this._target = BABYLON.Vector3.Zero();
  47547. if (target) {
  47548. _this.setTarget(target);
  47549. }
  47550. _this.alpha = alpha;
  47551. _this.beta = beta;
  47552. _this.radius = radius;
  47553. _this.getViewMatrix();
  47554. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  47555. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  47556. return _this;
  47557. }
  47558. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  47559. get: function () {
  47560. return this._target;
  47561. },
  47562. set: function (value) {
  47563. this.setTarget(value);
  47564. },
  47565. enumerable: true,
  47566. configurable: true
  47567. });
  47568. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  47569. //-- begin properties for backward compatibility for inputs
  47570. get: function () {
  47571. var pointers = this.inputs.attached["pointers"];
  47572. if (pointers)
  47573. return pointers.angularSensibilityX;
  47574. return 0;
  47575. },
  47576. set: function (value) {
  47577. var pointers = this.inputs.attached["pointers"];
  47578. if (pointers) {
  47579. pointers.angularSensibilityX = value;
  47580. }
  47581. },
  47582. enumerable: true,
  47583. configurable: true
  47584. });
  47585. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  47586. get: function () {
  47587. var pointers = this.inputs.attached["pointers"];
  47588. if (pointers)
  47589. return pointers.angularSensibilityY;
  47590. return 0;
  47591. },
  47592. set: function (value) {
  47593. var pointers = this.inputs.attached["pointers"];
  47594. if (pointers) {
  47595. pointers.angularSensibilityY = value;
  47596. }
  47597. },
  47598. enumerable: true,
  47599. configurable: true
  47600. });
  47601. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  47602. get: function () {
  47603. var pointers = this.inputs.attached["pointers"];
  47604. if (pointers)
  47605. return pointers.pinchPrecision;
  47606. return 0;
  47607. },
  47608. set: function (value) {
  47609. var pointers = this.inputs.attached["pointers"];
  47610. if (pointers) {
  47611. pointers.pinchPrecision = value;
  47612. }
  47613. },
  47614. enumerable: true,
  47615. configurable: true
  47616. });
  47617. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  47618. get: function () {
  47619. var pointers = this.inputs.attached["pointers"];
  47620. if (pointers)
  47621. return pointers.pinchDeltaPercentage;
  47622. return 0;
  47623. },
  47624. set: function (value) {
  47625. var pointers = this.inputs.attached["pointers"];
  47626. if (pointers) {
  47627. pointers.pinchDeltaPercentage = value;
  47628. }
  47629. },
  47630. enumerable: true,
  47631. configurable: true
  47632. });
  47633. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  47634. get: function () {
  47635. var pointers = this.inputs.attached["pointers"];
  47636. if (pointers)
  47637. return pointers.panningSensibility;
  47638. return 0;
  47639. },
  47640. set: function (value) {
  47641. var pointers = this.inputs.attached["pointers"];
  47642. if (pointers) {
  47643. pointers.panningSensibility = value;
  47644. }
  47645. },
  47646. enumerable: true,
  47647. configurable: true
  47648. });
  47649. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  47650. get: function () {
  47651. var keyboard = this.inputs.attached["keyboard"];
  47652. if (keyboard)
  47653. return keyboard.keysUp;
  47654. return [];
  47655. },
  47656. set: function (value) {
  47657. var keyboard = this.inputs.attached["keyboard"];
  47658. if (keyboard)
  47659. keyboard.keysUp = value;
  47660. },
  47661. enumerable: true,
  47662. configurable: true
  47663. });
  47664. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  47665. get: function () {
  47666. var keyboard = this.inputs.attached["keyboard"];
  47667. if (keyboard)
  47668. return keyboard.keysDown;
  47669. return [];
  47670. },
  47671. set: function (value) {
  47672. var keyboard = this.inputs.attached["keyboard"];
  47673. if (keyboard)
  47674. keyboard.keysDown = value;
  47675. },
  47676. enumerable: true,
  47677. configurable: true
  47678. });
  47679. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  47680. get: function () {
  47681. var keyboard = this.inputs.attached["keyboard"];
  47682. if (keyboard)
  47683. return keyboard.keysLeft;
  47684. return [];
  47685. },
  47686. set: function (value) {
  47687. var keyboard = this.inputs.attached["keyboard"];
  47688. if (keyboard)
  47689. keyboard.keysLeft = value;
  47690. },
  47691. enumerable: true,
  47692. configurable: true
  47693. });
  47694. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  47695. get: function () {
  47696. var keyboard = this.inputs.attached["keyboard"];
  47697. if (keyboard)
  47698. return keyboard.keysRight;
  47699. return [];
  47700. },
  47701. set: function (value) {
  47702. var keyboard = this.inputs.attached["keyboard"];
  47703. if (keyboard)
  47704. keyboard.keysRight = value;
  47705. },
  47706. enumerable: true,
  47707. configurable: true
  47708. });
  47709. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  47710. get: function () {
  47711. var mousewheel = this.inputs.attached["mousewheel"];
  47712. if (mousewheel)
  47713. return mousewheel.wheelPrecision;
  47714. return 0;
  47715. },
  47716. set: function (value) {
  47717. var mousewheel = this.inputs.attached["mousewheel"];
  47718. if (mousewheel)
  47719. mousewheel.wheelPrecision = value;
  47720. },
  47721. enumerable: true,
  47722. configurable: true
  47723. });
  47724. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  47725. get: function () {
  47726. var mousewheel = this.inputs.attached["mousewheel"];
  47727. if (mousewheel)
  47728. return mousewheel.wheelDeltaPercentage;
  47729. return 0;
  47730. },
  47731. set: function (value) {
  47732. var mousewheel = this.inputs.attached["mousewheel"];
  47733. if (mousewheel)
  47734. mousewheel.wheelDeltaPercentage = value;
  47735. },
  47736. enumerable: true,
  47737. configurable: true
  47738. });
  47739. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  47740. get: function () {
  47741. return this._bouncingBehavior;
  47742. },
  47743. enumerable: true,
  47744. configurable: true
  47745. });
  47746. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  47747. get: function () {
  47748. return this._bouncingBehavior != null;
  47749. },
  47750. set: function (value) {
  47751. if (value === this.useBouncingBehavior) {
  47752. return;
  47753. }
  47754. if (value) {
  47755. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  47756. this.addBehavior(this._bouncingBehavior);
  47757. }
  47758. else if (this._bouncingBehavior) {
  47759. this.removeBehavior(this._bouncingBehavior);
  47760. this._bouncingBehavior = null;
  47761. }
  47762. },
  47763. enumerable: true,
  47764. configurable: true
  47765. });
  47766. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  47767. get: function () {
  47768. return this._framingBehavior;
  47769. },
  47770. enumerable: true,
  47771. configurable: true
  47772. });
  47773. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  47774. get: function () {
  47775. return this._framingBehavior != null;
  47776. },
  47777. set: function (value) {
  47778. if (value === this.useFramingBehavior) {
  47779. return;
  47780. }
  47781. if (value) {
  47782. this._framingBehavior = new BABYLON.FramingBehavior();
  47783. this.addBehavior(this._framingBehavior);
  47784. }
  47785. else if (this._framingBehavior) {
  47786. this.removeBehavior(this._framingBehavior);
  47787. this._framingBehavior = null;
  47788. }
  47789. },
  47790. enumerable: true,
  47791. configurable: true
  47792. });
  47793. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  47794. get: function () {
  47795. return this._autoRotationBehavior;
  47796. },
  47797. enumerable: true,
  47798. configurable: true
  47799. });
  47800. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  47801. get: function () {
  47802. return this._autoRotationBehavior != null;
  47803. },
  47804. set: function (value) {
  47805. if (value === this.useAutoRotationBehavior) {
  47806. return;
  47807. }
  47808. if (value) {
  47809. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  47810. this.addBehavior(this._autoRotationBehavior);
  47811. }
  47812. else if (this._autoRotationBehavior) {
  47813. this.removeBehavior(this._autoRotationBehavior);
  47814. this._autoRotationBehavior = null;
  47815. }
  47816. },
  47817. enumerable: true,
  47818. configurable: true
  47819. });
  47820. // Cache
  47821. ArcRotateCamera.prototype._initCache = function () {
  47822. _super.prototype._initCache.call(this);
  47823. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47824. this._cache.alpha = undefined;
  47825. this._cache.beta = undefined;
  47826. this._cache.radius = undefined;
  47827. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  47828. };
  47829. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  47830. if (!ignoreParentClass) {
  47831. _super.prototype._updateCache.call(this);
  47832. }
  47833. this._cache._target.copyFrom(this._getTargetPosition());
  47834. this._cache.alpha = this.alpha;
  47835. this._cache.beta = this.beta;
  47836. this._cache.radius = this.radius;
  47837. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  47838. };
  47839. ArcRotateCamera.prototype._getTargetPosition = function () {
  47840. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  47841. var pos = this._targetHost.getAbsolutePosition();
  47842. if (this._targetBoundingCenter) {
  47843. pos.addToRef(this._targetBoundingCenter, this._target);
  47844. }
  47845. else {
  47846. this._target.copyFrom(pos);
  47847. }
  47848. }
  47849. var lockedTargetPosition = this._getLockedTargetPosition();
  47850. if (lockedTargetPosition) {
  47851. return lockedTargetPosition;
  47852. }
  47853. return this._target;
  47854. };
  47855. ArcRotateCamera.prototype.storeState = function () {
  47856. this._storedAlpha = this.alpha;
  47857. this._storedBeta = this.beta;
  47858. this._storedRadius = this.radius;
  47859. this._storedTarget = this._getTargetPosition().clone();
  47860. return _super.prototype.storeState.call(this);
  47861. };
  47862. /**
  47863. * Restored camera state. You must call storeState() first
  47864. */
  47865. ArcRotateCamera.prototype._restoreStateValues = function () {
  47866. if (!_super.prototype._restoreStateValues.call(this)) {
  47867. return false;
  47868. }
  47869. this.alpha = this._storedAlpha;
  47870. this.beta = this._storedBeta;
  47871. this.radius = this._storedRadius;
  47872. this.setTarget(this._storedTarget.clone());
  47873. this.inertialAlphaOffset = 0;
  47874. this.inertialBetaOffset = 0;
  47875. this.inertialRadiusOffset = 0;
  47876. this.inertialPanningX = 0;
  47877. this.inertialPanningY = 0;
  47878. return true;
  47879. };
  47880. // Synchronized
  47881. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  47882. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  47883. return false;
  47884. return this._cache._target.equals(this._getTargetPosition())
  47885. && this._cache.alpha === this.alpha
  47886. && this._cache.beta === this.beta
  47887. && this._cache.radius === this.radius
  47888. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  47889. };
  47890. // Methods
  47891. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  47892. var _this = this;
  47893. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  47894. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  47895. this._useCtrlForPanning = useCtrlForPanning;
  47896. this._panningMouseButton = panningMouseButton;
  47897. this.inputs.attachElement(element, noPreventDefault);
  47898. this._reset = function () {
  47899. _this.inertialAlphaOffset = 0;
  47900. _this.inertialBetaOffset = 0;
  47901. _this.inertialRadiusOffset = 0;
  47902. _this.inertialPanningX = 0;
  47903. _this.inertialPanningY = 0;
  47904. };
  47905. };
  47906. ArcRotateCamera.prototype.detachControl = function (element) {
  47907. this.inputs.detachElement(element);
  47908. if (this._reset) {
  47909. this._reset();
  47910. }
  47911. };
  47912. ArcRotateCamera.prototype._checkInputs = function () {
  47913. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  47914. if (this._collisionTriggered) {
  47915. return;
  47916. }
  47917. this.inputs.checkInputs();
  47918. // Inertia
  47919. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  47920. var inertialAlphaOffset = this.inertialAlphaOffset;
  47921. if (this.beta <= 0)
  47922. inertialAlphaOffset *= -1;
  47923. if (this.getScene().useRightHandedSystem)
  47924. inertialAlphaOffset *= -1;
  47925. if (this.parent && this.parent._getWorldMatrixDeterminant() < 0)
  47926. inertialAlphaOffset *= -1;
  47927. this.alpha += inertialAlphaOffset;
  47928. this.beta += this.inertialBetaOffset;
  47929. this.radius -= this.inertialRadiusOffset;
  47930. this.inertialAlphaOffset *= this.inertia;
  47931. this.inertialBetaOffset *= this.inertia;
  47932. this.inertialRadiusOffset *= this.inertia;
  47933. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  47934. this.inertialAlphaOffset = 0;
  47935. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  47936. this.inertialBetaOffset = 0;
  47937. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  47938. this.inertialRadiusOffset = 0;
  47939. }
  47940. // Panning inertia
  47941. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  47942. if (!this._localDirection) {
  47943. this._localDirection = BABYLON.Vector3.Zero();
  47944. this._transformedDirection = BABYLON.Vector3.Zero();
  47945. }
  47946. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  47947. this._localDirection.multiplyInPlace(this.panningAxis);
  47948. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  47949. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  47950. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  47951. if (!this.panningAxis.y) {
  47952. this._transformedDirection.y = 0;
  47953. }
  47954. if (!this._targetHost) {
  47955. if (this.panningDistanceLimit) {
  47956. this._transformedDirection.addInPlace(this._target);
  47957. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  47958. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  47959. this._target.copyFrom(this._transformedDirection);
  47960. }
  47961. }
  47962. else {
  47963. this._target.addInPlace(this._transformedDirection);
  47964. }
  47965. }
  47966. this.inertialPanningX *= this.panningInertia;
  47967. this.inertialPanningY *= this.panningInertia;
  47968. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  47969. this.inertialPanningX = 0;
  47970. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  47971. this.inertialPanningY = 0;
  47972. }
  47973. // Limits
  47974. this._checkLimits();
  47975. _super.prototype._checkInputs.call(this);
  47976. };
  47977. ArcRotateCamera.prototype._checkLimits = function () {
  47978. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  47979. if (this.allowUpsideDown && this.beta > Math.PI) {
  47980. this.beta = this.beta - (2 * Math.PI);
  47981. }
  47982. }
  47983. else {
  47984. if (this.beta < this.lowerBetaLimit) {
  47985. this.beta = this.lowerBetaLimit;
  47986. }
  47987. }
  47988. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  47989. if (this.allowUpsideDown && this.beta < -Math.PI) {
  47990. this.beta = this.beta + (2 * Math.PI);
  47991. }
  47992. }
  47993. else {
  47994. if (this.beta > this.upperBetaLimit) {
  47995. this.beta = this.upperBetaLimit;
  47996. }
  47997. }
  47998. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  47999. this.alpha = this.lowerAlphaLimit;
  48000. }
  48001. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  48002. this.alpha = this.upperAlphaLimit;
  48003. }
  48004. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  48005. this.radius = this.lowerRadiusLimit;
  48006. }
  48007. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  48008. this.radius = this.upperRadiusLimit;
  48009. }
  48010. };
  48011. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  48012. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  48013. this.radius = this._computationVector.length();
  48014. if (this.radius === 0) {
  48015. this.radius = 0.0001; // Just to avoid division by zero
  48016. }
  48017. // Alpha
  48018. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  48019. if (this._computationVector.z < 0) {
  48020. this.alpha = 2 * Math.PI - this.alpha;
  48021. }
  48022. // Beta
  48023. this.beta = Math.acos(this._computationVector.y / this.radius);
  48024. this._checkLimits();
  48025. };
  48026. ArcRotateCamera.prototype.setPosition = function (position) {
  48027. if (this.position.equals(position)) {
  48028. return;
  48029. }
  48030. this.position.copyFrom(position);
  48031. this.rebuildAnglesAndRadius();
  48032. };
  48033. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  48034. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  48035. if (allowSamePosition === void 0) { allowSamePosition = false; }
  48036. if (target.getBoundingInfo) {
  48037. if (toBoundingCenter) {
  48038. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  48039. }
  48040. else {
  48041. this._targetBoundingCenter = null;
  48042. }
  48043. this._targetHost = target;
  48044. this._target = this._getTargetPosition();
  48045. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  48046. }
  48047. else {
  48048. var newTarget = target;
  48049. var currentTarget = this._getTargetPosition();
  48050. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  48051. return;
  48052. }
  48053. this._targetHost = null;
  48054. this._target = newTarget;
  48055. this._targetBoundingCenter = null;
  48056. this.onMeshTargetChangedObservable.notifyObservers(null);
  48057. }
  48058. this.rebuildAnglesAndRadius();
  48059. };
  48060. ArcRotateCamera.prototype._getViewMatrix = function () {
  48061. // Compute
  48062. var cosa = Math.cos(this.alpha);
  48063. var sina = Math.sin(this.alpha);
  48064. var cosb = Math.cos(this.beta);
  48065. var sinb = Math.sin(this.beta);
  48066. if (sinb === 0) {
  48067. sinb = 0.0001;
  48068. }
  48069. var target = this._getTargetPosition();
  48070. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  48071. target.addToRef(this._computationVector, this._newPosition);
  48072. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  48073. if (!this._collider) {
  48074. this._collider = new BABYLON.Collider();
  48075. }
  48076. this._collider._radius = this.collisionRadius;
  48077. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  48078. this._collisionTriggered = true;
  48079. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  48080. }
  48081. else {
  48082. this.position.copyFrom(this._newPosition);
  48083. var up = this.upVector;
  48084. if (this.allowUpsideDown && sinb < 0) {
  48085. up = up.clone();
  48086. up = up.negate();
  48087. }
  48088. this._computeViewMatrix(this.position, target, up);
  48089. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  48090. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  48091. }
  48092. this._currentTarget = target;
  48093. return this._viewMatrix;
  48094. };
  48095. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  48096. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48097. meshes = meshes || this.getScene().meshes;
  48098. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  48099. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  48100. this.radius = distance * this.zoomOnFactor;
  48101. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  48102. };
  48103. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  48104. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48105. var meshesOrMinMaxVector;
  48106. var distance;
  48107. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  48108. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  48109. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  48110. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  48111. }
  48112. else { //minMaxVector and distance
  48113. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  48114. meshesOrMinMaxVector = minMaxVectorAndDistance;
  48115. distance = minMaxVectorAndDistance.distance;
  48116. }
  48117. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  48118. if (!doNotUpdateMaxZ) {
  48119. this.maxZ = distance * 2;
  48120. }
  48121. };
  48122. /**
  48123. * @override
  48124. * Override Camera.createRigCamera
  48125. */
  48126. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  48127. var alphaShift = 0;
  48128. switch (this.cameraRigMode) {
  48129. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48130. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48131. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48132. case BABYLON.Camera.RIG_MODE_VR:
  48133. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  48134. break;
  48135. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48136. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  48137. break;
  48138. }
  48139. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  48140. rigCam._cameraRigParams = {};
  48141. return rigCam;
  48142. };
  48143. /**
  48144. * @override
  48145. * Override Camera._updateRigCameras
  48146. */
  48147. ArcRotateCamera.prototype._updateRigCameras = function () {
  48148. var camLeft = this._rigCameras[0];
  48149. var camRight = this._rigCameras[1];
  48150. camLeft.beta = camRight.beta = this.beta;
  48151. camLeft.radius = camRight.radius = this.radius;
  48152. switch (this.cameraRigMode) {
  48153. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48154. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48155. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48156. case BABYLON.Camera.RIG_MODE_VR:
  48157. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48158. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48159. break;
  48160. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48161. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48162. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48163. break;
  48164. }
  48165. _super.prototype._updateRigCameras.call(this);
  48166. };
  48167. ArcRotateCamera.prototype.dispose = function () {
  48168. this.inputs.clear();
  48169. _super.prototype.dispose.call(this);
  48170. };
  48171. ArcRotateCamera.prototype.getClassName = function () {
  48172. return "ArcRotateCamera";
  48173. };
  48174. __decorate([
  48175. BABYLON.serialize()
  48176. ], ArcRotateCamera.prototype, "alpha", void 0);
  48177. __decorate([
  48178. BABYLON.serialize()
  48179. ], ArcRotateCamera.prototype, "beta", void 0);
  48180. __decorate([
  48181. BABYLON.serialize()
  48182. ], ArcRotateCamera.prototype, "radius", void 0);
  48183. __decorate([
  48184. BABYLON.serializeAsVector3("target")
  48185. ], ArcRotateCamera.prototype, "_target", void 0);
  48186. __decorate([
  48187. BABYLON.serialize()
  48188. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  48189. __decorate([
  48190. BABYLON.serialize()
  48191. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  48192. __decorate([
  48193. BABYLON.serialize()
  48194. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  48195. __decorate([
  48196. BABYLON.serialize()
  48197. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  48198. __decorate([
  48199. BABYLON.serialize()
  48200. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  48201. __decorate([
  48202. BABYLON.serialize()
  48203. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  48204. __decorate([
  48205. BABYLON.serialize()
  48206. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  48207. __decorate([
  48208. BABYLON.serialize()
  48209. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  48210. __decorate([
  48211. BABYLON.serialize()
  48212. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  48213. __decorate([
  48214. BABYLON.serialize()
  48215. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  48216. __decorate([
  48217. BABYLON.serialize()
  48218. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  48219. __decorate([
  48220. BABYLON.serialize()
  48221. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  48222. __decorate([
  48223. BABYLON.serialize()
  48224. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  48225. __decorate([
  48226. BABYLON.serializeAsVector3()
  48227. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  48228. __decorate([
  48229. BABYLON.serialize()
  48230. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  48231. __decorate([
  48232. BABYLON.serialize()
  48233. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  48234. __decorate([
  48235. BABYLON.serialize()
  48236. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  48237. return ArcRotateCamera;
  48238. }(BABYLON.TargetCamera));
  48239. BABYLON.ArcRotateCamera = ArcRotateCamera;
  48240. })(BABYLON || (BABYLON = {}));
  48241. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  48242. var BABYLON;
  48243. (function (BABYLON) {
  48244. /**
  48245. * The HemisphericLight simulates the ambient environment light,
  48246. * so the passed direction is the light reflection direction, not the incoming direction.
  48247. */
  48248. var HemisphericLight = /** @class */ (function (_super) {
  48249. __extends(HemisphericLight, _super);
  48250. /**
  48251. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  48252. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  48253. * The HemisphericLight can't cast shadows.
  48254. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48255. * @param name The friendly name of the light
  48256. * @param direction The direction of the light reflection
  48257. * @param scene The scene the light belongs to
  48258. */
  48259. function HemisphericLight(name, direction, scene) {
  48260. var _this = _super.call(this, name, scene) || this;
  48261. /**
  48262. * The groundColor is the light in the opposite direction to the one specified during creation.
  48263. * 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.
  48264. */
  48265. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  48266. _this.direction = direction || BABYLON.Vector3.Up();
  48267. return _this;
  48268. }
  48269. HemisphericLight.prototype._buildUniformLayout = function () {
  48270. this._uniformBuffer.addUniform("vLightData", 4);
  48271. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48272. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48273. this._uniformBuffer.addUniform("vLightGround", 3);
  48274. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48275. this._uniformBuffer.addUniform("depthValues", 2);
  48276. this._uniformBuffer.create();
  48277. };
  48278. /**
  48279. * Returns the string "HemisphericLight".
  48280. * @return The class name
  48281. */
  48282. HemisphericLight.prototype.getClassName = function () {
  48283. return "HemisphericLight";
  48284. };
  48285. /**
  48286. * Sets the HemisphericLight direction towards the passed target (Vector3).
  48287. * Returns the updated direction.
  48288. * @param target The target the direction should point to
  48289. * @return The computed direction
  48290. */
  48291. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  48292. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  48293. return this.direction;
  48294. };
  48295. /**
  48296. * Returns the shadow generator associated to the light.
  48297. * @returns Always null for hemispheric lights because it does not support shadows.
  48298. */
  48299. HemisphericLight.prototype.getShadowGenerator = function () {
  48300. return null;
  48301. };
  48302. /**
  48303. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  48304. * @param effect The effect to update
  48305. * @param lightIndex The index of the light in the effect to update
  48306. * @returns The hemispheric light
  48307. */
  48308. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  48309. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  48310. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  48311. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  48312. return this;
  48313. };
  48314. /**
  48315. * @hidden internal use only.
  48316. */
  48317. HemisphericLight.prototype._getWorldMatrix = function () {
  48318. if (!this._worldMatrix) {
  48319. this._worldMatrix = BABYLON.Matrix.Identity();
  48320. }
  48321. return this._worldMatrix;
  48322. };
  48323. /**
  48324. * Returns the integer 3.
  48325. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48326. */
  48327. HemisphericLight.prototype.getTypeID = function () {
  48328. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  48329. };
  48330. __decorate([
  48331. BABYLON.serializeAsColor3()
  48332. ], HemisphericLight.prototype, "groundColor", void 0);
  48333. __decorate([
  48334. BABYLON.serializeAsVector3()
  48335. ], HemisphericLight.prototype, "direction", void 0);
  48336. return HemisphericLight;
  48337. }(BABYLON.Light));
  48338. BABYLON.HemisphericLight = HemisphericLight;
  48339. })(BABYLON || (BABYLON = {}));
  48340. //# sourceMappingURL=babylon.hemisphericLight.js.map
  48341. var BABYLON;
  48342. (function (BABYLON) {
  48343. /**
  48344. * Base implementation IShadowLight
  48345. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  48346. */
  48347. var ShadowLight = /** @class */ (function (_super) {
  48348. __extends(ShadowLight, _super);
  48349. function ShadowLight() {
  48350. var _this = _super !== null && _super.apply(this, arguments) || this;
  48351. _this._needProjectionMatrixCompute = true;
  48352. return _this;
  48353. }
  48354. ShadowLight.prototype._setPosition = function (value) {
  48355. this._position = value;
  48356. };
  48357. Object.defineProperty(ShadowLight.prototype, "position", {
  48358. /**
  48359. * Sets the position the shadow will be casted from. Also use as the light position for both
  48360. * point and spot lights.
  48361. */
  48362. get: function () {
  48363. return this._position;
  48364. },
  48365. /**
  48366. * Sets the position the shadow will be casted from. Also use as the light position for both
  48367. * point and spot lights.
  48368. */
  48369. set: function (value) {
  48370. this._setPosition(value);
  48371. },
  48372. enumerable: true,
  48373. configurable: true
  48374. });
  48375. ShadowLight.prototype._setDirection = function (value) {
  48376. this._direction = value;
  48377. };
  48378. Object.defineProperty(ShadowLight.prototype, "direction", {
  48379. /**
  48380. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  48381. * Also use as the light direction on spot and directional lights.
  48382. */
  48383. get: function () {
  48384. return this._direction;
  48385. },
  48386. /**
  48387. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  48388. * Also use as the light direction on spot and directional lights.
  48389. */
  48390. set: function (value) {
  48391. this._setDirection(value);
  48392. },
  48393. enumerable: true,
  48394. configurable: true
  48395. });
  48396. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  48397. /**
  48398. * Gets the shadow projection clipping minimum z value.
  48399. */
  48400. get: function () {
  48401. return this._shadowMinZ;
  48402. },
  48403. /**
  48404. * Sets the shadow projection clipping minimum z value.
  48405. */
  48406. set: function (value) {
  48407. this._shadowMinZ = value;
  48408. this.forceProjectionMatrixCompute();
  48409. },
  48410. enumerable: true,
  48411. configurable: true
  48412. });
  48413. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  48414. /**
  48415. * Sets the shadow projection clipping maximum z value.
  48416. */
  48417. get: function () {
  48418. return this._shadowMaxZ;
  48419. },
  48420. /**
  48421. * Gets the shadow projection clipping maximum z value.
  48422. */
  48423. set: function (value) {
  48424. this._shadowMaxZ = value;
  48425. this.forceProjectionMatrixCompute();
  48426. },
  48427. enumerable: true,
  48428. configurable: true
  48429. });
  48430. /**
  48431. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  48432. * @returns true if the information has been computed, false if it does not need to (no parenting)
  48433. */
  48434. ShadowLight.prototype.computeTransformedInformation = function () {
  48435. if (this.parent && this.parent.getWorldMatrix) {
  48436. if (!this.transformedPosition) {
  48437. this.transformedPosition = BABYLON.Vector3.Zero();
  48438. }
  48439. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  48440. // In case the direction is present.
  48441. if (this.direction) {
  48442. if (!this.transformedDirection) {
  48443. this.transformedDirection = BABYLON.Vector3.Zero();
  48444. }
  48445. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  48446. }
  48447. return true;
  48448. }
  48449. return false;
  48450. };
  48451. /**
  48452. * Return the depth scale used for the shadow map.
  48453. * @returns the depth scale.
  48454. */
  48455. ShadowLight.prototype.getDepthScale = function () {
  48456. return 50.0;
  48457. };
  48458. /**
  48459. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  48460. * @param faceIndex The index of the face we are computed the direction to generate shadow
  48461. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  48462. */
  48463. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  48464. return this.transformedDirection ? this.transformedDirection : this.direction;
  48465. };
  48466. /**
  48467. * Returns the ShadowLight absolute position in the World.
  48468. * @returns the position vector in world space
  48469. */
  48470. ShadowLight.prototype.getAbsolutePosition = function () {
  48471. return this.transformedPosition ? this.transformedPosition : this.position;
  48472. };
  48473. /**
  48474. * Sets the ShadowLight direction toward the passed target.
  48475. * @param target The point tot target in local space
  48476. * @returns the updated ShadowLight direction
  48477. */
  48478. ShadowLight.prototype.setDirectionToTarget = function (target) {
  48479. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  48480. return this.direction;
  48481. };
  48482. /**
  48483. * Returns the light rotation in euler definition.
  48484. * @returns the x y z rotation in local space.
  48485. */
  48486. ShadowLight.prototype.getRotation = function () {
  48487. this.direction.normalize();
  48488. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  48489. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  48490. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  48491. };
  48492. /**
  48493. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  48494. * @returns true if a cube texture needs to be use
  48495. */
  48496. ShadowLight.prototype.needCube = function () {
  48497. return false;
  48498. };
  48499. /**
  48500. * Detects if the projection matrix requires to be recomputed this frame.
  48501. * @returns true if it requires to be recomputed otherwise, false.
  48502. */
  48503. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  48504. return this._needProjectionMatrixCompute;
  48505. };
  48506. /**
  48507. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  48508. */
  48509. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  48510. this._needProjectionMatrixCompute = true;
  48511. };
  48512. /**
  48513. * Get the world matrix of the sahdow lights.
  48514. * @hidden Internal Use Only
  48515. */
  48516. ShadowLight.prototype._getWorldMatrix = function () {
  48517. if (!this._worldMatrix) {
  48518. this._worldMatrix = BABYLON.Matrix.Identity();
  48519. }
  48520. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  48521. return this._worldMatrix;
  48522. };
  48523. /**
  48524. * Gets the minZ used for shadow according to both the scene and the light.
  48525. * @param activeCamera The camera we are returning the min for
  48526. * @returns the depth min z
  48527. */
  48528. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  48529. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  48530. };
  48531. /**
  48532. * Gets the maxZ used for shadow according to both the scene and the light.
  48533. * @param activeCamera The camera we are returning the max for
  48534. * @returns the depth max z
  48535. */
  48536. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  48537. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  48538. };
  48539. /**
  48540. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  48541. * @param matrix The materix to updated with the projection information
  48542. * @param viewMatrix The transform matrix of the light
  48543. * @param renderList The list of mesh to render in the map
  48544. * @returns The current light
  48545. */
  48546. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48547. if (this.customProjectionMatrixBuilder) {
  48548. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  48549. }
  48550. else {
  48551. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  48552. }
  48553. return this;
  48554. };
  48555. __decorate([
  48556. BABYLON.serializeAsVector3()
  48557. ], ShadowLight.prototype, "position", null);
  48558. __decorate([
  48559. BABYLON.serializeAsVector3()
  48560. ], ShadowLight.prototype, "direction", null);
  48561. __decorate([
  48562. BABYLON.serialize()
  48563. ], ShadowLight.prototype, "shadowMinZ", null);
  48564. __decorate([
  48565. BABYLON.serialize()
  48566. ], ShadowLight.prototype, "shadowMaxZ", null);
  48567. return ShadowLight;
  48568. }(BABYLON.Light));
  48569. BABYLON.ShadowLight = ShadowLight;
  48570. })(BABYLON || (BABYLON = {}));
  48571. //# sourceMappingURL=babylon.shadowLight.js.map
  48572. var BABYLON;
  48573. (function (BABYLON) {
  48574. /**
  48575. * A point light is a light defined by an unique point in world space.
  48576. * The light is emitted in every direction from this point.
  48577. * A good example of a point light is a standard light bulb.
  48578. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48579. */
  48580. var PointLight = /** @class */ (function (_super) {
  48581. __extends(PointLight, _super);
  48582. /**
  48583. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  48584. * A PointLight emits the light in every direction.
  48585. * It can cast shadows.
  48586. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  48587. * ```javascript
  48588. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  48589. * ```
  48590. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48591. * @param name The light friendly name
  48592. * @param position The position of the point light in the scene
  48593. * @param scene The scene the lights belongs to
  48594. */
  48595. function PointLight(name, position, scene) {
  48596. var _this = _super.call(this, name, scene) || this;
  48597. _this._shadowAngle = Math.PI / 2;
  48598. _this.position = position;
  48599. return _this;
  48600. }
  48601. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  48602. /**
  48603. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48604. * This specifies what angle the shadow will use to be created.
  48605. *
  48606. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  48607. */
  48608. get: function () {
  48609. return this._shadowAngle;
  48610. },
  48611. /**
  48612. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48613. * This specifies what angle the shadow will use to be created.
  48614. *
  48615. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  48616. */
  48617. set: function (value) {
  48618. this._shadowAngle = value;
  48619. this.forceProjectionMatrixCompute();
  48620. },
  48621. enumerable: true,
  48622. configurable: true
  48623. });
  48624. Object.defineProperty(PointLight.prototype, "direction", {
  48625. /**
  48626. * Gets the direction if it has been set.
  48627. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48628. */
  48629. get: function () {
  48630. return this._direction;
  48631. },
  48632. /**
  48633. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48634. */
  48635. set: function (value) {
  48636. var previousNeedCube = this.needCube();
  48637. this._direction = value;
  48638. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  48639. this._shadowGenerator.recreateShadowMap();
  48640. }
  48641. },
  48642. enumerable: true,
  48643. configurable: true
  48644. });
  48645. /**
  48646. * Returns the string "PointLight"
  48647. * @returns the class name
  48648. */
  48649. PointLight.prototype.getClassName = function () {
  48650. return "PointLight";
  48651. };
  48652. /**
  48653. * Returns the integer 0.
  48654. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48655. */
  48656. PointLight.prototype.getTypeID = function () {
  48657. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  48658. };
  48659. /**
  48660. * Specifies wether or not the shadowmap should be a cube texture.
  48661. * @returns true if the shadowmap needs to be a cube texture.
  48662. */
  48663. PointLight.prototype.needCube = function () {
  48664. return !this.direction;
  48665. };
  48666. /**
  48667. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  48668. * @param faceIndex The index of the face we are computed the direction to generate shadow
  48669. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  48670. */
  48671. PointLight.prototype.getShadowDirection = function (faceIndex) {
  48672. if (this.direction) {
  48673. return _super.prototype.getShadowDirection.call(this, faceIndex);
  48674. }
  48675. else {
  48676. switch (faceIndex) {
  48677. case 0:
  48678. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  48679. case 1:
  48680. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  48681. case 2:
  48682. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  48683. case 3:
  48684. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  48685. case 4:
  48686. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  48687. case 5:
  48688. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  48689. }
  48690. }
  48691. return BABYLON.Vector3.Zero();
  48692. };
  48693. /**
  48694. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  48695. * - fov = PI / 2
  48696. * - aspect ratio : 1.0
  48697. * - z-near and far equal to the active camera minZ and maxZ.
  48698. * Returns the PointLight.
  48699. */
  48700. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48701. var activeCamera = this.getScene().activeCamera;
  48702. if (!activeCamera) {
  48703. return;
  48704. }
  48705. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  48706. };
  48707. PointLight.prototype._buildUniformLayout = function () {
  48708. this._uniformBuffer.addUniform("vLightData", 4);
  48709. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48710. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48711. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48712. this._uniformBuffer.addUniform("depthValues", 2);
  48713. this._uniformBuffer.create();
  48714. };
  48715. /**
  48716. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  48717. * @param effect The effect to update
  48718. * @param lightIndex The index of the light in the effect to update
  48719. * @returns The point light
  48720. */
  48721. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  48722. if (this.computeTransformedInformation()) {
  48723. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  48724. return this;
  48725. }
  48726. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  48727. return this;
  48728. };
  48729. __decorate([
  48730. BABYLON.serialize()
  48731. ], PointLight.prototype, "shadowAngle", null);
  48732. return PointLight;
  48733. }(BABYLON.ShadowLight));
  48734. BABYLON.PointLight = PointLight;
  48735. })(BABYLON || (BABYLON = {}));
  48736. //# sourceMappingURL=babylon.pointLight.js.map
  48737. var BABYLON;
  48738. (function (BABYLON) {
  48739. /**
  48740. * A directional light is defined by a direction (what a surprise!).
  48741. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  48742. * 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.
  48743. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48744. */
  48745. var DirectionalLight = /** @class */ (function (_super) {
  48746. __extends(DirectionalLight, _super);
  48747. /**
  48748. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  48749. * The directional light is emitted from everywhere in the given direction.
  48750. * It can cast shawdows.
  48751. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48752. * @param name The friendly name of the light
  48753. * @param direction The direction of the light
  48754. * @param scene The scene the light belongs to
  48755. */
  48756. function DirectionalLight(name, direction, scene) {
  48757. var _this = _super.call(this, name, scene) || this;
  48758. _this._shadowFrustumSize = 0;
  48759. _this._shadowOrthoScale = 0.1;
  48760. /**
  48761. * Automatically compute the projection matrix to best fit (including all the casters)
  48762. * on each frame.
  48763. */
  48764. _this.autoUpdateExtends = true;
  48765. // Cache
  48766. _this._orthoLeft = Number.MAX_VALUE;
  48767. _this._orthoRight = Number.MIN_VALUE;
  48768. _this._orthoTop = Number.MIN_VALUE;
  48769. _this._orthoBottom = Number.MAX_VALUE;
  48770. _this.position = direction.scale(-1.0);
  48771. _this.direction = direction;
  48772. return _this;
  48773. }
  48774. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  48775. /**
  48776. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  48777. */
  48778. get: function () {
  48779. return this._shadowFrustumSize;
  48780. },
  48781. /**
  48782. * Specifies a fix frustum size for the shadow generation.
  48783. */
  48784. set: function (value) {
  48785. this._shadowFrustumSize = value;
  48786. this.forceProjectionMatrixCompute();
  48787. },
  48788. enumerable: true,
  48789. configurable: true
  48790. });
  48791. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  48792. /**
  48793. * Gets the shadow projection scale against the optimal computed one.
  48794. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  48795. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  48796. */
  48797. get: function () {
  48798. return this._shadowOrthoScale;
  48799. },
  48800. /**
  48801. * Sets the shadow projection scale against the optimal computed one.
  48802. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  48803. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  48804. */
  48805. set: function (value) {
  48806. this._shadowOrthoScale = value;
  48807. this.forceProjectionMatrixCompute();
  48808. },
  48809. enumerable: true,
  48810. configurable: true
  48811. });
  48812. /**
  48813. * Returns the string "DirectionalLight".
  48814. * @return The class name
  48815. */
  48816. DirectionalLight.prototype.getClassName = function () {
  48817. return "DirectionalLight";
  48818. };
  48819. /**
  48820. * Returns the integer 1.
  48821. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48822. */
  48823. DirectionalLight.prototype.getTypeID = function () {
  48824. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  48825. };
  48826. /**
  48827. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  48828. * Returns the DirectionalLight Shadow projection matrix.
  48829. */
  48830. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48831. if (this.shadowFrustumSize > 0) {
  48832. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  48833. }
  48834. else {
  48835. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  48836. }
  48837. };
  48838. /**
  48839. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  48840. * Returns the DirectionalLight Shadow projection matrix.
  48841. */
  48842. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  48843. var activeCamera = this.getScene().activeCamera;
  48844. if (!activeCamera) {
  48845. return;
  48846. }
  48847. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  48848. };
  48849. /**
  48850. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  48851. * Returns the DirectionalLight Shadow projection matrix.
  48852. */
  48853. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48854. var activeCamera = this.getScene().activeCamera;
  48855. if (!activeCamera) {
  48856. return;
  48857. }
  48858. // Check extends
  48859. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  48860. var tempVector3 = BABYLON.Vector3.Zero();
  48861. this._orthoLeft = Number.MAX_VALUE;
  48862. this._orthoRight = Number.MIN_VALUE;
  48863. this._orthoTop = Number.MIN_VALUE;
  48864. this._orthoBottom = Number.MAX_VALUE;
  48865. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  48866. var mesh = renderList[meshIndex];
  48867. if (!mesh) {
  48868. continue;
  48869. }
  48870. var boundingInfo = mesh.getBoundingInfo();
  48871. var boundingBox = boundingInfo.boundingBox;
  48872. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  48873. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  48874. if (tempVector3.x < this._orthoLeft)
  48875. this._orthoLeft = tempVector3.x;
  48876. if (tempVector3.y < this._orthoBottom)
  48877. this._orthoBottom = tempVector3.y;
  48878. if (tempVector3.x > this._orthoRight)
  48879. this._orthoRight = tempVector3.x;
  48880. if (tempVector3.y > this._orthoTop)
  48881. this._orthoTop = tempVector3.y;
  48882. }
  48883. }
  48884. }
  48885. var xOffset = this._orthoRight - this._orthoLeft;
  48886. var yOffset = this._orthoTop - this._orthoBottom;
  48887. 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);
  48888. };
  48889. DirectionalLight.prototype._buildUniformLayout = function () {
  48890. this._uniformBuffer.addUniform("vLightData", 4);
  48891. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48892. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48893. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48894. this._uniformBuffer.addUniform("depthValues", 2);
  48895. this._uniformBuffer.create();
  48896. };
  48897. /**
  48898. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  48899. * @param effect The effect to update
  48900. * @param lightIndex The index of the light in the effect to update
  48901. * @returns The directional light
  48902. */
  48903. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  48904. if (this.computeTransformedInformation()) {
  48905. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  48906. return this;
  48907. }
  48908. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  48909. return this;
  48910. };
  48911. /**
  48912. * Gets the minZ used for shadow according to both the scene and the light.
  48913. *
  48914. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  48915. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  48916. * @param activeCamera The camera we are returning the min for
  48917. * @returns the depth min z
  48918. */
  48919. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  48920. return 1;
  48921. };
  48922. /**
  48923. * Gets the maxZ used for shadow according to both the scene and the light.
  48924. *
  48925. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  48926. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  48927. * @param activeCamera The camera we are returning the max for
  48928. * @returns the depth max z
  48929. */
  48930. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  48931. return 1;
  48932. };
  48933. __decorate([
  48934. BABYLON.serialize()
  48935. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  48936. __decorate([
  48937. BABYLON.serialize()
  48938. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  48939. __decorate([
  48940. BABYLON.serialize()
  48941. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  48942. return DirectionalLight;
  48943. }(BABYLON.ShadowLight));
  48944. BABYLON.DirectionalLight = DirectionalLight;
  48945. })(BABYLON || (BABYLON = {}));
  48946. //# sourceMappingURL=babylon.directionalLight.js.map
  48947. var BABYLON;
  48948. (function (BABYLON) {
  48949. /**
  48950. * A spot light is defined by a position, a direction, an angle, and an exponent.
  48951. * These values define a cone of light starting from the position, emitting toward the direction.
  48952. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  48953. * and the exponent defines the speed of the decay of the light with distance (reach).
  48954. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48955. */
  48956. var SpotLight = /** @class */ (function (_super) {
  48957. __extends(SpotLight, _super);
  48958. /**
  48959. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  48960. * It can cast shadows.
  48961. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48962. * @param name The light friendly name
  48963. * @param position The position of the spot light in the scene
  48964. * @param direction The direction of the light in the scene
  48965. * @param angle The cone angle of the light in Radians
  48966. * @param exponent The light decay speed with the distance from the emission spot
  48967. * @param scene The scene the lights belongs to
  48968. */
  48969. function SpotLight(name, position, direction, angle, exponent, scene) {
  48970. var _this = _super.call(this, name, scene) || this;
  48971. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  48972. _this._projectionTextureLightNear = 1e-6;
  48973. _this._projectionTextureLightFar = 1000.0;
  48974. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  48975. _this._projectionTextureViewLightDirty = true;
  48976. _this._projectionTextureProjectionLightDirty = true;
  48977. _this._projectionTextureDirty = true;
  48978. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  48979. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  48980. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  48981. _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);
  48982. _this.position = position;
  48983. _this.direction = direction;
  48984. _this.angle = angle;
  48985. _this.exponent = exponent;
  48986. return _this;
  48987. }
  48988. Object.defineProperty(SpotLight.prototype, "angle", {
  48989. /**
  48990. * Gets the cone angle of the spot light in Radians.
  48991. */
  48992. get: function () {
  48993. return this._angle;
  48994. },
  48995. /**
  48996. * Sets the cone angle of the spot light in Radians.
  48997. */
  48998. set: function (value) {
  48999. this._angle = value;
  49000. this._projectionTextureProjectionLightDirty = true;
  49001. this.forceProjectionMatrixCompute();
  49002. },
  49003. enumerable: true,
  49004. configurable: true
  49005. });
  49006. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  49007. /**
  49008. * Allows scaling the angle of the light for shadow generation only.
  49009. */
  49010. get: function () {
  49011. return this._shadowAngleScale;
  49012. },
  49013. /**
  49014. * Allows scaling the angle of the light for shadow generation only.
  49015. */
  49016. set: function (value) {
  49017. this._shadowAngleScale = value;
  49018. this.forceProjectionMatrixCompute();
  49019. },
  49020. enumerable: true,
  49021. configurable: true
  49022. });
  49023. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  49024. /**
  49025. * Allows reading the projecton texture
  49026. */
  49027. get: function () {
  49028. return this._projectionTextureMatrix;
  49029. },
  49030. enumerable: true,
  49031. configurable: true
  49032. });
  49033. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  49034. /**
  49035. * Gets the near clip of the Spotlight for texture projection.
  49036. */
  49037. get: function () {
  49038. return this._projectionTextureLightNear;
  49039. },
  49040. /**
  49041. * Sets the near clip of the Spotlight for texture projection.
  49042. */
  49043. set: function (value) {
  49044. this._projectionTextureLightNear = value;
  49045. this._projectionTextureProjectionLightDirty = true;
  49046. },
  49047. enumerable: true,
  49048. configurable: true
  49049. });
  49050. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  49051. /**
  49052. * Gets the far clip of the Spotlight for texture projection.
  49053. */
  49054. get: function () {
  49055. return this._projectionTextureLightFar;
  49056. },
  49057. /**
  49058. * Sets the far clip of the Spotlight for texture projection.
  49059. */
  49060. set: function (value) {
  49061. this._projectionTextureLightFar = value;
  49062. this._projectionTextureProjectionLightDirty = true;
  49063. },
  49064. enumerable: true,
  49065. configurable: true
  49066. });
  49067. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  49068. /**
  49069. * Gets the Up vector of the Spotlight for texture projection.
  49070. */
  49071. get: function () {
  49072. return this._projectionTextureUpDirection;
  49073. },
  49074. /**
  49075. * Sets the Up vector of the Spotlight for texture projection.
  49076. */
  49077. set: function (value) {
  49078. this._projectionTextureUpDirection = value;
  49079. this._projectionTextureProjectionLightDirty = true;
  49080. },
  49081. enumerable: true,
  49082. configurable: true
  49083. });
  49084. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  49085. /**
  49086. * Gets the projection texture of the light.
  49087. */
  49088. get: function () {
  49089. return this._projectionTexture;
  49090. },
  49091. /**
  49092. * Sets the projection texture of the light.
  49093. */
  49094. set: function (value) {
  49095. this._projectionTexture = value;
  49096. this._projectionTextureDirty = true;
  49097. },
  49098. enumerable: true,
  49099. configurable: true
  49100. });
  49101. /**
  49102. * Returns the string "SpotLight".
  49103. * @returns the class name
  49104. */
  49105. SpotLight.prototype.getClassName = function () {
  49106. return "SpotLight";
  49107. };
  49108. /**
  49109. * Returns the integer 2.
  49110. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49111. */
  49112. SpotLight.prototype.getTypeID = function () {
  49113. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  49114. };
  49115. /**
  49116. * Overrides the direction setter to recompute the projection texture view light Matrix.
  49117. */
  49118. SpotLight.prototype._setDirection = function (value) {
  49119. _super.prototype._setDirection.call(this, value);
  49120. this._projectionTextureViewLightDirty = true;
  49121. };
  49122. /**
  49123. * Overrides the position setter to recompute the projection texture view light Matrix.
  49124. */
  49125. SpotLight.prototype._setPosition = function (value) {
  49126. _super.prototype._setPosition.call(this, value);
  49127. this._projectionTextureViewLightDirty = true;
  49128. };
  49129. /**
  49130. * 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.
  49131. * Returns the SpotLight.
  49132. */
  49133. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49134. var activeCamera = this.getScene().activeCamera;
  49135. if (!activeCamera) {
  49136. return;
  49137. }
  49138. this._shadowAngleScale = this._shadowAngleScale || 1;
  49139. var angle = this._shadowAngleScale * this._angle;
  49140. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  49141. };
  49142. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  49143. this._projectionTextureViewLightDirty = false;
  49144. this._projectionTextureDirty = true;
  49145. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  49146. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  49147. };
  49148. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  49149. this._projectionTextureProjectionLightDirty = false;
  49150. this._projectionTextureDirty = true;
  49151. var light_far = this.projectionTextureLightFar;
  49152. var light_near = this.projectionTextureLightNear;
  49153. var P = light_far / (light_far - light_near);
  49154. var Q = -P * light_near;
  49155. var S = 1.0 / Math.tan(this._angle / 2.0);
  49156. var A = 1.0;
  49157. 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);
  49158. };
  49159. /**
  49160. * Main function for light texture projection matrix computing.
  49161. */
  49162. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  49163. this._projectionTextureDirty = false;
  49164. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  49165. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  49166. };
  49167. SpotLight.prototype._buildUniformLayout = function () {
  49168. this._uniformBuffer.addUniform("vLightData", 4);
  49169. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49170. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49171. this._uniformBuffer.addUniform("vLightDirection", 3);
  49172. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49173. this._uniformBuffer.addUniform("depthValues", 2);
  49174. this._uniformBuffer.create();
  49175. };
  49176. /**
  49177. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  49178. * @param effect The effect to update
  49179. * @param lightIndex The index of the light in the effect to update
  49180. * @returns The spot light
  49181. */
  49182. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  49183. var normalizeDirection;
  49184. if (this.computeTransformedInformation()) {
  49185. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  49186. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  49187. }
  49188. else {
  49189. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  49190. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  49191. }
  49192. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  49193. if (this.projectionTexture && this.projectionTexture.isReady()) {
  49194. if (this._projectionTextureViewLightDirty) {
  49195. this._computeProjectionTextureViewLightMatrix();
  49196. }
  49197. if (this._projectionTextureProjectionLightDirty) {
  49198. this._computeProjectionTextureProjectionLightMatrix();
  49199. }
  49200. if (this._projectionTextureDirty) {
  49201. this._computeProjectionTextureMatrix();
  49202. }
  49203. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  49204. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  49205. }
  49206. return this;
  49207. };
  49208. /**
  49209. * Disposes the light and the associated resources.
  49210. */
  49211. SpotLight.prototype.dispose = function () {
  49212. _super.prototype.dispose.call(this);
  49213. if (this._projectionTexture) {
  49214. this._projectionTexture.dispose();
  49215. }
  49216. };
  49217. __decorate([
  49218. BABYLON.serialize()
  49219. ], SpotLight.prototype, "angle", null);
  49220. __decorate([
  49221. BABYLON.serialize()
  49222. ], SpotLight.prototype, "shadowAngleScale", null);
  49223. __decorate([
  49224. BABYLON.serialize()
  49225. ], SpotLight.prototype, "exponent", void 0);
  49226. __decorate([
  49227. BABYLON.serialize()
  49228. ], SpotLight.prototype, "projectionTextureLightNear", null);
  49229. __decorate([
  49230. BABYLON.serialize()
  49231. ], SpotLight.prototype, "projectionTextureLightFar", null);
  49232. __decorate([
  49233. BABYLON.serialize()
  49234. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  49235. __decorate([
  49236. BABYLON.serializeAsTexture("projectedLightTexture")
  49237. ], SpotLight.prototype, "_projectionTexture", void 0);
  49238. return SpotLight;
  49239. }(BABYLON.ShadowLight));
  49240. BABYLON.SpotLight = SpotLight;
  49241. })(BABYLON || (BABYLON = {}));
  49242. //# sourceMappingURL=babylon.spotLight.js.map
  49243. var BABYLON;
  49244. (function (BABYLON) {
  49245. /**
  49246. * Class used to override all child animations of a given target
  49247. */
  49248. var AnimationPropertiesOverride = /** @class */ (function () {
  49249. function AnimationPropertiesOverride() {
  49250. /**
  49251. * Gets or sets a value indicating if animation blending must be used
  49252. */
  49253. this.enableBlending = false;
  49254. /**
  49255. * Gets or sets the blending speed to use when enableBlending is true
  49256. */
  49257. this.blendingSpeed = 0.01;
  49258. /**
  49259. * Gets or sets the default loop mode to use
  49260. */
  49261. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  49262. }
  49263. return AnimationPropertiesOverride;
  49264. }());
  49265. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  49266. })(BABYLON || (BABYLON = {}));
  49267. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  49268. var BABYLON;
  49269. (function (BABYLON) {
  49270. /**
  49271. * Represents the range of an animation
  49272. */
  49273. var AnimationRange = /** @class */ (function () {
  49274. /**
  49275. * Initializes the range of an animation
  49276. * @param name The name of the animation range
  49277. * @param from The starting frame of the animation
  49278. * @param to The ending frame of the animation
  49279. */
  49280. function AnimationRange(
  49281. /**The name of the animation range**/
  49282. name,
  49283. /**The starting frame of the animation */
  49284. from,
  49285. /**The ending frame of the animation*/
  49286. to) {
  49287. this.name = name;
  49288. this.from = from;
  49289. this.to = to;
  49290. }
  49291. /**
  49292. * Makes a copy of the animation range
  49293. * @returns A copy of the animation range
  49294. */
  49295. AnimationRange.prototype.clone = function () {
  49296. return new AnimationRange(this.name, this.from, this.to);
  49297. };
  49298. return AnimationRange;
  49299. }());
  49300. BABYLON.AnimationRange = AnimationRange;
  49301. /**
  49302. * Composed of a frame, and an action function
  49303. */
  49304. var AnimationEvent = /** @class */ (function () {
  49305. /**
  49306. * Initializes the animation event
  49307. * @param frame The frame for which the event is triggered
  49308. * @param action The event to perform when triggered
  49309. * @param onlyOnce Specifies if the event should be triggered only once
  49310. */
  49311. function AnimationEvent(
  49312. /** The frame for which the event is triggered **/
  49313. frame,
  49314. /** The event to perform when triggered **/
  49315. action,
  49316. /** Specifies if the event should be triggered only once**/
  49317. onlyOnce) {
  49318. this.frame = frame;
  49319. this.action = action;
  49320. this.onlyOnce = onlyOnce;
  49321. /**
  49322. * Specifies if the animation event is done
  49323. */
  49324. this.isDone = false;
  49325. }
  49326. /** @hidden */
  49327. AnimationEvent.prototype._clone = function () {
  49328. return new AnimationEvent(this.frame, this.action, this.onlyOnce);
  49329. };
  49330. return AnimationEvent;
  49331. }());
  49332. BABYLON.AnimationEvent = AnimationEvent;
  49333. /**
  49334. * A cursor which tracks a point on a path
  49335. */
  49336. var PathCursor = /** @class */ (function () {
  49337. /**
  49338. * Initializes the path cursor
  49339. * @param path The path to track
  49340. */
  49341. function PathCursor(path) {
  49342. this.path = path;
  49343. /**
  49344. * Stores path cursor callbacks for when an onchange event is triggered
  49345. */
  49346. this._onchange = new Array();
  49347. /**
  49348. * The value of the path cursor
  49349. */
  49350. this.value = 0;
  49351. /**
  49352. * The animation array of the path cursor
  49353. */
  49354. this.animations = new Array();
  49355. }
  49356. /**
  49357. * Gets the cursor point on the path
  49358. * @returns A point on the path cursor at the cursor location
  49359. */
  49360. PathCursor.prototype.getPoint = function () {
  49361. var point = this.path.getPointAtLengthPosition(this.value);
  49362. return new BABYLON.Vector3(point.x, 0, point.y);
  49363. };
  49364. /**
  49365. * Moves the cursor ahead by the step amount
  49366. * @param step The amount to move the cursor forward
  49367. * @returns This path cursor
  49368. */
  49369. PathCursor.prototype.moveAhead = function (step) {
  49370. if (step === void 0) { step = 0.002; }
  49371. this.move(step);
  49372. return this;
  49373. };
  49374. /**
  49375. * Moves the cursor behind by the step amount
  49376. * @param step The amount to move the cursor back
  49377. * @returns This path cursor
  49378. */
  49379. PathCursor.prototype.moveBack = function (step) {
  49380. if (step === void 0) { step = 0.002; }
  49381. this.move(-step);
  49382. return this;
  49383. };
  49384. /**
  49385. * Moves the cursor by the step amount
  49386. * If the step amount is greater than one, an exception is thrown
  49387. * @param step The amount to move the cursor
  49388. * @returns This path cursor
  49389. */
  49390. PathCursor.prototype.move = function (step) {
  49391. if (Math.abs(step) > 1) {
  49392. throw "step size should be less than 1.";
  49393. }
  49394. this.value += step;
  49395. this.ensureLimits();
  49396. this.raiseOnChange();
  49397. return this;
  49398. };
  49399. /**
  49400. * Ensures that the value is limited between zero and one
  49401. * @returns This path cursor
  49402. */
  49403. PathCursor.prototype.ensureLimits = function () {
  49404. while (this.value > 1) {
  49405. this.value -= 1;
  49406. }
  49407. while (this.value < 0) {
  49408. this.value += 1;
  49409. }
  49410. return this;
  49411. };
  49412. /**
  49413. * Runs onchange callbacks on change (used by the animation engine)
  49414. * @returns This path cursor
  49415. */
  49416. PathCursor.prototype.raiseOnChange = function () {
  49417. var _this = this;
  49418. this._onchange.forEach(function (f) { return f(_this); });
  49419. return this;
  49420. };
  49421. /**
  49422. * Executes a function on change
  49423. * @param f A path cursor onchange callback
  49424. * @returns This path cursor
  49425. */
  49426. PathCursor.prototype.onchange = function (f) {
  49427. this._onchange.push(f);
  49428. return this;
  49429. };
  49430. return PathCursor;
  49431. }());
  49432. BABYLON.PathCursor = PathCursor;
  49433. /**
  49434. * Enum for the animation key frame interpolation type
  49435. */
  49436. var AnimationKeyInterpolation;
  49437. (function (AnimationKeyInterpolation) {
  49438. /**
  49439. * Do not interpolate between keys and use the start key value only. Tangents are ignored
  49440. */
  49441. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  49442. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  49443. /**
  49444. * Class used to store any kind of animation
  49445. */
  49446. var Animation = /** @class */ (function () {
  49447. /**
  49448. * Initializes the animation
  49449. * @param name Name of the animation
  49450. * @param targetProperty Property to animate
  49451. * @param framePerSecond The frames per second of the animation
  49452. * @param dataType The data type of the animation
  49453. * @param loopMode The loop mode of the animation
  49454. * @param enableBlendings Specifies if blending should be enabled
  49455. */
  49456. function Animation(
  49457. /**Name of the animation */
  49458. name,
  49459. /**Property to animate */
  49460. targetProperty,
  49461. /**The frames per second of the animation */
  49462. framePerSecond,
  49463. /**The data type of the animation */
  49464. dataType,
  49465. /**The loop mode of the animation */
  49466. loopMode,
  49467. /**Specifies if blending should be enabled */
  49468. enableBlending) {
  49469. this.name = name;
  49470. this.targetProperty = targetProperty;
  49471. this.framePerSecond = framePerSecond;
  49472. this.dataType = dataType;
  49473. this.loopMode = loopMode;
  49474. this.enableBlending = enableBlending;
  49475. /**
  49476. * @hidden Internal use only
  49477. */
  49478. this._runtimeAnimations = new Array();
  49479. /**
  49480. * The set of event that will be linked to this animation
  49481. */
  49482. this._events = new Array();
  49483. /**
  49484. * Stores the blending speed of the animation
  49485. */
  49486. this.blendingSpeed = 0.01;
  49487. /**
  49488. * Stores the animation ranges for the animation
  49489. */
  49490. this._ranges = {};
  49491. this.targetPropertyPath = targetProperty.split(".");
  49492. this.dataType = dataType;
  49493. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  49494. }
  49495. /**
  49496. * @hidden Internal use
  49497. */
  49498. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  49499. var dataType = undefined;
  49500. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  49501. dataType = Animation.ANIMATIONTYPE_FLOAT;
  49502. }
  49503. else if (from instanceof BABYLON.Quaternion) {
  49504. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  49505. }
  49506. else if (from instanceof BABYLON.Vector3) {
  49507. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  49508. }
  49509. else if (from instanceof BABYLON.Vector2) {
  49510. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  49511. }
  49512. else if (from instanceof BABYLON.Color3) {
  49513. dataType = Animation.ANIMATIONTYPE_COLOR3;
  49514. }
  49515. else if (from instanceof BABYLON.Size) {
  49516. dataType = Animation.ANIMATIONTYPE_SIZE;
  49517. }
  49518. if (dataType == undefined) {
  49519. return null;
  49520. }
  49521. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  49522. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  49523. animation.setKeys(keys);
  49524. if (easingFunction !== undefined) {
  49525. animation.setEasingFunction(easingFunction);
  49526. }
  49527. return animation;
  49528. };
  49529. /**
  49530. * Sets up an animation
  49531. * @param property The property to animate
  49532. * @param animationType The animation type to apply
  49533. * @param framePerSecond The frames per second of the animation
  49534. * @param easingFunction The easing function used in the animation
  49535. * @returns The created animation
  49536. */
  49537. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  49538. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  49539. animation.setEasingFunction(easingFunction);
  49540. return animation;
  49541. };
  49542. /**
  49543. * Create and start an animation on a node
  49544. * @param name defines the name of the global animation that will be run on all nodes
  49545. * @param node defines the root node where the animation will take place
  49546. * @param targetProperty defines property to animate
  49547. * @param framePerSecond defines the number of frame per second yo use
  49548. * @param totalFrame defines the number of frames in total
  49549. * @param from defines the initial value
  49550. * @param to defines the final value
  49551. * @param loopMode defines which loop mode you want to use (off by default)
  49552. * @param easingFunction defines the easing function to use (linear by default)
  49553. * @param onAnimationEnd defines the callback to call when animation end
  49554. * @returns the animatable created for this animation
  49555. */
  49556. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49557. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49558. if (!animation) {
  49559. return null;
  49560. }
  49561. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49562. };
  49563. /**
  49564. * Create and start an animation on a node and its descendants
  49565. * @param name defines the name of the global animation that will be run on all nodes
  49566. * @param node defines the root node where the animation will take place
  49567. * @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
  49568. * @param targetProperty defines property to animate
  49569. * @param framePerSecond defines the number of frame per second to use
  49570. * @param totalFrame defines the number of frames in total
  49571. * @param from defines the initial value
  49572. * @param to defines the final value
  49573. * @param loopMode defines which loop mode you want to use (off by default)
  49574. * @param easingFunction defines the easing function to use (linear by default)
  49575. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  49576. * @returns the list of animatables created for all nodes
  49577. * @example https://www.babylonjs-playground.com/#MH0VLI
  49578. */
  49579. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49580. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49581. if (!animation) {
  49582. return null;
  49583. }
  49584. var scene = node.getScene();
  49585. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49586. };
  49587. /**
  49588. * Creates a new animation, merges it with the existing animations and starts it
  49589. * @param name Name of the animation
  49590. * @param node Node which contains the scene that begins the animations
  49591. * @param targetProperty Specifies which property to animate
  49592. * @param framePerSecond The frames per second of the animation
  49593. * @param totalFrame The total number of frames
  49594. * @param from The frame at the beginning of the animation
  49595. * @param to The frame at the end of the animation
  49596. * @param loopMode Specifies the loop mode of the animation
  49597. * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
  49598. * @param onAnimationEnd Callback to run once the animation is complete
  49599. * @returns Nullable animation
  49600. */
  49601. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49602. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49603. if (!animation) {
  49604. return null;
  49605. }
  49606. node.animations.push(animation);
  49607. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49608. };
  49609. /**
  49610. * Transition property of an host to the target Value
  49611. * @param property The property to transition
  49612. * @param targetValue The target Value of the property
  49613. * @param host The object where the property to animate belongs
  49614. * @param scene Scene used to run the animation
  49615. * @param frameRate Framerate (in frame/s) to use
  49616. * @param transition The transition type we want to use
  49617. * @param duration The duration of the animation, in milliseconds
  49618. * @param onAnimationEnd Callback trigger at the end of the animation
  49619. * @returns Nullable animation
  49620. */
  49621. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  49622. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  49623. if (duration <= 0) {
  49624. host[property] = targetValue;
  49625. if (onAnimationEnd) {
  49626. onAnimationEnd();
  49627. }
  49628. return null;
  49629. }
  49630. var endFrame = frameRate * (duration / 1000);
  49631. transition.setKeys([{
  49632. frame: 0,
  49633. value: host[property].clone ? host[property].clone() : host[property]
  49634. },
  49635. {
  49636. frame: endFrame,
  49637. value: targetValue
  49638. }]);
  49639. if (!host.animations) {
  49640. host.animations = [];
  49641. }
  49642. host.animations.push(transition);
  49643. var animation = scene.beginAnimation(host, 0, endFrame, false);
  49644. animation.onAnimationEnd = onAnimationEnd;
  49645. return animation;
  49646. };
  49647. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  49648. /**
  49649. * Return the array of runtime animations currently using this animation
  49650. */
  49651. get: function () {
  49652. return this._runtimeAnimations;
  49653. },
  49654. enumerable: true,
  49655. configurable: true
  49656. });
  49657. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  49658. /**
  49659. * Specifies if any of the runtime animations are currently running
  49660. */
  49661. get: function () {
  49662. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  49663. var runtimeAnimation = _a[_i];
  49664. if (!runtimeAnimation.isStopped) {
  49665. return true;
  49666. }
  49667. }
  49668. return false;
  49669. },
  49670. enumerable: true,
  49671. configurable: true
  49672. });
  49673. // Methods
  49674. /**
  49675. * Converts the animation to a string
  49676. * @param fullDetails support for multiple levels of logging within scene loading
  49677. * @returns String form of the animation
  49678. */
  49679. Animation.prototype.toString = function (fullDetails) {
  49680. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  49681. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  49682. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  49683. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  49684. if (fullDetails) {
  49685. ret += ", Ranges: {";
  49686. var first = true;
  49687. for (var name in this._ranges) {
  49688. if (first) {
  49689. ret += ", ";
  49690. first = false;
  49691. }
  49692. ret += name;
  49693. }
  49694. ret += "}";
  49695. }
  49696. return ret;
  49697. };
  49698. /**
  49699. * Add an event to this animation
  49700. * @param event Event to add
  49701. */
  49702. Animation.prototype.addEvent = function (event) {
  49703. this._events.push(event);
  49704. };
  49705. /**
  49706. * Remove all events found at the given frame
  49707. * @param frame The frame to remove events from
  49708. */
  49709. Animation.prototype.removeEvents = function (frame) {
  49710. for (var index = 0; index < this._events.length; index++) {
  49711. if (this._events[index].frame === frame) {
  49712. this._events.splice(index, 1);
  49713. index--;
  49714. }
  49715. }
  49716. };
  49717. /**
  49718. * Retrieves all the events from the animation
  49719. * @returns Events from the animation
  49720. */
  49721. Animation.prototype.getEvents = function () {
  49722. return this._events;
  49723. };
  49724. /**
  49725. * Creates an animation range
  49726. * @param name Name of the animation range
  49727. * @param from Starting frame of the animation range
  49728. * @param to Ending frame of the animation
  49729. */
  49730. Animation.prototype.createRange = function (name, from, to) {
  49731. // check name not already in use; could happen for bones after serialized
  49732. if (!this._ranges[name]) {
  49733. this._ranges[name] = new AnimationRange(name, from, to);
  49734. }
  49735. };
  49736. /**
  49737. * Deletes an animation range by name
  49738. * @param name Name of the animation range to delete
  49739. * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
  49740. */
  49741. Animation.prototype.deleteRange = function (name, deleteFrames) {
  49742. if (deleteFrames === void 0) { deleteFrames = true; }
  49743. var range = this._ranges[name];
  49744. if (!range) {
  49745. return;
  49746. }
  49747. if (deleteFrames) {
  49748. var from = range.from;
  49749. var to = range.to;
  49750. // this loop MUST go high to low for multiple splices to work
  49751. for (var key = this._keys.length - 1; key >= 0; key--) {
  49752. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  49753. this._keys.splice(key, 1);
  49754. }
  49755. }
  49756. }
  49757. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  49758. };
  49759. /**
  49760. * Gets the animation range by name, or null if not defined
  49761. * @param name Name of the animation range
  49762. * @returns Nullable animation range
  49763. */
  49764. Animation.prototype.getRange = function (name) {
  49765. return this._ranges[name];
  49766. };
  49767. /**
  49768. * Gets the key frames from the animation
  49769. * @returns The key frames of the animation
  49770. */
  49771. Animation.prototype.getKeys = function () {
  49772. return this._keys;
  49773. };
  49774. /**
  49775. * Gets the highest frame rate of the animation
  49776. * @returns Highest frame rate of the animation
  49777. */
  49778. Animation.prototype.getHighestFrame = function () {
  49779. var ret = 0;
  49780. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  49781. if (ret < this._keys[key].frame) {
  49782. ret = this._keys[key].frame;
  49783. }
  49784. }
  49785. return ret;
  49786. };
  49787. /**
  49788. * Gets the easing function of the animation
  49789. * @returns Easing function of the animation
  49790. */
  49791. Animation.prototype.getEasingFunction = function () {
  49792. return this._easingFunction;
  49793. };
  49794. /**
  49795. * Sets the easing function of the animation
  49796. * @param easingFunction A custom mathematical formula for animation
  49797. */
  49798. Animation.prototype.setEasingFunction = function (easingFunction) {
  49799. this._easingFunction = easingFunction;
  49800. };
  49801. /**
  49802. * Interpolates a scalar linearly
  49803. * @param startValue Start value of the animation curve
  49804. * @param endValue End value of the animation curve
  49805. * @param gradient Scalar amount to interpolate
  49806. * @returns Interpolated scalar value
  49807. */
  49808. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  49809. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  49810. };
  49811. /**
  49812. * Interpolates a scalar cubically
  49813. * @param startValue Start value of the animation curve
  49814. * @param outTangent End tangent of the animation
  49815. * @param endValue End value of the animation curve
  49816. * @param inTangent Start tangent of the animation curve
  49817. * @param gradient Scalar amount to interpolate
  49818. * @returns Interpolated scalar value
  49819. */
  49820. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49821. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49822. };
  49823. /**
  49824. * Interpolates a quaternion using a spherical linear interpolation
  49825. * @param startValue Start value of the animation curve
  49826. * @param endValue End value of the animation curve
  49827. * @param gradient Scalar amount to interpolate
  49828. * @returns Interpolated quaternion value
  49829. */
  49830. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  49831. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  49832. };
  49833. /**
  49834. * Interpolates a quaternion cubically
  49835. * @param startValue Start value of the animation curve
  49836. * @param outTangent End tangent of the animation curve
  49837. * @param endValue End value of the animation curve
  49838. * @param inTangent Start tangent of the animation curve
  49839. * @param gradient Scalar amount to interpolate
  49840. * @returns Interpolated quaternion value
  49841. */
  49842. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49843. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  49844. };
  49845. /**
  49846. * Interpolates a Vector3 linearl
  49847. * @param startValue Start value of the animation curve
  49848. * @param endValue End value of the animation curve
  49849. * @param gradient Scalar amount to interpolate
  49850. * @returns Interpolated scalar value
  49851. */
  49852. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  49853. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  49854. };
  49855. /**
  49856. * Interpolates a Vector3 cubically
  49857. * @param startValue Start value of the animation curve
  49858. * @param outTangent End tangent of the animation
  49859. * @param endValue End value of the animation curve
  49860. * @param inTangent Start tangent of the animation curve
  49861. * @param gradient Scalar amount to interpolate
  49862. * @returns InterpolatedVector3 value
  49863. */
  49864. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49865. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49866. };
  49867. /**
  49868. * Interpolates a Vector2 linearly
  49869. * @param startValue Start value of the animation curve
  49870. * @param endValue End value of the animation curve
  49871. * @param gradient Scalar amount to interpolate
  49872. * @returns Interpolated Vector2 value
  49873. */
  49874. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  49875. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  49876. };
  49877. /**
  49878. * Interpolates a Vector2 cubically
  49879. * @param startValue Start value of the animation curve
  49880. * @param outTangent End tangent of the animation
  49881. * @param endValue End value of the animation curve
  49882. * @param inTangent Start tangent of the animation curve
  49883. * @param gradient Scalar amount to interpolate
  49884. * @returns Interpolated Vector2 value
  49885. */
  49886. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49887. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49888. };
  49889. /**
  49890. * Interpolates a size linearly
  49891. * @param startValue Start value of the animation curve
  49892. * @param endValue End value of the animation curve
  49893. * @param gradient Scalar amount to interpolate
  49894. * @returns Interpolated Size value
  49895. */
  49896. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  49897. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  49898. };
  49899. /**
  49900. * Interpolates a Color3 linearly
  49901. * @param startValue Start value of the animation curve
  49902. * @param endValue End value of the animation curve
  49903. * @param gradient Scalar amount to interpolate
  49904. * @returns Interpolated Color3 value
  49905. */
  49906. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  49907. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  49908. };
  49909. /**
  49910. * @hidden Internal use only
  49911. */
  49912. Animation.prototype._getKeyValue = function (value) {
  49913. if (typeof value === "function") {
  49914. return value();
  49915. }
  49916. return value;
  49917. };
  49918. /**
  49919. * @hidden Internal use only
  49920. */
  49921. Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {
  49922. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  49923. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  49924. }
  49925. var keys = this.getKeys();
  49926. // Try to get a hash to find the right key
  49927. 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));
  49928. if (keys[startKeyIndex].frame >= currentFrame) {
  49929. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  49930. startKeyIndex--;
  49931. }
  49932. }
  49933. for (var key = startKeyIndex; key < keys.length; key++) {
  49934. var endKey = keys[key + 1];
  49935. if (endKey.frame >= currentFrame) {
  49936. var startKey = keys[key];
  49937. var startValue = this._getKeyValue(startKey.value);
  49938. if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
  49939. return startValue;
  49940. }
  49941. var endValue = this._getKeyValue(endKey.value);
  49942. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  49943. var frameDelta = endKey.frame - startKey.frame;
  49944. // gradient : percent of currentFrame between the frame inf and the frame sup
  49945. var gradient = (currentFrame - startKey.frame) / frameDelta;
  49946. // check for easingFunction and correction of gradient
  49947. var easingFunction = this.getEasingFunction();
  49948. if (easingFunction != null) {
  49949. gradient = easingFunction.ease(gradient);
  49950. }
  49951. switch (this.dataType) {
  49952. // Float
  49953. case Animation.ANIMATIONTYPE_FLOAT:
  49954. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  49955. switch (loopMode) {
  49956. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49957. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49958. return floatValue;
  49959. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49960. return offsetValue * repeatCount + floatValue;
  49961. }
  49962. break;
  49963. // Quaternion
  49964. case Animation.ANIMATIONTYPE_QUATERNION:
  49965. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  49966. switch (loopMode) {
  49967. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49968. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49969. return quatValue;
  49970. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49971. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  49972. }
  49973. return quatValue;
  49974. // Vector3
  49975. case Animation.ANIMATIONTYPE_VECTOR3:
  49976. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  49977. switch (loopMode) {
  49978. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49979. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49980. return vec3Value;
  49981. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49982. return vec3Value.add(offsetValue.scale(repeatCount));
  49983. }
  49984. // Vector2
  49985. case Animation.ANIMATIONTYPE_VECTOR2:
  49986. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  49987. switch (loopMode) {
  49988. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49989. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49990. return vec2Value;
  49991. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49992. return vec2Value.add(offsetValue.scale(repeatCount));
  49993. }
  49994. // Size
  49995. case Animation.ANIMATIONTYPE_SIZE:
  49996. switch (loopMode) {
  49997. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49998. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49999. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  50000. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50001. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50002. }
  50003. // Color3
  50004. case Animation.ANIMATIONTYPE_COLOR3:
  50005. switch (loopMode) {
  50006. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50007. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50008. return this.color3InterpolateFunction(startValue, endValue, gradient);
  50009. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50010. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50011. }
  50012. // Matrix
  50013. case Animation.ANIMATIONTYPE_MATRIX:
  50014. switch (loopMode) {
  50015. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50016. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50017. if (Animation.AllowMatricesInterpolation) {
  50018. return this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
  50019. }
  50020. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50021. return startValue;
  50022. }
  50023. default:
  50024. break;
  50025. }
  50026. break;
  50027. }
  50028. }
  50029. return this._getKeyValue(keys[keys.length - 1].value);
  50030. };
  50031. /**
  50032. * Defines the function to use to interpolate matrices
  50033. * @param startValue defines the start matrix
  50034. * @param endValue defines the end matrix
  50035. * @param gradient defines the gradient between both matrices
  50036. * @param result defines an optional target matrix where to store the interpolation
  50037. * @returns the interpolated matrix
  50038. */
  50039. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  50040. if (Animation.AllowMatrixDecomposeForInterpolation) {
  50041. if (result) {
  50042. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  50043. return result;
  50044. }
  50045. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  50046. }
  50047. if (result) {
  50048. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  50049. return result;
  50050. }
  50051. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  50052. };
  50053. /**
  50054. * Makes a copy of the animation
  50055. * @returns Cloned animation
  50056. */
  50057. Animation.prototype.clone = function () {
  50058. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  50059. clone.enableBlending = this.enableBlending;
  50060. clone.blendingSpeed = this.blendingSpeed;
  50061. if (this._keys) {
  50062. clone.setKeys(this._keys);
  50063. }
  50064. if (this._ranges) {
  50065. clone._ranges = {};
  50066. for (var name in this._ranges) {
  50067. var range = this._ranges[name];
  50068. if (!range) {
  50069. continue;
  50070. }
  50071. clone._ranges[name] = range.clone();
  50072. }
  50073. }
  50074. return clone;
  50075. };
  50076. /**
  50077. * Sets the key frames of the animation
  50078. * @param values The animation key frames to set
  50079. */
  50080. Animation.prototype.setKeys = function (values) {
  50081. this._keys = values.slice(0);
  50082. };
  50083. /**
  50084. * Serializes the animation to an object
  50085. * @returns Serialized object
  50086. */
  50087. Animation.prototype.serialize = function () {
  50088. var serializationObject = {};
  50089. serializationObject.name = this.name;
  50090. serializationObject.property = this.targetProperty;
  50091. serializationObject.framePerSecond = this.framePerSecond;
  50092. serializationObject.dataType = this.dataType;
  50093. serializationObject.loopBehavior = this.loopMode;
  50094. serializationObject.enableBlending = this.enableBlending;
  50095. serializationObject.blendingSpeed = this.blendingSpeed;
  50096. var dataType = this.dataType;
  50097. serializationObject.keys = [];
  50098. var keys = this.getKeys();
  50099. for (var index = 0; index < keys.length; index++) {
  50100. var animationKey = keys[index];
  50101. var key = {};
  50102. key.frame = animationKey.frame;
  50103. switch (dataType) {
  50104. case Animation.ANIMATIONTYPE_FLOAT:
  50105. key.values = [animationKey.value];
  50106. break;
  50107. case Animation.ANIMATIONTYPE_QUATERNION:
  50108. case Animation.ANIMATIONTYPE_MATRIX:
  50109. case Animation.ANIMATIONTYPE_VECTOR3:
  50110. case Animation.ANIMATIONTYPE_COLOR3:
  50111. key.values = animationKey.value.asArray();
  50112. break;
  50113. }
  50114. serializationObject.keys.push(key);
  50115. }
  50116. serializationObject.ranges = [];
  50117. for (var name in this._ranges) {
  50118. var source = this._ranges[name];
  50119. if (!source) {
  50120. continue;
  50121. }
  50122. var range = {};
  50123. range.name = name;
  50124. range.from = source.from;
  50125. range.to = source.to;
  50126. serializationObject.ranges.push(range);
  50127. }
  50128. return serializationObject;
  50129. };
  50130. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  50131. /**
  50132. * Get the float animation type
  50133. */
  50134. get: function () {
  50135. return Animation._ANIMATIONTYPE_FLOAT;
  50136. },
  50137. enumerable: true,
  50138. configurable: true
  50139. });
  50140. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  50141. /**
  50142. * Get the Vector3 animation type
  50143. */
  50144. get: function () {
  50145. return Animation._ANIMATIONTYPE_VECTOR3;
  50146. },
  50147. enumerable: true,
  50148. configurable: true
  50149. });
  50150. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  50151. /**
  50152. * Get the Vectpr2 animation type
  50153. */
  50154. get: function () {
  50155. return Animation._ANIMATIONTYPE_VECTOR2;
  50156. },
  50157. enumerable: true,
  50158. configurable: true
  50159. });
  50160. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  50161. /**
  50162. * Get the Size animation type
  50163. */
  50164. get: function () {
  50165. return Animation._ANIMATIONTYPE_SIZE;
  50166. },
  50167. enumerable: true,
  50168. configurable: true
  50169. });
  50170. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  50171. /**
  50172. * Get the Quaternion animation type
  50173. */
  50174. get: function () {
  50175. return Animation._ANIMATIONTYPE_QUATERNION;
  50176. },
  50177. enumerable: true,
  50178. configurable: true
  50179. });
  50180. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  50181. /**
  50182. * Get the Matrix animation type
  50183. */
  50184. get: function () {
  50185. return Animation._ANIMATIONTYPE_MATRIX;
  50186. },
  50187. enumerable: true,
  50188. configurable: true
  50189. });
  50190. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  50191. /**
  50192. * Get the Color3 animation type
  50193. */
  50194. get: function () {
  50195. return Animation._ANIMATIONTYPE_COLOR3;
  50196. },
  50197. enumerable: true,
  50198. configurable: true
  50199. });
  50200. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  50201. /**
  50202. * Get the Relative Loop Mode
  50203. */
  50204. get: function () {
  50205. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  50206. },
  50207. enumerable: true,
  50208. configurable: true
  50209. });
  50210. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  50211. /**
  50212. * Get the Cycle Loop Mode
  50213. */
  50214. get: function () {
  50215. return Animation._ANIMATIONLOOPMODE_CYCLE;
  50216. },
  50217. enumerable: true,
  50218. configurable: true
  50219. });
  50220. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  50221. /**
  50222. * Get the Constant Loop Mode
  50223. */
  50224. get: function () {
  50225. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  50226. },
  50227. enumerable: true,
  50228. configurable: true
  50229. });
  50230. /** @hidden */
  50231. Animation._UniversalLerp = function (left, right, amount) {
  50232. var constructor = left.constructor;
  50233. if (constructor.Lerp) { // Lerp supported
  50234. return constructor.Lerp(left, right, amount);
  50235. }
  50236. else if (constructor.Slerp) { // Slerp supported
  50237. return constructor.Slerp(left, right, amount);
  50238. }
  50239. else if (left.toFixed) { // Number
  50240. return left * (1.0 - amount) + amount * right;
  50241. }
  50242. else { // Blending not supported
  50243. return right;
  50244. }
  50245. };
  50246. /**
  50247. * Parses an animation object and creates an animation
  50248. * @param parsedAnimation Parsed animation object
  50249. * @returns Animation object
  50250. */
  50251. Animation.Parse = function (parsedAnimation) {
  50252. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  50253. var dataType = parsedAnimation.dataType;
  50254. var keys = [];
  50255. var data;
  50256. var index;
  50257. if (parsedAnimation.enableBlending) {
  50258. animation.enableBlending = parsedAnimation.enableBlending;
  50259. }
  50260. if (parsedAnimation.blendingSpeed) {
  50261. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  50262. }
  50263. for (index = 0; index < parsedAnimation.keys.length; index++) {
  50264. var key = parsedAnimation.keys[index];
  50265. var inTangent;
  50266. var outTangent;
  50267. switch (dataType) {
  50268. case Animation.ANIMATIONTYPE_FLOAT:
  50269. data = key.values[0];
  50270. if (key.values.length >= 1) {
  50271. inTangent = key.values[1];
  50272. }
  50273. if (key.values.length >= 2) {
  50274. outTangent = key.values[2];
  50275. }
  50276. break;
  50277. case Animation.ANIMATIONTYPE_QUATERNION:
  50278. data = BABYLON.Quaternion.FromArray(key.values);
  50279. if (key.values.length >= 8) {
  50280. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  50281. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  50282. inTangent = _inTangent;
  50283. }
  50284. }
  50285. if (key.values.length >= 12) {
  50286. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  50287. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  50288. outTangent = _outTangent;
  50289. }
  50290. }
  50291. break;
  50292. case Animation.ANIMATIONTYPE_MATRIX:
  50293. data = BABYLON.Matrix.FromArray(key.values);
  50294. break;
  50295. case Animation.ANIMATIONTYPE_COLOR3:
  50296. data = BABYLON.Color3.FromArray(key.values);
  50297. break;
  50298. case Animation.ANIMATIONTYPE_VECTOR3:
  50299. default:
  50300. data = BABYLON.Vector3.FromArray(key.values);
  50301. break;
  50302. }
  50303. var keyData = {};
  50304. keyData.frame = key.frame;
  50305. keyData.value = data;
  50306. if (inTangent != undefined) {
  50307. keyData.inTangent = inTangent;
  50308. }
  50309. if (outTangent != undefined) {
  50310. keyData.outTangent = outTangent;
  50311. }
  50312. keys.push(keyData);
  50313. }
  50314. animation.setKeys(keys);
  50315. if (parsedAnimation.ranges) {
  50316. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  50317. data = parsedAnimation.ranges[index];
  50318. animation.createRange(data.name, data.from, data.to);
  50319. }
  50320. }
  50321. return animation;
  50322. };
  50323. /**
  50324. * Appends the serialized animations from the source animations
  50325. * @param source Source containing the animations
  50326. * @param destination Target to store the animations
  50327. */
  50328. Animation.AppendSerializedAnimations = function (source, destination) {
  50329. if (source.animations) {
  50330. destination.animations = [];
  50331. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  50332. var animation = source.animations[animationIndex];
  50333. destination.animations.push(animation.serialize());
  50334. }
  50335. }
  50336. };
  50337. /**
  50338. * Use matrix interpolation instead of using direct key value when animating matrices
  50339. */
  50340. Animation.AllowMatricesInterpolation = false;
  50341. /**
  50342. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  50343. */
  50344. Animation.AllowMatrixDecomposeForInterpolation = true;
  50345. // Statics
  50346. /**
  50347. * Float animation type
  50348. */
  50349. Animation._ANIMATIONTYPE_FLOAT = 0;
  50350. /**
  50351. * Vector3 animation type
  50352. */
  50353. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  50354. /**
  50355. * Quaternion animation type
  50356. */
  50357. Animation._ANIMATIONTYPE_QUATERNION = 2;
  50358. /**
  50359. * Matrix animation type
  50360. */
  50361. Animation._ANIMATIONTYPE_MATRIX = 3;
  50362. /**
  50363. * Color3 animation type
  50364. */
  50365. Animation._ANIMATIONTYPE_COLOR3 = 4;
  50366. /**
  50367. * Vector2 animation type
  50368. */
  50369. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  50370. /**
  50371. * Size animation type
  50372. */
  50373. Animation._ANIMATIONTYPE_SIZE = 6;
  50374. /**
  50375. * Relative Loop Mode
  50376. */
  50377. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  50378. /**
  50379. * Cycle Loop Mode
  50380. */
  50381. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  50382. /**
  50383. * Constant Loop Mode
  50384. */
  50385. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  50386. return Animation;
  50387. }());
  50388. BABYLON.Animation = Animation;
  50389. })(BABYLON || (BABYLON = {}));
  50390. //# sourceMappingURL=babylon.animation.js.map
  50391. var BABYLON;
  50392. (function (BABYLON) {
  50393. /**
  50394. * This class defines the direct association between an animation and a target
  50395. */
  50396. var TargetedAnimation = /** @class */ (function () {
  50397. function TargetedAnimation() {
  50398. }
  50399. return TargetedAnimation;
  50400. }());
  50401. BABYLON.TargetedAnimation = TargetedAnimation;
  50402. /**
  50403. * Use this class to create coordinated animations on multiple targets
  50404. */
  50405. var AnimationGroup = /** @class */ (function () {
  50406. function AnimationGroup(name, scene) {
  50407. if (scene === void 0) { scene = null; }
  50408. this.name = name;
  50409. this._targetedAnimations = new Array();
  50410. this._animatables = new Array();
  50411. this._from = Number.MAX_VALUE;
  50412. this._to = -Number.MAX_VALUE;
  50413. this._speedRatio = 1;
  50414. this.onAnimationEndObservable = new BABYLON.Observable();
  50415. /**
  50416. * This observable will notify when all animations have ended.
  50417. */
  50418. this.onAnimationGroupEndObservable = new BABYLON.Observable();
  50419. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  50420. this._scene.animationGroups.push(this);
  50421. }
  50422. Object.defineProperty(AnimationGroup.prototype, "from", {
  50423. /**
  50424. * Gets the first frame
  50425. */
  50426. get: function () {
  50427. return this._from;
  50428. },
  50429. enumerable: true,
  50430. configurable: true
  50431. });
  50432. Object.defineProperty(AnimationGroup.prototype, "to", {
  50433. /**
  50434. * Gets the last frame
  50435. */
  50436. get: function () {
  50437. return this._to;
  50438. },
  50439. enumerable: true,
  50440. configurable: true
  50441. });
  50442. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  50443. /**
  50444. * Define if the animations are started
  50445. */
  50446. get: function () {
  50447. return this._isStarted;
  50448. },
  50449. enumerable: true,
  50450. configurable: true
  50451. });
  50452. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  50453. /**
  50454. * Gets or sets the speed ratio to use for all animations
  50455. */
  50456. get: function () {
  50457. return this._speedRatio;
  50458. },
  50459. /**
  50460. * Gets or sets the speed ratio to use for all animations
  50461. */
  50462. set: function (value) {
  50463. if (this._speedRatio === value) {
  50464. return;
  50465. }
  50466. this._speedRatio = value;
  50467. for (var index = 0; index < this._animatables.length; index++) {
  50468. var animatable = this._animatables[index];
  50469. animatable.speedRatio = this._speedRatio;
  50470. }
  50471. },
  50472. enumerable: true,
  50473. configurable: true
  50474. });
  50475. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  50476. /**
  50477. * Gets the targeted animations for this animation group
  50478. */
  50479. get: function () {
  50480. return this._targetedAnimations;
  50481. },
  50482. enumerable: true,
  50483. configurable: true
  50484. });
  50485. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  50486. /**
  50487. * returning the list of animatables controlled by this animation group.
  50488. */
  50489. get: function () {
  50490. return this._animatables;
  50491. },
  50492. enumerable: true,
  50493. configurable: true
  50494. });
  50495. /**
  50496. * Add an animation (with its target) in the group
  50497. * @param animation defines the animation we want to add
  50498. * @param target defines the target of the animation
  50499. * @returns the {BABYLON.TargetedAnimation} object
  50500. */
  50501. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  50502. var targetedAnimation = {
  50503. animation: animation,
  50504. target: target
  50505. };
  50506. var keys = animation.getKeys();
  50507. if (this._from > keys[0].frame) {
  50508. this._from = keys[0].frame;
  50509. }
  50510. if (this._to < keys[keys.length - 1].frame) {
  50511. this._to = keys[keys.length - 1].frame;
  50512. }
  50513. this._targetedAnimations.push(targetedAnimation);
  50514. return targetedAnimation;
  50515. };
  50516. /**
  50517. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  50518. * It can add constant keys at begin or end
  50519. * @param beginFrame defines the new begin frame for all animations or the smallest begin frame of all animations if null (defaults to null)
  50520. * @param endFrame defines the new end frame for all animations or the largest end frame of all animations if null (defaults to null)
  50521. */
  50522. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  50523. if (beginFrame === void 0) { beginFrame = null; }
  50524. if (endFrame === void 0) { endFrame = null; }
  50525. if (beginFrame == null)
  50526. beginFrame = this._from;
  50527. if (endFrame == null)
  50528. endFrame = this._to;
  50529. for (var index = 0; index < this._targetedAnimations.length; index++) {
  50530. var targetedAnimation = this._targetedAnimations[index];
  50531. var keys = targetedAnimation.animation.getKeys();
  50532. var startKey = keys[0];
  50533. var endKey = keys[keys.length - 1];
  50534. if (startKey.frame > beginFrame) {
  50535. var newKey = {
  50536. frame: beginFrame,
  50537. value: startKey.value,
  50538. inTangent: startKey.inTangent,
  50539. outTangent: startKey.outTangent,
  50540. interpolation: startKey.interpolation
  50541. };
  50542. keys.splice(0, 0, newKey);
  50543. }
  50544. if (endKey.frame < endFrame) {
  50545. var newKey = {
  50546. frame: endFrame,
  50547. value: endKey.value,
  50548. inTangent: endKey.outTangent,
  50549. outTangent: endKey.outTangent,
  50550. interpolation: endKey.interpolation
  50551. };
  50552. keys.push(newKey);
  50553. }
  50554. }
  50555. this._from = beginFrame;
  50556. this._to = endFrame;
  50557. return this;
  50558. };
  50559. /**
  50560. * Start all animations on given targets
  50561. * @param loop defines if animations must loop
  50562. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  50563. * @param from defines the from key (optional)
  50564. * @param to defines the to key (optional)
  50565. * @returns the current animation group
  50566. */
  50567. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  50568. var _this = this;
  50569. if (loop === void 0) { loop = false; }
  50570. if (speedRatio === void 0) { speedRatio = 1; }
  50571. if (this._isStarted || this._targetedAnimations.length === 0) {
  50572. return this;
  50573. }
  50574. var _loop_1 = function (targetedAnimation) {
  50575. var animatable = this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio);
  50576. animatable.onAnimationEnd = function () {
  50577. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  50578. _this._checkAnimationGroupEnded(animatable);
  50579. };
  50580. this_1._animatables.push(animatable);
  50581. };
  50582. var this_1 = this;
  50583. for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {
  50584. var targetedAnimation = _a[_i];
  50585. _loop_1(targetedAnimation);
  50586. }
  50587. this._speedRatio = speedRatio;
  50588. this._isStarted = true;
  50589. return this;
  50590. };
  50591. /**
  50592. * Pause all animations
  50593. */
  50594. AnimationGroup.prototype.pause = function () {
  50595. if (!this._isStarted) {
  50596. return this;
  50597. }
  50598. for (var index = 0; index < this._animatables.length; index++) {
  50599. var animatable = this._animatables[index];
  50600. animatable.pause();
  50601. }
  50602. return this;
  50603. };
  50604. /**
  50605. * Play all animations to initial state
  50606. * This function will start() the animations if they were not started or will restart() them if they were paused
  50607. * @param loop defines if animations must loop
  50608. */
  50609. AnimationGroup.prototype.play = function (loop) {
  50610. // only if all animatables are ready and exist
  50611. if (this.isStarted && this._animatables.length === this._targetedAnimations.length) {
  50612. if (loop !== undefined) {
  50613. for (var index = 0; index < this._animatables.length; index++) {
  50614. var animatable = this._animatables[index];
  50615. animatable.loopAnimation = loop;
  50616. }
  50617. }
  50618. this.restart();
  50619. }
  50620. else {
  50621. this.stop();
  50622. this.start(loop, this._speedRatio);
  50623. }
  50624. return this;
  50625. };
  50626. /**
  50627. * Reset all animations to initial state
  50628. */
  50629. AnimationGroup.prototype.reset = function () {
  50630. if (!this._isStarted) {
  50631. return this;
  50632. }
  50633. for (var index = 0; index < this._animatables.length; index++) {
  50634. var animatable = this._animatables[index];
  50635. animatable.reset();
  50636. }
  50637. return this;
  50638. };
  50639. /**
  50640. * Restart animations from key 0
  50641. */
  50642. AnimationGroup.prototype.restart = function () {
  50643. if (!this._isStarted) {
  50644. return this;
  50645. }
  50646. for (var index = 0; index < this._animatables.length; index++) {
  50647. var animatable = this._animatables[index];
  50648. animatable.restart();
  50649. }
  50650. return this;
  50651. };
  50652. /**
  50653. * Stop all animations
  50654. */
  50655. AnimationGroup.prototype.stop = function () {
  50656. if (!this._isStarted) {
  50657. return this;
  50658. }
  50659. for (var index = 0; index < this._animatables.length; index++) {
  50660. var animatable = this._animatables[index];
  50661. animatable.stop();
  50662. }
  50663. this._isStarted = false;
  50664. return this;
  50665. };
  50666. /**
  50667. * Set animation weight for all animatables
  50668. * @param weight defines the weight to use
  50669. * @return the animationGroup
  50670. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  50671. */
  50672. AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {
  50673. for (var index = 0; index < this._animatables.length; index++) {
  50674. var animatable = this._animatables[index];
  50675. animatable.weight = weight;
  50676. }
  50677. return this;
  50678. };
  50679. /**
  50680. * Synchronize and normalize all animatables with a source animatable
  50681. * @param root defines the root animatable to synchronize with
  50682. * @return the animationGroup
  50683. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  50684. */
  50685. AnimationGroup.prototype.syncAllAnimationsWith = function (root) {
  50686. for (var index = 0; index < this._animatables.length; index++) {
  50687. var animatable = this._animatables[index];
  50688. animatable.syncWith(root);
  50689. }
  50690. return this;
  50691. };
  50692. /**
  50693. * Goes to a specific frame in this animation group
  50694. * @param frame the frame number to go to
  50695. * @return the animationGroup
  50696. */
  50697. AnimationGroup.prototype.goToFrame = function (frame) {
  50698. if (!this._isStarted) {
  50699. return this;
  50700. }
  50701. for (var index = 0; index < this._animatables.length; index++) {
  50702. var animatable = this._animatables[index];
  50703. animatable.goToFrame(frame);
  50704. }
  50705. return this;
  50706. };
  50707. /**
  50708. * Dispose all associated resources
  50709. */
  50710. AnimationGroup.prototype.dispose = function () {
  50711. this._targetedAnimations = [];
  50712. this._animatables = [];
  50713. var index = this._scene.animationGroups.indexOf(this);
  50714. if (index > -1) {
  50715. this._scene.animationGroups.splice(index, 1);
  50716. }
  50717. };
  50718. AnimationGroup.prototype._checkAnimationGroupEnded = function (animatable) {
  50719. // animatable should be taken out of the array
  50720. var idx = this._animatables.indexOf(animatable);
  50721. if (idx > -1) {
  50722. this._animatables.splice(idx, 1);
  50723. }
  50724. // all animatables were removed? animation group ended!
  50725. if (this._animatables.length === 0) {
  50726. this._isStarted = false;
  50727. this.onAnimationGroupEndObservable.notifyObservers(this);
  50728. }
  50729. };
  50730. return AnimationGroup;
  50731. }());
  50732. BABYLON.AnimationGroup = AnimationGroup;
  50733. })(BABYLON || (BABYLON = {}));
  50734. //# sourceMappingURL=babylon.animationGroup.js.map
  50735. var BABYLON;
  50736. (function (BABYLON) {
  50737. /**
  50738. * Defines a runtime animation
  50739. */
  50740. var RuntimeAnimation = /** @class */ (function () {
  50741. /**
  50742. * Create a new RuntimeAnimation object
  50743. * @param target defines the target of the animation
  50744. * @param animation defines the source animation object
  50745. * @param scene defines the hosting scene
  50746. * @param host defines the initiating Animatable
  50747. */
  50748. function RuntimeAnimation(target, animation, scene, host) {
  50749. var _this = this;
  50750. this._events = new Array();
  50751. /**
  50752. * The current frame of the runtime animation
  50753. */
  50754. this._currentFrame = 0;
  50755. /**
  50756. * The original value of the runtime animation
  50757. */
  50758. this._originalValue = new Array();
  50759. /**
  50760. * The offsets cache of the runtime animation
  50761. */
  50762. this._offsetsCache = {};
  50763. /**
  50764. * The high limits cache of the runtime animation
  50765. */
  50766. this._highLimitsCache = {};
  50767. /**
  50768. * Specifies if the runtime animation has been stopped
  50769. */
  50770. this._stopped = false;
  50771. /**
  50772. * The blending factor of the runtime animation
  50773. */
  50774. this._blendingFactor = 0;
  50775. /**
  50776. * The target path of the runtime animation
  50777. */
  50778. this._targetPath = "";
  50779. /**
  50780. * The weight of the runtime animation
  50781. */
  50782. this._weight = 1.0;
  50783. /**
  50784. * The ratio offset of the runtime animation
  50785. */
  50786. this._ratioOffset = 0;
  50787. /**
  50788. * The previous delay of the runtime animation
  50789. */
  50790. this._previousDelay = 0;
  50791. /**
  50792. * The previous ratio of the runtime animation
  50793. */
  50794. this._previousRatio = 0;
  50795. this._animation = animation;
  50796. this._target = target;
  50797. this._scene = scene;
  50798. this._host = host;
  50799. animation._runtimeAnimations.push(this);
  50800. // Cloning events locally
  50801. var events = animation.getEvents();
  50802. if (events && events.length > 0) {
  50803. events.forEach(function (e) {
  50804. _this._events.push(e._clone());
  50805. });
  50806. }
  50807. }
  50808. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  50809. /**
  50810. * Gets the current frame of the runtime animation
  50811. */
  50812. get: function () {
  50813. return this._currentFrame;
  50814. },
  50815. enumerable: true,
  50816. configurable: true
  50817. });
  50818. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  50819. /**
  50820. * Gets the weight of the runtime animation
  50821. */
  50822. get: function () {
  50823. return this._weight;
  50824. },
  50825. enumerable: true,
  50826. configurable: true
  50827. });
  50828. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  50829. /**
  50830. * Gets the current value of the runtime animation
  50831. */
  50832. get: function () {
  50833. return this._currentValue;
  50834. },
  50835. enumerable: true,
  50836. configurable: true
  50837. });
  50838. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  50839. /**
  50840. * Gets the target path of the runtime animation
  50841. */
  50842. get: function () {
  50843. return this._targetPath;
  50844. },
  50845. enumerable: true,
  50846. configurable: true
  50847. });
  50848. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  50849. /**
  50850. * Gets the actual target of the runtime animation
  50851. */
  50852. get: function () {
  50853. return this._activeTarget;
  50854. },
  50855. enumerable: true,
  50856. configurable: true
  50857. });
  50858. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  50859. /**
  50860. * Gets the animation from the runtime animation
  50861. */
  50862. get: function () {
  50863. return this._animation;
  50864. },
  50865. enumerable: true,
  50866. configurable: true
  50867. });
  50868. /**
  50869. * Resets the runtime animation to the beginning
  50870. * @param restoreOriginal defines whether to restore the target property to the original value
  50871. */
  50872. RuntimeAnimation.prototype.reset = function (restoreOriginal) {
  50873. if (restoreOriginal === void 0) { restoreOriginal = false; }
  50874. if (restoreOriginal) {
  50875. if (this._target instanceof Array) {
  50876. var index = 0;
  50877. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  50878. var target = _a[_i];
  50879. if (this._originalValue[index] !== undefined) {
  50880. this._setValue(target, this._originalValue[index], -1);
  50881. }
  50882. index++;
  50883. }
  50884. }
  50885. else {
  50886. if (this._originalValue[0] !== undefined) {
  50887. this._setValue(this._target, this._originalValue[0], -1);
  50888. }
  50889. }
  50890. }
  50891. this._offsetsCache = {};
  50892. this._highLimitsCache = {};
  50893. this._currentFrame = 0;
  50894. this._blendingFactor = 0;
  50895. this._originalValue = new Array();
  50896. // Events
  50897. for (var index = 0; index < this._events.length; index++) {
  50898. this._events[index].isDone = false;
  50899. }
  50900. };
  50901. /**
  50902. * Specifies if the runtime animation is stopped
  50903. * @returns Boolean specifying if the runtime animation is stopped
  50904. */
  50905. RuntimeAnimation.prototype.isStopped = function () {
  50906. return this._stopped;
  50907. };
  50908. /**
  50909. * Disposes of the runtime animation
  50910. */
  50911. RuntimeAnimation.prototype.dispose = function () {
  50912. var index = this._animation.runtimeAnimations.indexOf(this);
  50913. if (index > -1) {
  50914. this._animation.runtimeAnimations.splice(index, 1);
  50915. }
  50916. };
  50917. /**
  50918. * Interpolates the animation from the current frame
  50919. * @param currentFrame The frame to interpolate the animation to
  50920. * @param repeatCount The number of times that the animation should loop
  50921. * @param loopMode The type of looping mode to use
  50922. * @param offsetValue Animation offset value
  50923. * @param highLimitValue The high limit value
  50924. * @returns The interpolated value
  50925. */
  50926. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  50927. this._currentFrame = currentFrame;
  50928. if (this._animation.dataType === BABYLON.Animation.ANIMATIONTYPE_MATRIX && !this._workValue) {
  50929. this._workValue = BABYLON.Matrix.Zero();
  50930. }
  50931. return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
  50932. };
  50933. /**
  50934. * Apply the interpolated value to the target
  50935. * @param currentValue defines the value computed by the animation
  50936. * @param weight defines the weight to apply to this value (Defaults to 1.0)
  50937. */
  50938. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  50939. if (weight === void 0) { weight = 1.0; }
  50940. if (this._target instanceof Array) {
  50941. var index = 0;
  50942. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  50943. var target = _a[_i];
  50944. this._setValue(target, currentValue, weight, index);
  50945. index++;
  50946. }
  50947. }
  50948. else {
  50949. this._setValue(this._target, currentValue, weight);
  50950. }
  50951. };
  50952. RuntimeAnimation.prototype._setValue = function (target, currentValue, weight, targetIndex) {
  50953. if (targetIndex === void 0) { targetIndex = 0; }
  50954. // Set value
  50955. var path;
  50956. var destination;
  50957. var targetPropertyPath = this._animation.targetPropertyPath;
  50958. if (targetPropertyPath.length > 1) {
  50959. var property = target[targetPropertyPath[0]];
  50960. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  50961. property = property[targetPropertyPath[index]];
  50962. }
  50963. path = targetPropertyPath[targetPropertyPath.length - 1];
  50964. destination = property;
  50965. }
  50966. else {
  50967. path = targetPropertyPath[0];
  50968. destination = target;
  50969. }
  50970. this._targetPath = path;
  50971. this._activeTarget = destination;
  50972. this._weight = weight;
  50973. if (this._originalValue[targetIndex] === undefined) {
  50974. var originalValue = void 0;
  50975. if (destination.getRestPose && path === "_matrix") { // For bones
  50976. originalValue = destination.getRestPose();
  50977. }
  50978. else {
  50979. originalValue = destination[path];
  50980. }
  50981. if (originalValue && originalValue.clone) {
  50982. this._originalValue[targetIndex] = originalValue.clone();
  50983. }
  50984. else {
  50985. this._originalValue[targetIndex] = originalValue;
  50986. }
  50987. }
  50988. // Blending
  50989. var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  50990. if (enableBlending && this._blendingFactor <= 1.0) {
  50991. if (!this._originalBlendValue) {
  50992. var originalValue = destination[path];
  50993. if (originalValue.clone) {
  50994. this._originalBlendValue = originalValue.clone();
  50995. }
  50996. else {
  50997. this._originalBlendValue = originalValue;
  50998. }
  50999. }
  51000. if (this._originalBlendValue.m) { // Matrix
  51001. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  51002. if (this._currentValue) {
  51003. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  51004. }
  51005. else {
  51006. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51007. }
  51008. }
  51009. else {
  51010. if (this._currentValue) {
  51011. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  51012. }
  51013. else {
  51014. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51015. }
  51016. }
  51017. }
  51018. else {
  51019. this._currentValue = BABYLON.Animation._UniversalLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51020. }
  51021. var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  51022. this._blendingFactor += blendingSpeed;
  51023. }
  51024. else {
  51025. this._currentValue = currentValue;
  51026. }
  51027. if (weight !== -1.0) {
  51028. this._scene._registerTargetForLateAnimationBinding(this, this._originalValue[targetIndex]);
  51029. }
  51030. else {
  51031. destination[path] = this._currentValue;
  51032. }
  51033. if (target.markAsDirty) {
  51034. target.markAsDirty(this._animation.targetProperty);
  51035. }
  51036. };
  51037. /**
  51038. * Gets the loop pmode of the runtime animation
  51039. * @returns Loop Mode
  51040. */
  51041. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  51042. if (this._target && this._target.animationPropertiesOverride) {
  51043. return this._target.animationPropertiesOverride.loopMode;
  51044. }
  51045. return this._animation.loopMode;
  51046. };
  51047. /**
  51048. * Move the current animation to a given frame
  51049. * @param frame defines the frame to move to
  51050. */
  51051. RuntimeAnimation.prototype.goToFrame = function (frame) {
  51052. var keys = this._animation.getKeys();
  51053. if (frame < keys[0].frame) {
  51054. frame = keys[0].frame;
  51055. }
  51056. else if (frame > keys[keys.length - 1].frame) {
  51057. frame = keys[keys.length - 1].frame;
  51058. }
  51059. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  51060. this.setValue(currentValue, -1);
  51061. };
  51062. /**
  51063. * @hidden Internal use only
  51064. */
  51065. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  51066. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  51067. this._ratioOffset = this._previousRatio - newRatio;
  51068. };
  51069. /**
  51070. * Execute the current animation
  51071. * @param delay defines the delay to add to the current frame
  51072. * @param from defines the lower bound of the animation range
  51073. * @param to defines the upper bound of the animation range
  51074. * @param loop defines if the current animation must loop
  51075. * @param speedRatio defines the current speed ratio
  51076. * @param weight defines the weight of the animation (default is -1 so no weight)
  51077. * @returns a boolean indicating if the animation has ended
  51078. */
  51079. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  51080. if (weight === void 0) { weight = -1.0; }
  51081. var targetPropertyPath = this._animation.targetPropertyPath;
  51082. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  51083. this._stopped = true;
  51084. return false;
  51085. }
  51086. var returnValue = true;
  51087. var keys = this._animation.getKeys();
  51088. // Adding a start key at frame 0 if missing
  51089. if (keys[0].frame !== 0) {
  51090. var newKey = { frame: 0, value: keys[0].value };
  51091. keys.splice(0, 0, newKey);
  51092. }
  51093. // Check limits
  51094. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  51095. from = keys[0].frame;
  51096. }
  51097. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  51098. to = keys[keys.length - 1].frame;
  51099. }
  51100. //to and from cannot be the same key
  51101. if (from === to) {
  51102. if (from > keys[0].frame) {
  51103. from--;
  51104. }
  51105. else if (to < keys[keys.length - 1].frame) {
  51106. to++;
  51107. }
  51108. }
  51109. // Compute ratio
  51110. var range = to - from;
  51111. var offsetValue;
  51112. // ratio represents the frame delta between from and to
  51113. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  51114. var highLimitValue = 0;
  51115. this._previousDelay = delay;
  51116. this._previousRatio = ratio;
  51117. if (((to > from && ratio >= range) || (from > to && ratio <= range)) && !loop) { // If we are out of range and not looping get back to caller
  51118. returnValue = false;
  51119. highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);
  51120. }
  51121. else {
  51122. // Get max value if required
  51123. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  51124. var keyOffset = to.toString() + from.toString();
  51125. if (!this._offsetsCache[keyOffset]) {
  51126. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51127. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51128. switch (this._animation.dataType) {
  51129. // Float
  51130. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51131. this._offsetsCache[keyOffset] = toValue - fromValue;
  51132. break;
  51133. // Quaternion
  51134. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51135. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51136. break;
  51137. // Vector3
  51138. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51139. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51140. // Vector2
  51141. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51142. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51143. // Size
  51144. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51145. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51146. // Color3
  51147. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51148. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51149. default:
  51150. break;
  51151. }
  51152. this._highLimitsCache[keyOffset] = toValue;
  51153. }
  51154. highLimitValue = this._highLimitsCache[keyOffset];
  51155. offsetValue = this._offsetsCache[keyOffset];
  51156. }
  51157. }
  51158. if (offsetValue === undefined) {
  51159. switch (this._animation.dataType) {
  51160. // Float
  51161. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51162. offsetValue = 0;
  51163. break;
  51164. // Quaternion
  51165. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51166. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  51167. break;
  51168. // Vector3
  51169. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51170. offsetValue = BABYLON.Vector3.Zero();
  51171. break;
  51172. // Vector2
  51173. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51174. offsetValue = BABYLON.Vector2.Zero();
  51175. break;
  51176. // Size
  51177. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51178. offsetValue = BABYLON.Size.Zero();
  51179. break;
  51180. // Color3
  51181. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51182. offsetValue = BABYLON.Color3.Black();
  51183. }
  51184. }
  51185. // Compute value
  51186. var repeatCount = (ratio / range) >> 0;
  51187. var currentFrame = returnValue ? from + ratio % range : to;
  51188. // Need to normalize?
  51189. if (this._host && this._host.syncRoot) {
  51190. var syncRoot = this._host.syncRoot;
  51191. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  51192. currentFrame = from + (to - from) * hostNormalizedFrame;
  51193. }
  51194. // Reset events if looping
  51195. var events = this._events;
  51196. if (range > 0 && this.currentFrame > currentFrame ||
  51197. range < 0 && this.currentFrame < currentFrame) {
  51198. // Need to reset animation events
  51199. for (var index = 0; index < events.length; index++) {
  51200. if (!events[index].onlyOnce) {
  51201. // reset event, the animation is looping
  51202. events[index].isDone = false;
  51203. }
  51204. }
  51205. }
  51206. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  51207. // Set value
  51208. this.setValue(currentValue, weight);
  51209. // Check events
  51210. for (var index = 0; index < events.length; index++) {
  51211. // Make sure current frame has passed event frame and that event frame is within the current range
  51212. // Also, handle both forward and reverse animations
  51213. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  51214. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  51215. var event = events[index];
  51216. if (!event.isDone) {
  51217. // If event should be done only once, remove it.
  51218. if (event.onlyOnce) {
  51219. events.splice(index, 1);
  51220. index--;
  51221. }
  51222. event.isDone = true;
  51223. event.action();
  51224. } // Don't do anything if the event has already be done.
  51225. }
  51226. }
  51227. if (!returnValue) {
  51228. this._stopped = true;
  51229. }
  51230. return returnValue;
  51231. };
  51232. return RuntimeAnimation;
  51233. }());
  51234. BABYLON.RuntimeAnimation = RuntimeAnimation;
  51235. })(BABYLON || (BABYLON = {}));
  51236. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  51237. var BABYLON;
  51238. (function (BABYLON) {
  51239. var Animatable = /** @class */ (function () {
  51240. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  51241. if (fromFrame === void 0) { fromFrame = 0; }
  51242. if (toFrame === void 0) { toFrame = 100; }
  51243. if (loopAnimation === void 0) { loopAnimation = false; }
  51244. if (speedRatio === void 0) { speedRatio = 1.0; }
  51245. this.target = target;
  51246. this.fromFrame = fromFrame;
  51247. this.toFrame = toFrame;
  51248. this.loopAnimation = loopAnimation;
  51249. this.onAnimationEnd = onAnimationEnd;
  51250. this._localDelayOffset = null;
  51251. this._pausedDelay = null;
  51252. this._runtimeAnimations = new Array();
  51253. this._paused = false;
  51254. this._speedRatio = 1;
  51255. this._weight = -1.0;
  51256. this.animationStarted = false;
  51257. /**
  51258. * Observer raised when the animation ends
  51259. */
  51260. this.onAnimationEndObservable = new BABYLON.Observable();
  51261. this._scene = scene;
  51262. if (animations) {
  51263. this.appendAnimations(target, animations);
  51264. }
  51265. this._speedRatio = speedRatio;
  51266. scene._activeAnimatables.push(this);
  51267. }
  51268. Object.defineProperty(Animatable.prototype, "syncRoot", {
  51269. /**
  51270. * Gets the root Animatable used to synchronize and normalize animations
  51271. */
  51272. get: function () {
  51273. return this._syncRoot;
  51274. },
  51275. enumerable: true,
  51276. configurable: true
  51277. });
  51278. Object.defineProperty(Animatable.prototype, "masterFrame", {
  51279. /**
  51280. * Gets the current frame of the first RuntimeAnimation
  51281. * Used to synchronize Animatables
  51282. */
  51283. get: function () {
  51284. if (this._runtimeAnimations.length === 0) {
  51285. return 0;
  51286. }
  51287. return this._runtimeAnimations[0].currentFrame;
  51288. },
  51289. enumerable: true,
  51290. configurable: true
  51291. });
  51292. Object.defineProperty(Animatable.prototype, "weight", {
  51293. /**
  51294. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  51295. */
  51296. get: function () {
  51297. return this._weight;
  51298. },
  51299. set: function (value) {
  51300. if (value === -1) { // -1 is ok and means no weight
  51301. this._weight = -1;
  51302. return;
  51303. }
  51304. // Else weight must be in [0, 1] range
  51305. this._weight = Math.min(Math.max(value, 0), 1.0);
  51306. },
  51307. enumerable: true,
  51308. configurable: true
  51309. });
  51310. Object.defineProperty(Animatable.prototype, "speedRatio", {
  51311. /**
  51312. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  51313. */
  51314. get: function () {
  51315. return this._speedRatio;
  51316. },
  51317. set: function (value) {
  51318. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  51319. var animation = this._runtimeAnimations[index];
  51320. animation._prepareForSpeedRatioChange(value);
  51321. }
  51322. this._speedRatio = value;
  51323. },
  51324. enumerable: true,
  51325. configurable: true
  51326. });
  51327. // Methods
  51328. /**
  51329. * Synchronize and normalize current Animatable with a source Animatable
  51330. * This is useful when using animation weights and when animations are not of the same length
  51331. * @param root defines the root Animatable to synchronize with
  51332. * @returns the current Animatable
  51333. */
  51334. Animatable.prototype.syncWith = function (root) {
  51335. this._syncRoot = root;
  51336. if (root) {
  51337. // Make sure this animatable will animate after the root
  51338. var index = this._scene._activeAnimatables.indexOf(this);
  51339. if (index > -1) {
  51340. this._scene._activeAnimatables.splice(index, 1);
  51341. this._scene._activeAnimatables.push(this);
  51342. }
  51343. }
  51344. return this;
  51345. };
  51346. Animatable.prototype.getAnimations = function () {
  51347. return this._runtimeAnimations;
  51348. };
  51349. Animatable.prototype.appendAnimations = function (target, animations) {
  51350. for (var index = 0; index < animations.length; index++) {
  51351. var animation = animations[index];
  51352. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  51353. }
  51354. };
  51355. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  51356. var runtimeAnimations = this._runtimeAnimations;
  51357. for (var index = 0; index < runtimeAnimations.length; index++) {
  51358. if (runtimeAnimations[index].animation.targetProperty === property) {
  51359. return runtimeAnimations[index].animation;
  51360. }
  51361. }
  51362. return null;
  51363. };
  51364. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  51365. var runtimeAnimations = this._runtimeAnimations;
  51366. for (var index = 0; index < runtimeAnimations.length; index++) {
  51367. if (runtimeAnimations[index].animation.targetProperty === property) {
  51368. return runtimeAnimations[index];
  51369. }
  51370. }
  51371. return null;
  51372. };
  51373. Animatable.prototype.reset = function () {
  51374. var runtimeAnimations = this._runtimeAnimations;
  51375. for (var index = 0; index < runtimeAnimations.length; index++) {
  51376. runtimeAnimations[index].reset(true);
  51377. }
  51378. this._localDelayOffset = null;
  51379. this._pausedDelay = null;
  51380. };
  51381. Animatable.prototype.enableBlending = function (blendingSpeed) {
  51382. var runtimeAnimations = this._runtimeAnimations;
  51383. for (var index = 0; index < runtimeAnimations.length; index++) {
  51384. runtimeAnimations[index].animation.enableBlending = true;
  51385. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  51386. }
  51387. };
  51388. Animatable.prototype.disableBlending = function () {
  51389. var runtimeAnimations = this._runtimeAnimations;
  51390. for (var index = 0; index < runtimeAnimations.length; index++) {
  51391. runtimeAnimations[index].animation.enableBlending = false;
  51392. }
  51393. };
  51394. Animatable.prototype.goToFrame = function (frame) {
  51395. var runtimeAnimations = this._runtimeAnimations;
  51396. if (runtimeAnimations[0]) {
  51397. var fps = runtimeAnimations[0].animation.framePerSecond;
  51398. var currentFrame = runtimeAnimations[0].currentFrame;
  51399. var adjustTime = frame - currentFrame;
  51400. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  51401. if (this._localDelayOffset === null) {
  51402. this._localDelayOffset = 0;
  51403. }
  51404. this._localDelayOffset -= delay;
  51405. }
  51406. for (var index = 0; index < runtimeAnimations.length; index++) {
  51407. runtimeAnimations[index].goToFrame(frame);
  51408. }
  51409. };
  51410. Animatable.prototype.pause = function () {
  51411. if (this._paused) {
  51412. return;
  51413. }
  51414. this._paused = true;
  51415. };
  51416. Animatable.prototype.restart = function () {
  51417. this._paused = false;
  51418. };
  51419. Animatable.prototype._raiseOnAnimationEnd = function () {
  51420. if (this.onAnimationEnd) {
  51421. this.onAnimationEnd();
  51422. }
  51423. this.onAnimationEndObservable.notifyObservers(this);
  51424. };
  51425. Animatable.prototype.stop = function (animationName) {
  51426. if (animationName) {
  51427. var idx = this._scene._activeAnimatables.indexOf(this);
  51428. if (idx > -1) {
  51429. var runtimeAnimations = this._runtimeAnimations;
  51430. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  51431. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  51432. continue;
  51433. }
  51434. runtimeAnimations[index].dispose();
  51435. runtimeAnimations.splice(index, 1);
  51436. }
  51437. if (runtimeAnimations.length == 0) {
  51438. this._scene._activeAnimatables.splice(idx, 1);
  51439. this._raiseOnAnimationEnd();
  51440. }
  51441. }
  51442. }
  51443. else {
  51444. var index = this._scene._activeAnimatables.indexOf(this);
  51445. if (index > -1) {
  51446. this._scene._activeAnimatables.splice(index, 1);
  51447. var runtimeAnimations = this._runtimeAnimations;
  51448. for (var index = 0; index < runtimeAnimations.length; index++) {
  51449. runtimeAnimations[index].dispose();
  51450. }
  51451. this._raiseOnAnimationEnd();
  51452. }
  51453. }
  51454. };
  51455. /**
  51456. * Wait asynchronously for the animation to end
  51457. * @returns a promise which will be fullfilled when the animation ends
  51458. */
  51459. Animatable.prototype.waitAsync = function () {
  51460. var _this = this;
  51461. return new Promise(function (resolve, reject) {
  51462. _this.onAnimationEndObservable.add(function () {
  51463. resolve(_this);
  51464. }, undefined, undefined, _this, true);
  51465. });
  51466. };
  51467. /** @hidden */
  51468. Animatable.prototype._animate = function (delay) {
  51469. if (this._paused) {
  51470. this.animationStarted = false;
  51471. if (this._pausedDelay === null) {
  51472. this._pausedDelay = delay;
  51473. }
  51474. return true;
  51475. }
  51476. if (this._localDelayOffset === null) {
  51477. this._localDelayOffset = delay;
  51478. this._pausedDelay = null;
  51479. }
  51480. else if (this._pausedDelay !== null) {
  51481. this._localDelayOffset += delay - this._pausedDelay;
  51482. this._pausedDelay = null;
  51483. }
  51484. if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
  51485. return true;
  51486. }
  51487. // Animating
  51488. var running = false;
  51489. var runtimeAnimations = this._runtimeAnimations;
  51490. var index;
  51491. for (index = 0; index < runtimeAnimations.length; index++) {
  51492. var animation = runtimeAnimations[index];
  51493. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  51494. running = running || isRunning;
  51495. }
  51496. this.animationStarted = running;
  51497. if (!running) {
  51498. // Remove from active animatables
  51499. index = this._scene._activeAnimatables.indexOf(this);
  51500. this._scene._activeAnimatables.splice(index, 1);
  51501. // Dispose all runtime animations
  51502. for (index = 0; index < runtimeAnimations.length; index++) {
  51503. runtimeAnimations[index].dispose();
  51504. }
  51505. this._raiseOnAnimationEnd();
  51506. this.onAnimationEnd = null;
  51507. this.onAnimationEndObservable.clear();
  51508. }
  51509. return running;
  51510. };
  51511. return Animatable;
  51512. }());
  51513. BABYLON.Animatable = Animatable;
  51514. })(BABYLON || (BABYLON = {}));
  51515. //# sourceMappingURL=babylon.animatable.js.map
  51516. var BABYLON;
  51517. (function (BABYLON) {
  51518. var EasingFunction = /** @class */ (function () {
  51519. function EasingFunction() {
  51520. // Properties
  51521. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  51522. }
  51523. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  51524. get: function () {
  51525. return EasingFunction._EASINGMODE_EASEIN;
  51526. },
  51527. enumerable: true,
  51528. configurable: true
  51529. });
  51530. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  51531. get: function () {
  51532. return EasingFunction._EASINGMODE_EASEOUT;
  51533. },
  51534. enumerable: true,
  51535. configurable: true
  51536. });
  51537. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  51538. get: function () {
  51539. return EasingFunction._EASINGMODE_EASEINOUT;
  51540. },
  51541. enumerable: true,
  51542. configurable: true
  51543. });
  51544. EasingFunction.prototype.setEasingMode = function (easingMode) {
  51545. var n = Math.min(Math.max(easingMode, 0), 2);
  51546. this._easingMode = n;
  51547. };
  51548. EasingFunction.prototype.getEasingMode = function () {
  51549. return this._easingMode;
  51550. };
  51551. EasingFunction.prototype.easeInCore = function (gradient) {
  51552. throw new Error('You must implement this method');
  51553. };
  51554. EasingFunction.prototype.ease = function (gradient) {
  51555. switch (this._easingMode) {
  51556. case EasingFunction.EASINGMODE_EASEIN:
  51557. return this.easeInCore(gradient);
  51558. case EasingFunction.EASINGMODE_EASEOUT:
  51559. return (1 - this.easeInCore(1 - gradient));
  51560. }
  51561. if (gradient >= 0.5) {
  51562. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  51563. }
  51564. return (this.easeInCore(gradient * 2) * 0.5);
  51565. };
  51566. //Statics
  51567. EasingFunction._EASINGMODE_EASEIN = 0;
  51568. EasingFunction._EASINGMODE_EASEOUT = 1;
  51569. EasingFunction._EASINGMODE_EASEINOUT = 2;
  51570. return EasingFunction;
  51571. }());
  51572. BABYLON.EasingFunction = EasingFunction;
  51573. var CircleEase = /** @class */ (function (_super) {
  51574. __extends(CircleEase, _super);
  51575. function CircleEase() {
  51576. return _super !== null && _super.apply(this, arguments) || this;
  51577. }
  51578. CircleEase.prototype.easeInCore = function (gradient) {
  51579. gradient = Math.max(0, Math.min(1, gradient));
  51580. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  51581. };
  51582. return CircleEase;
  51583. }(EasingFunction));
  51584. BABYLON.CircleEase = CircleEase;
  51585. var BackEase = /** @class */ (function (_super) {
  51586. __extends(BackEase, _super);
  51587. function BackEase(amplitude) {
  51588. if (amplitude === void 0) { amplitude = 1; }
  51589. var _this = _super.call(this) || this;
  51590. _this.amplitude = amplitude;
  51591. return _this;
  51592. }
  51593. BackEase.prototype.easeInCore = function (gradient) {
  51594. var num = Math.max(0, this.amplitude);
  51595. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  51596. };
  51597. return BackEase;
  51598. }(EasingFunction));
  51599. BABYLON.BackEase = BackEase;
  51600. var BounceEase = /** @class */ (function (_super) {
  51601. __extends(BounceEase, _super);
  51602. function BounceEase(bounces, bounciness) {
  51603. if (bounces === void 0) { bounces = 3; }
  51604. if (bounciness === void 0) { bounciness = 2; }
  51605. var _this = _super.call(this) || this;
  51606. _this.bounces = bounces;
  51607. _this.bounciness = bounciness;
  51608. return _this;
  51609. }
  51610. BounceEase.prototype.easeInCore = function (gradient) {
  51611. var y = Math.max(0.0, this.bounces);
  51612. var bounciness = this.bounciness;
  51613. if (bounciness <= 1.0) {
  51614. bounciness = 1.001;
  51615. }
  51616. var num9 = Math.pow(bounciness, y);
  51617. var num5 = 1.0 - bounciness;
  51618. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  51619. var num15 = gradient * num4;
  51620. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  51621. var num3 = Math.floor(num65);
  51622. var num13 = num3 + 1.0;
  51623. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  51624. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  51625. var num7 = (num8 + num12) * 0.5;
  51626. var num6 = gradient - num7;
  51627. var num2 = num7 - num8;
  51628. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  51629. };
  51630. return BounceEase;
  51631. }(EasingFunction));
  51632. BABYLON.BounceEase = BounceEase;
  51633. var CubicEase = /** @class */ (function (_super) {
  51634. __extends(CubicEase, _super);
  51635. function CubicEase() {
  51636. return _super !== null && _super.apply(this, arguments) || this;
  51637. }
  51638. CubicEase.prototype.easeInCore = function (gradient) {
  51639. return (gradient * gradient * gradient);
  51640. };
  51641. return CubicEase;
  51642. }(EasingFunction));
  51643. BABYLON.CubicEase = CubicEase;
  51644. var ElasticEase = /** @class */ (function (_super) {
  51645. __extends(ElasticEase, _super);
  51646. function ElasticEase(oscillations, springiness) {
  51647. if (oscillations === void 0) { oscillations = 3; }
  51648. if (springiness === void 0) { springiness = 3; }
  51649. var _this = _super.call(this) || this;
  51650. _this.oscillations = oscillations;
  51651. _this.springiness = springiness;
  51652. return _this;
  51653. }
  51654. ElasticEase.prototype.easeInCore = function (gradient) {
  51655. var num2;
  51656. var num3 = Math.max(0.0, this.oscillations);
  51657. var num = Math.max(0.0, this.springiness);
  51658. if (num == 0) {
  51659. num2 = gradient;
  51660. }
  51661. else {
  51662. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  51663. }
  51664. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  51665. };
  51666. return ElasticEase;
  51667. }(EasingFunction));
  51668. BABYLON.ElasticEase = ElasticEase;
  51669. var ExponentialEase = /** @class */ (function (_super) {
  51670. __extends(ExponentialEase, _super);
  51671. function ExponentialEase(exponent) {
  51672. if (exponent === void 0) { exponent = 2; }
  51673. var _this = _super.call(this) || this;
  51674. _this.exponent = exponent;
  51675. return _this;
  51676. }
  51677. ExponentialEase.prototype.easeInCore = function (gradient) {
  51678. if (this.exponent <= 0) {
  51679. return gradient;
  51680. }
  51681. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  51682. };
  51683. return ExponentialEase;
  51684. }(EasingFunction));
  51685. BABYLON.ExponentialEase = ExponentialEase;
  51686. var PowerEase = /** @class */ (function (_super) {
  51687. __extends(PowerEase, _super);
  51688. function PowerEase(power) {
  51689. if (power === void 0) { power = 2; }
  51690. var _this = _super.call(this) || this;
  51691. _this.power = power;
  51692. return _this;
  51693. }
  51694. PowerEase.prototype.easeInCore = function (gradient) {
  51695. var y = Math.max(0.0, this.power);
  51696. return Math.pow(gradient, y);
  51697. };
  51698. return PowerEase;
  51699. }(EasingFunction));
  51700. BABYLON.PowerEase = PowerEase;
  51701. var QuadraticEase = /** @class */ (function (_super) {
  51702. __extends(QuadraticEase, _super);
  51703. function QuadraticEase() {
  51704. return _super !== null && _super.apply(this, arguments) || this;
  51705. }
  51706. QuadraticEase.prototype.easeInCore = function (gradient) {
  51707. return (gradient * gradient);
  51708. };
  51709. return QuadraticEase;
  51710. }(EasingFunction));
  51711. BABYLON.QuadraticEase = QuadraticEase;
  51712. var QuarticEase = /** @class */ (function (_super) {
  51713. __extends(QuarticEase, _super);
  51714. function QuarticEase() {
  51715. return _super !== null && _super.apply(this, arguments) || this;
  51716. }
  51717. QuarticEase.prototype.easeInCore = function (gradient) {
  51718. return (gradient * gradient * gradient * gradient);
  51719. };
  51720. return QuarticEase;
  51721. }(EasingFunction));
  51722. BABYLON.QuarticEase = QuarticEase;
  51723. var QuinticEase = /** @class */ (function (_super) {
  51724. __extends(QuinticEase, _super);
  51725. function QuinticEase() {
  51726. return _super !== null && _super.apply(this, arguments) || this;
  51727. }
  51728. QuinticEase.prototype.easeInCore = function (gradient) {
  51729. return (gradient * gradient * gradient * gradient * gradient);
  51730. };
  51731. return QuinticEase;
  51732. }(EasingFunction));
  51733. BABYLON.QuinticEase = QuinticEase;
  51734. var SineEase = /** @class */ (function (_super) {
  51735. __extends(SineEase, _super);
  51736. function SineEase() {
  51737. return _super !== null && _super.apply(this, arguments) || this;
  51738. }
  51739. SineEase.prototype.easeInCore = function (gradient) {
  51740. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  51741. };
  51742. return SineEase;
  51743. }(EasingFunction));
  51744. BABYLON.SineEase = SineEase;
  51745. var BezierCurveEase = /** @class */ (function (_super) {
  51746. __extends(BezierCurveEase, _super);
  51747. function BezierCurveEase(x1, y1, x2, y2) {
  51748. if (x1 === void 0) { x1 = 0; }
  51749. if (y1 === void 0) { y1 = 0; }
  51750. if (x2 === void 0) { x2 = 1; }
  51751. if (y2 === void 0) { y2 = 1; }
  51752. var _this = _super.call(this) || this;
  51753. _this.x1 = x1;
  51754. _this.y1 = y1;
  51755. _this.x2 = x2;
  51756. _this.y2 = y2;
  51757. return _this;
  51758. }
  51759. BezierCurveEase.prototype.easeInCore = function (gradient) {
  51760. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  51761. };
  51762. return BezierCurveEase;
  51763. }(EasingFunction));
  51764. BABYLON.BezierCurveEase = BezierCurveEase;
  51765. })(BABYLON || (BABYLON = {}));
  51766. //# sourceMappingURL=babylon.easing.js.map
  51767. var BABYLON;
  51768. (function (BABYLON) {
  51769. /**
  51770. * A Condition applied to an Action
  51771. */
  51772. var Condition = /** @class */ (function () {
  51773. /**
  51774. * Creates a new Condition
  51775. * @param actionManager the manager of the action the condition is applied to
  51776. */
  51777. function Condition(actionManager) {
  51778. this._actionManager = actionManager;
  51779. }
  51780. /**
  51781. * Check if the current condition is valid
  51782. * @returns a boolean
  51783. */
  51784. Condition.prototype.isValid = function () {
  51785. return true;
  51786. };
  51787. /**
  51788. * Internal only
  51789. * @hidden
  51790. */
  51791. Condition.prototype._getProperty = function (propertyPath) {
  51792. return this._actionManager._getProperty(propertyPath);
  51793. };
  51794. /**
  51795. * Internal only
  51796. * @hidden
  51797. */
  51798. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  51799. return this._actionManager._getEffectiveTarget(target, propertyPath);
  51800. };
  51801. /**
  51802. * Serialize placeholder for child classes
  51803. * @returns the serialized object
  51804. */
  51805. Condition.prototype.serialize = function () {
  51806. };
  51807. /**
  51808. * Internal only
  51809. * @hidden
  51810. */
  51811. Condition.prototype._serialize = function (serializedCondition) {
  51812. return {
  51813. type: 2,
  51814. children: [],
  51815. name: serializedCondition.name,
  51816. properties: serializedCondition.properties
  51817. };
  51818. };
  51819. return Condition;
  51820. }());
  51821. BABYLON.Condition = Condition;
  51822. /**
  51823. * Defines specific conditional operators as extensions of Condition
  51824. */
  51825. var ValueCondition = /** @class */ (function (_super) {
  51826. __extends(ValueCondition, _super);
  51827. /**
  51828. * Creates a new ValueCondition
  51829. * @param actionManager manager for the action the condition applies to
  51830. * @param target for the action
  51831. * @param propertyPath path to specify the property of the target the conditional operator uses
  51832. * @param value the value compared by the conditional operator against the current value of the property
  51833. * @param operator the conditional operator, default ValueCondition.IsEqual
  51834. */
  51835. function ValueCondition(actionManager, target,
  51836. /** path to specify the property of the target the conditional operator uses */
  51837. propertyPath,
  51838. /** the value compared by the conditional operator against the current value of the property */
  51839. value,
  51840. /** the conditional operator, default ValueCondition.IsEqual */
  51841. operator) {
  51842. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  51843. var _this = _super.call(this, actionManager) || this;
  51844. _this.propertyPath = propertyPath;
  51845. _this.value = value;
  51846. _this.operator = operator;
  51847. _this._target = target;
  51848. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  51849. _this._property = _this._getProperty(_this.propertyPath);
  51850. return _this;
  51851. }
  51852. Object.defineProperty(ValueCondition, "IsEqual", {
  51853. /**
  51854. * returns the number for IsEqual
  51855. */
  51856. get: function () {
  51857. return ValueCondition._IsEqual;
  51858. },
  51859. enumerable: true,
  51860. configurable: true
  51861. });
  51862. Object.defineProperty(ValueCondition, "IsDifferent", {
  51863. /**
  51864. * Returns the number for IsDifferent
  51865. */
  51866. get: function () {
  51867. return ValueCondition._IsDifferent;
  51868. },
  51869. enumerable: true,
  51870. configurable: true
  51871. });
  51872. Object.defineProperty(ValueCondition, "IsGreater", {
  51873. /**
  51874. * Returns the number for IsGreater
  51875. */
  51876. get: function () {
  51877. return ValueCondition._IsGreater;
  51878. },
  51879. enumerable: true,
  51880. configurable: true
  51881. });
  51882. Object.defineProperty(ValueCondition, "IsLesser", {
  51883. /**
  51884. * Returns the number for IsLesser
  51885. */
  51886. get: function () {
  51887. return ValueCondition._IsLesser;
  51888. },
  51889. enumerable: true,
  51890. configurable: true
  51891. });
  51892. /**
  51893. * Compares the given value with the property value for the specified conditional operator
  51894. * @returns the result of the comparison
  51895. */
  51896. ValueCondition.prototype.isValid = function () {
  51897. switch (this.operator) {
  51898. case ValueCondition.IsGreater:
  51899. return this._effectiveTarget[this._property] > this.value;
  51900. case ValueCondition.IsLesser:
  51901. return this._effectiveTarget[this._property] < this.value;
  51902. case ValueCondition.IsEqual:
  51903. case ValueCondition.IsDifferent:
  51904. var check;
  51905. if (this.value.equals) {
  51906. check = this.value.equals(this._effectiveTarget[this._property]);
  51907. }
  51908. else {
  51909. check = this.value === this._effectiveTarget[this._property];
  51910. }
  51911. return this.operator === ValueCondition.IsEqual ? check : !check;
  51912. }
  51913. return false;
  51914. };
  51915. /**
  51916. * Serialize the ValueCondition into a JSON compatible object
  51917. * @returns serialization object
  51918. */
  51919. ValueCondition.prototype.serialize = function () {
  51920. return this._serialize({
  51921. name: "ValueCondition",
  51922. properties: [
  51923. BABYLON.Action._GetTargetProperty(this._target),
  51924. { name: "propertyPath", value: this.propertyPath },
  51925. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  51926. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  51927. ]
  51928. });
  51929. };
  51930. /**
  51931. * Gets the name of the conditional operator for the ValueCondition
  51932. * @param operator the conditional operator
  51933. * @returns the name
  51934. */
  51935. ValueCondition.GetOperatorName = function (operator) {
  51936. switch (operator) {
  51937. case ValueCondition._IsEqual: return "IsEqual";
  51938. case ValueCondition._IsDifferent: return "IsDifferent";
  51939. case ValueCondition._IsGreater: return "IsGreater";
  51940. case ValueCondition._IsLesser: return "IsLesser";
  51941. default: return "";
  51942. }
  51943. };
  51944. /**
  51945. * Internal only
  51946. * @hidden
  51947. */
  51948. ValueCondition._IsEqual = 0;
  51949. /**
  51950. * Internal only
  51951. * @hidden
  51952. */
  51953. ValueCondition._IsDifferent = 1;
  51954. /**
  51955. * Internal only
  51956. * @hidden
  51957. */
  51958. ValueCondition._IsGreater = 2;
  51959. /**
  51960. * Internal only
  51961. * @hidden
  51962. */
  51963. ValueCondition._IsLesser = 3;
  51964. return ValueCondition;
  51965. }(Condition));
  51966. BABYLON.ValueCondition = ValueCondition;
  51967. /**
  51968. * Defines a predicate condition as an extension of Condition
  51969. */
  51970. var PredicateCondition = /** @class */ (function (_super) {
  51971. __extends(PredicateCondition, _super);
  51972. /**
  51973. * Creates a new PredicateCondition
  51974. * @param actionManager manager for the action the condition applies to
  51975. * @param predicate defines the predicate function used to validate the condition
  51976. */
  51977. function PredicateCondition(actionManager,
  51978. /** defines the predicate function used to validate the condition */
  51979. predicate) {
  51980. var _this = _super.call(this, actionManager) || this;
  51981. _this.predicate = predicate;
  51982. return _this;
  51983. }
  51984. /**
  51985. * @returns the validity of the predicate condition
  51986. */
  51987. PredicateCondition.prototype.isValid = function () {
  51988. return this.predicate();
  51989. };
  51990. return PredicateCondition;
  51991. }(Condition));
  51992. BABYLON.PredicateCondition = PredicateCondition;
  51993. /**
  51994. * Defines a state condition as an extension of Condition
  51995. */
  51996. var StateCondition = /** @class */ (function (_super) {
  51997. __extends(StateCondition, _super);
  51998. /**
  51999. * Creates a new StateCondition
  52000. * @param actionManager manager for the action the condition applies to
  52001. * @param target of the condition
  52002. * @param value to compare with target state
  52003. */
  52004. function StateCondition(actionManager, target, value) {
  52005. var _this = _super.call(this, actionManager) || this;
  52006. _this.value = value;
  52007. _this._target = target;
  52008. return _this;
  52009. }
  52010. /**
  52011. * @returns the validity of the state
  52012. */
  52013. StateCondition.prototype.isValid = function () {
  52014. return this._target.state === this.value;
  52015. };
  52016. /**
  52017. * Serialize the StateCondition into a JSON compatible object
  52018. * @returns serialization object
  52019. */
  52020. StateCondition.prototype.serialize = function () {
  52021. return this._serialize({
  52022. name: "StateCondition",
  52023. properties: [
  52024. BABYLON.Action._GetTargetProperty(this._target),
  52025. { name: "value", value: this.value }
  52026. ]
  52027. });
  52028. };
  52029. return StateCondition;
  52030. }(Condition));
  52031. BABYLON.StateCondition = StateCondition;
  52032. })(BABYLON || (BABYLON = {}));
  52033. //# sourceMappingURL=babylon.condition.js.map
  52034. var BABYLON;
  52035. (function (BABYLON) {
  52036. /**
  52037. * The action to be carried out following a trigger
  52038. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  52039. */
  52040. var Action = /** @class */ (function () {
  52041. /**
  52042. * Creates a new Action
  52043. * @param triggerOptions the trigger, with or without parameters, for the action
  52044. * @param condition an optional determinant of action
  52045. */
  52046. function Action(
  52047. /** the trigger, with or without parameters, for the action */
  52048. triggerOptions, condition) {
  52049. this.triggerOptions = triggerOptions;
  52050. /**
  52051. * An event triggered prior to action being executed.
  52052. */
  52053. this.onBeforeExecuteObservable = new BABYLON.Observable();
  52054. if (triggerOptions.parameter) {
  52055. this.trigger = triggerOptions.trigger;
  52056. this._triggerParameter = triggerOptions.parameter;
  52057. }
  52058. else {
  52059. this.trigger = triggerOptions;
  52060. }
  52061. this._nextActiveAction = this;
  52062. this._condition = condition;
  52063. }
  52064. /**
  52065. * Internal only
  52066. * @hidden
  52067. */
  52068. Action.prototype._prepare = function () {
  52069. };
  52070. /**
  52071. * Gets the trigger parameters
  52072. * @returns the trigger parameters
  52073. */
  52074. Action.prototype.getTriggerParameter = function () {
  52075. return this._triggerParameter;
  52076. };
  52077. /**
  52078. * Internal only - executes current action event
  52079. * @hidden
  52080. */
  52081. Action.prototype._executeCurrent = function (evt) {
  52082. if (this._nextActiveAction._condition) {
  52083. var condition = this._nextActiveAction._condition;
  52084. var currentRenderId = this._actionManager.getScene().getRenderId();
  52085. // We cache the current evaluation for the current frame
  52086. if (condition._evaluationId === currentRenderId) {
  52087. if (!condition._currentResult) {
  52088. return;
  52089. }
  52090. }
  52091. else {
  52092. condition._evaluationId = currentRenderId;
  52093. if (!condition.isValid()) {
  52094. condition._currentResult = false;
  52095. return;
  52096. }
  52097. condition._currentResult = true;
  52098. }
  52099. }
  52100. this.onBeforeExecuteObservable.notifyObservers(this);
  52101. this._nextActiveAction.execute(evt);
  52102. this.skipToNextActiveAction();
  52103. };
  52104. /**
  52105. * Execute placeholder for child classes
  52106. * @param evt optional action event
  52107. */
  52108. Action.prototype.execute = function (evt) {
  52109. };
  52110. /**
  52111. * Skips to next active action
  52112. */
  52113. Action.prototype.skipToNextActiveAction = function () {
  52114. if (this._nextActiveAction._child) {
  52115. if (!this._nextActiveAction._child._actionManager) {
  52116. this._nextActiveAction._child._actionManager = this._actionManager;
  52117. }
  52118. this._nextActiveAction = this._nextActiveAction._child;
  52119. }
  52120. else {
  52121. this._nextActiveAction = this;
  52122. }
  52123. };
  52124. /**
  52125. * Adds action to chain of actions, may be a DoNothingAction
  52126. * @param action defines the next action to execute
  52127. * @returns The action passed in
  52128. * @see https://www.babylonjs-playground.com/#1T30HR#0
  52129. */
  52130. Action.prototype.then = function (action) {
  52131. this._child = action;
  52132. action._actionManager = this._actionManager;
  52133. action._prepare();
  52134. return action;
  52135. };
  52136. /**
  52137. * Internal only
  52138. * @hidden
  52139. */
  52140. Action.prototype._getProperty = function (propertyPath) {
  52141. return this._actionManager._getProperty(propertyPath);
  52142. };
  52143. /**
  52144. * Internal only
  52145. * @hidden
  52146. */
  52147. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  52148. return this._actionManager._getEffectiveTarget(target, propertyPath);
  52149. };
  52150. /**
  52151. * Serialize placeholder for child classes
  52152. * @param parent of child
  52153. * @returns the serialized object
  52154. */
  52155. Action.prototype.serialize = function (parent) {
  52156. };
  52157. /**
  52158. * Internal only called by serialize
  52159. * @hidden
  52160. */
  52161. Action.prototype._serialize = function (serializedAction, parent) {
  52162. var serializationObject = {
  52163. type: 1,
  52164. children: [],
  52165. name: serializedAction.name,
  52166. properties: serializedAction.properties || []
  52167. };
  52168. // Serialize child
  52169. if (this._child) {
  52170. this._child.serialize(serializationObject);
  52171. }
  52172. // Check if "this" has a condition
  52173. if (this._condition) {
  52174. var serializedCondition = this._condition.serialize();
  52175. serializedCondition.children.push(serializationObject);
  52176. if (parent) {
  52177. parent.children.push(serializedCondition);
  52178. }
  52179. return serializedCondition;
  52180. }
  52181. if (parent) {
  52182. parent.children.push(serializationObject);
  52183. }
  52184. return serializationObject;
  52185. };
  52186. /**
  52187. * Internal only
  52188. * @hidden
  52189. */
  52190. Action._SerializeValueAsString = function (value) {
  52191. if (typeof value === "number") {
  52192. return value.toString();
  52193. }
  52194. if (typeof value === "boolean") {
  52195. return value ? "true" : "false";
  52196. }
  52197. if (value instanceof BABYLON.Vector2) {
  52198. return value.x + ", " + value.y;
  52199. }
  52200. if (value instanceof BABYLON.Vector3) {
  52201. return value.x + ", " + value.y + ", " + value.z;
  52202. }
  52203. if (value instanceof BABYLON.Color3) {
  52204. return value.r + ", " + value.g + ", " + value.b;
  52205. }
  52206. if (value instanceof BABYLON.Color4) {
  52207. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  52208. }
  52209. return value; // string
  52210. };
  52211. /**
  52212. * Internal only
  52213. * @hidden
  52214. */
  52215. Action._GetTargetProperty = function (target) {
  52216. return {
  52217. name: "target",
  52218. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  52219. : target instanceof BABYLON.Light ? "LightProperties"
  52220. : target instanceof BABYLON.Camera ? "CameraProperties"
  52221. : "SceneProperties",
  52222. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  52223. };
  52224. };
  52225. return Action;
  52226. }());
  52227. BABYLON.Action = Action;
  52228. })(BABYLON || (BABYLON = {}));
  52229. //# sourceMappingURL=babylon.action.js.map
  52230. var BABYLON;
  52231. (function (BABYLON) {
  52232. /**
  52233. * ActionEvent is the event being sent when an action is triggered.
  52234. */
  52235. var ActionEvent = /** @class */ (function () {
  52236. /**
  52237. * Creates a new ActionEvent
  52238. * @param source The mesh or sprite that triggered the action
  52239. * @param pointerX The X mouse cursor position at the time of the event
  52240. * @param pointerY The Y mouse cursor position at the time of the event
  52241. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  52242. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  52243. * @param additionalData additional data for the event
  52244. */
  52245. function ActionEvent(
  52246. /** The mesh or sprite that triggered the action */
  52247. source,
  52248. /** The X mouse cursor position at the time of the event */
  52249. pointerX,
  52250. /** The Y mouse cursor position at the time of the event */
  52251. pointerY,
  52252. /** The mesh that is currently pointed at (can be null) */
  52253. meshUnderPointer,
  52254. /** the original (browser) event that triggered the ActionEvent */
  52255. sourceEvent,
  52256. /** additional data for the event */
  52257. additionalData) {
  52258. this.source = source;
  52259. this.pointerX = pointerX;
  52260. this.pointerY = pointerY;
  52261. this.meshUnderPointer = meshUnderPointer;
  52262. this.sourceEvent = sourceEvent;
  52263. this.additionalData = additionalData;
  52264. }
  52265. /**
  52266. * Helper function to auto-create an ActionEvent from a source mesh.
  52267. * @param source The source mesh that triggered the event
  52268. * @param evt The original (browser) event
  52269. * @param additionalData additional data for the event
  52270. * @returns the new ActionEvent
  52271. */
  52272. ActionEvent.CreateNew = function (source, evt, additionalData) {
  52273. var scene = source.getScene();
  52274. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52275. };
  52276. /**
  52277. * Helper function to auto-create an ActionEvent from a source sprite
  52278. * @param source The source sprite that triggered the event
  52279. * @param scene Scene associated with the sprite
  52280. * @param evt The original (browser) event
  52281. * @param additionalData additional data for the event
  52282. * @returns the new ActionEvent
  52283. */
  52284. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  52285. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52286. };
  52287. /**
  52288. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  52289. * @param scene the scene where the event occurred
  52290. * @param evt The original (browser) event
  52291. * @returns the new ActionEvent
  52292. */
  52293. ActionEvent.CreateNewFromScene = function (scene, evt) {
  52294. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  52295. };
  52296. /**
  52297. * Helper function to auto-create an ActionEvent from a primitive
  52298. * @param prim defines the target primitive
  52299. * @param pointerPos defines the pointer position
  52300. * @param evt The original (browser) event
  52301. * @param additionalData additional data for the event
  52302. * @returns the new ActionEvent
  52303. */
  52304. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  52305. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  52306. };
  52307. return ActionEvent;
  52308. }());
  52309. BABYLON.ActionEvent = ActionEvent;
  52310. /**
  52311. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  52312. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  52313. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  52314. */
  52315. var ActionManager = /** @class */ (function () {
  52316. /**
  52317. * Creates a new action manager
  52318. * @param scene defines the hosting scene
  52319. */
  52320. function ActionManager(scene) {
  52321. // Members
  52322. /** Gets the list of actions */
  52323. this.actions = new Array();
  52324. /** Gets the cursor to use when hovering items */
  52325. this.hoverCursor = '';
  52326. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  52327. scene._actionManagers.push(this);
  52328. }
  52329. Object.defineProperty(ActionManager, "NothingTrigger", {
  52330. /**
  52331. * Nothing
  52332. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52333. */
  52334. get: function () {
  52335. return ActionManager._NothingTrigger;
  52336. },
  52337. enumerable: true,
  52338. configurable: true
  52339. });
  52340. Object.defineProperty(ActionManager, "OnPickTrigger", {
  52341. /**
  52342. * On pick
  52343. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52344. */
  52345. get: function () {
  52346. return ActionManager._OnPickTrigger;
  52347. },
  52348. enumerable: true,
  52349. configurable: true
  52350. });
  52351. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  52352. /**
  52353. * On left pick
  52354. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52355. */
  52356. get: function () {
  52357. return ActionManager._OnLeftPickTrigger;
  52358. },
  52359. enumerable: true,
  52360. configurable: true
  52361. });
  52362. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  52363. /**
  52364. * On right pick
  52365. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52366. */
  52367. get: function () {
  52368. return ActionManager._OnRightPickTrigger;
  52369. },
  52370. enumerable: true,
  52371. configurable: true
  52372. });
  52373. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  52374. /**
  52375. * On center pick
  52376. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52377. */
  52378. get: function () {
  52379. return ActionManager._OnCenterPickTrigger;
  52380. },
  52381. enumerable: true,
  52382. configurable: true
  52383. });
  52384. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  52385. /**
  52386. * On pick down
  52387. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52388. */
  52389. get: function () {
  52390. return ActionManager._OnPickDownTrigger;
  52391. },
  52392. enumerable: true,
  52393. configurable: true
  52394. });
  52395. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  52396. /**
  52397. * On double pick
  52398. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52399. */
  52400. get: function () {
  52401. return ActionManager._OnDoublePickTrigger;
  52402. },
  52403. enumerable: true,
  52404. configurable: true
  52405. });
  52406. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  52407. /**
  52408. * On pick up
  52409. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52410. */
  52411. get: function () {
  52412. return ActionManager._OnPickUpTrigger;
  52413. },
  52414. enumerable: true,
  52415. configurable: true
  52416. });
  52417. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  52418. /**
  52419. * On pick out.
  52420. * This trigger will only be raised if you also declared a OnPickDown
  52421. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52422. */
  52423. get: function () {
  52424. return ActionManager._OnPickOutTrigger;
  52425. },
  52426. enumerable: true,
  52427. configurable: true
  52428. });
  52429. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  52430. /**
  52431. * On long press
  52432. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52433. */
  52434. get: function () {
  52435. return ActionManager._OnLongPressTrigger;
  52436. },
  52437. enumerable: true,
  52438. configurable: true
  52439. });
  52440. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  52441. /**
  52442. * On pointer over
  52443. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52444. */
  52445. get: function () {
  52446. return ActionManager._OnPointerOverTrigger;
  52447. },
  52448. enumerable: true,
  52449. configurable: true
  52450. });
  52451. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  52452. /**
  52453. * On pointer out
  52454. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52455. */
  52456. get: function () {
  52457. return ActionManager._OnPointerOutTrigger;
  52458. },
  52459. enumerable: true,
  52460. configurable: true
  52461. });
  52462. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  52463. /**
  52464. * On every frame
  52465. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52466. */
  52467. get: function () {
  52468. return ActionManager._OnEveryFrameTrigger;
  52469. },
  52470. enumerable: true,
  52471. configurable: true
  52472. });
  52473. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  52474. /**
  52475. * On intersection enter
  52476. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52477. */
  52478. get: function () {
  52479. return ActionManager._OnIntersectionEnterTrigger;
  52480. },
  52481. enumerable: true,
  52482. configurable: true
  52483. });
  52484. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  52485. /**
  52486. * On intersection exit
  52487. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52488. */
  52489. get: function () {
  52490. return ActionManager._OnIntersectionExitTrigger;
  52491. },
  52492. enumerable: true,
  52493. configurable: true
  52494. });
  52495. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  52496. /**
  52497. * On key down
  52498. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52499. */
  52500. get: function () {
  52501. return ActionManager._OnKeyDownTrigger;
  52502. },
  52503. enumerable: true,
  52504. configurable: true
  52505. });
  52506. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  52507. /**
  52508. * On key up
  52509. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52510. */
  52511. get: function () {
  52512. return ActionManager._OnKeyUpTrigger;
  52513. },
  52514. enumerable: true,
  52515. configurable: true
  52516. });
  52517. // Methods
  52518. /**
  52519. * Releases all associated resources
  52520. */
  52521. ActionManager.prototype.dispose = function () {
  52522. var index = this._scene._actionManagers.indexOf(this);
  52523. for (var i = 0; i < this.actions.length; i++) {
  52524. var action = this.actions[i];
  52525. ActionManager.Triggers[action.trigger]--;
  52526. if (ActionManager.Triggers[action.trigger] === 0) {
  52527. delete ActionManager.Triggers[action.trigger];
  52528. }
  52529. }
  52530. if (index > -1) {
  52531. this._scene._actionManagers.splice(index, 1);
  52532. }
  52533. };
  52534. /**
  52535. * Gets hosting scene
  52536. * @returns the hosting scene
  52537. */
  52538. ActionManager.prototype.getScene = function () {
  52539. return this._scene;
  52540. };
  52541. /**
  52542. * Does this action manager handles actions of any of the given triggers
  52543. * @param triggers defines the triggers to be tested
  52544. * @return a boolean indicating whether one (or more) of the triggers is handled
  52545. */
  52546. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  52547. for (var index = 0; index < this.actions.length; index++) {
  52548. var action = this.actions[index];
  52549. if (triggers.indexOf(action.trigger) > -1) {
  52550. return true;
  52551. }
  52552. }
  52553. return false;
  52554. };
  52555. /**
  52556. * Does this action manager handles actions of a given trigger
  52557. * @param trigger defines the trigger to be tested
  52558. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  52559. * @return whether the trigger is handled
  52560. */
  52561. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  52562. for (var index = 0; index < this.actions.length; index++) {
  52563. var action = this.actions[index];
  52564. if (action.trigger === trigger) {
  52565. if (parameterPredicate) {
  52566. if (parameterPredicate(action.getTriggerParameter())) {
  52567. return true;
  52568. }
  52569. }
  52570. else {
  52571. return true;
  52572. }
  52573. }
  52574. }
  52575. return false;
  52576. };
  52577. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  52578. /**
  52579. * Does this action manager has pointer triggers
  52580. */
  52581. get: function () {
  52582. for (var index = 0; index < this.actions.length; index++) {
  52583. var action = this.actions[index];
  52584. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  52585. return true;
  52586. }
  52587. }
  52588. return false;
  52589. },
  52590. enumerable: true,
  52591. configurable: true
  52592. });
  52593. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  52594. /**
  52595. * Does this action manager has pick triggers
  52596. */
  52597. get: function () {
  52598. for (var index = 0; index < this.actions.length; index++) {
  52599. var action = this.actions[index];
  52600. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  52601. return true;
  52602. }
  52603. }
  52604. return false;
  52605. },
  52606. enumerable: true,
  52607. configurable: true
  52608. });
  52609. Object.defineProperty(ActionManager, "HasTriggers", {
  52610. /**
  52611. * Does exist one action manager with at least one trigger
  52612. **/
  52613. get: function () {
  52614. for (var t in ActionManager.Triggers) {
  52615. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52616. return true;
  52617. }
  52618. }
  52619. return false;
  52620. },
  52621. enumerable: true,
  52622. configurable: true
  52623. });
  52624. Object.defineProperty(ActionManager, "HasPickTriggers", {
  52625. /**
  52626. * Does exist one action manager with at least one pick trigger
  52627. **/
  52628. get: function () {
  52629. for (var t in ActionManager.Triggers) {
  52630. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52631. var t_int = parseInt(t);
  52632. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  52633. return true;
  52634. }
  52635. }
  52636. }
  52637. return false;
  52638. },
  52639. enumerable: true,
  52640. configurable: true
  52641. });
  52642. /**
  52643. * Does exist one action manager that handles actions of a given trigger
  52644. * @param trigger defines the trigger to be tested
  52645. * @return a boolean indicating whether the trigger is handeled by at least one action manager
  52646. **/
  52647. ActionManager.HasSpecificTrigger = function (trigger) {
  52648. for (var t in ActionManager.Triggers) {
  52649. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52650. var t_int = parseInt(t);
  52651. if (t_int === trigger) {
  52652. return true;
  52653. }
  52654. }
  52655. }
  52656. return false;
  52657. };
  52658. /**
  52659. * Registers an action to this action manager
  52660. * @param action defines the action to be registered
  52661. * @return the action amended (prepared) after registration
  52662. */
  52663. ActionManager.prototype.registerAction = function (action) {
  52664. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  52665. if (this.getScene().actionManager !== this) {
  52666. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  52667. return null;
  52668. }
  52669. }
  52670. this.actions.push(action);
  52671. if (ActionManager.Triggers[action.trigger]) {
  52672. ActionManager.Triggers[action.trigger]++;
  52673. }
  52674. else {
  52675. ActionManager.Triggers[action.trigger] = 1;
  52676. }
  52677. action._actionManager = this;
  52678. action._prepare();
  52679. return action;
  52680. };
  52681. /**
  52682. * Unregisters an action to this action manager
  52683. * @param action defines the action to be unregistered
  52684. * @return a boolean indicating whether the action has been unregistered
  52685. */
  52686. ActionManager.prototype.unregisterAction = function (action) {
  52687. var index = this.actions.indexOf(action);
  52688. if (index !== -1) {
  52689. this.actions.splice(index, 1);
  52690. ActionManager.Triggers[action.trigger] -= 1;
  52691. if (ActionManager.Triggers[action.trigger] === 0) {
  52692. delete ActionManager.Triggers[action.trigger];
  52693. }
  52694. delete action._actionManager;
  52695. return true;
  52696. }
  52697. return false;
  52698. };
  52699. /**
  52700. * Process a specific trigger
  52701. * @param trigger defines the trigger to process
  52702. * @param evt defines the event details to be processed
  52703. */
  52704. ActionManager.prototype.processTrigger = function (trigger, evt) {
  52705. for (var index = 0; index < this.actions.length; index++) {
  52706. var action = this.actions[index];
  52707. if (action.trigger === trigger) {
  52708. if (evt) {
  52709. if (trigger === ActionManager.OnKeyUpTrigger
  52710. || trigger === ActionManager.OnKeyDownTrigger) {
  52711. var parameter = action.getTriggerParameter();
  52712. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  52713. if (!parameter.toLowerCase) {
  52714. continue;
  52715. }
  52716. var lowerCase = parameter.toLowerCase();
  52717. if (lowerCase !== evt.sourceEvent.key) {
  52718. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  52719. var actualkey = String.fromCharCode(unicode).toLowerCase();
  52720. if (actualkey !== lowerCase) {
  52721. continue;
  52722. }
  52723. }
  52724. }
  52725. }
  52726. }
  52727. action._executeCurrent(evt);
  52728. }
  52729. }
  52730. };
  52731. /** @hidden */
  52732. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  52733. var properties = propertyPath.split(".");
  52734. for (var index = 0; index < properties.length - 1; index++) {
  52735. target = target[properties[index]];
  52736. }
  52737. return target;
  52738. };
  52739. /** @hidden */
  52740. ActionManager.prototype._getProperty = function (propertyPath) {
  52741. var properties = propertyPath.split(".");
  52742. return properties[properties.length - 1];
  52743. };
  52744. /**
  52745. * Serialize this manager to a JSON object
  52746. * @param name defines the property name to store this manager
  52747. * @returns a JSON representation of this manager
  52748. */
  52749. ActionManager.prototype.serialize = function (name) {
  52750. var root = {
  52751. children: new Array(),
  52752. name: name,
  52753. type: 3,
  52754. properties: new Array() // Empty for root but required
  52755. };
  52756. for (var i = 0; i < this.actions.length; i++) {
  52757. var triggerObject = {
  52758. type: 0,
  52759. children: new Array(),
  52760. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  52761. properties: new Array()
  52762. };
  52763. var triggerOptions = this.actions[i].triggerOptions;
  52764. if (triggerOptions && typeof triggerOptions !== "number") {
  52765. if (triggerOptions.parameter instanceof BABYLON.Node) {
  52766. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  52767. }
  52768. else {
  52769. var parameter = {};
  52770. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  52771. if (triggerOptions.parameter.mesh) {
  52772. parameter._meshId = triggerOptions.parameter.mesh.id;
  52773. }
  52774. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  52775. }
  52776. }
  52777. // Serialize child action, recursively
  52778. this.actions[i].serialize(triggerObject);
  52779. // Add serialized trigger
  52780. root.children.push(triggerObject);
  52781. }
  52782. return root;
  52783. };
  52784. /**
  52785. * Creates a new ActionManager from a JSON data
  52786. * @param parsedActions defines the JSON data to read from
  52787. * @param object defines the hosting mesh
  52788. * @param scene defines the hosting scene
  52789. */
  52790. ActionManager.Parse = function (parsedActions, object, scene) {
  52791. var actionManager = new ActionManager(scene);
  52792. if (object === null)
  52793. scene.actionManager = actionManager;
  52794. else
  52795. object.actionManager = actionManager;
  52796. // instanciate a new object
  52797. var instanciate = function (name, params) {
  52798. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  52799. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  52800. newInstance.constructor.apply(newInstance, params);
  52801. return newInstance;
  52802. };
  52803. var parseParameter = function (name, value, target, propertyPath) {
  52804. if (propertyPath === null) {
  52805. // String, boolean or float
  52806. var floatValue = parseFloat(value);
  52807. if (value === "true" || value === "false")
  52808. return value === "true";
  52809. else
  52810. return isNaN(floatValue) ? value : floatValue;
  52811. }
  52812. var effectiveTarget = propertyPath.split(".");
  52813. var values = value.split(",");
  52814. // Get effective Target
  52815. for (var i = 0; i < effectiveTarget.length; i++) {
  52816. target = target[effectiveTarget[i]];
  52817. }
  52818. // Return appropriate value with its type
  52819. if (typeof (target) === "boolean")
  52820. return values[0] === "true";
  52821. if (typeof (target) === "string")
  52822. return values[0];
  52823. // Parameters with multiple values such as Vector3 etc.
  52824. var split = new Array();
  52825. for (var i = 0; i < values.length; i++)
  52826. split.push(parseFloat(values[i]));
  52827. if (target instanceof BABYLON.Vector3)
  52828. return BABYLON.Vector3.FromArray(split);
  52829. if (target instanceof BABYLON.Vector4)
  52830. return BABYLON.Vector4.FromArray(split);
  52831. if (target instanceof BABYLON.Color3)
  52832. return BABYLON.Color3.FromArray(split);
  52833. if (target instanceof BABYLON.Color4)
  52834. return BABYLON.Color4.FromArray(split);
  52835. return parseFloat(values[0]);
  52836. };
  52837. // traverse graph per trigger
  52838. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  52839. if (combineArray === void 0) { combineArray = null; }
  52840. if (parsedAction.detached)
  52841. return;
  52842. var parameters = new Array();
  52843. var target = null;
  52844. var propertyPath = null;
  52845. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  52846. // Parameters
  52847. if (parsedAction.type === 2)
  52848. parameters.push(actionManager);
  52849. else
  52850. parameters.push(trigger);
  52851. if (combine) {
  52852. var actions = new Array();
  52853. for (var j = 0; j < parsedAction.combine.length; j++) {
  52854. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  52855. }
  52856. parameters.push(actions);
  52857. }
  52858. else {
  52859. for (var i = 0; i < parsedAction.properties.length; i++) {
  52860. var value = parsedAction.properties[i].value;
  52861. var name = parsedAction.properties[i].name;
  52862. var targetType = parsedAction.properties[i].targetType;
  52863. if (name === "target")
  52864. if (targetType !== null && targetType === "SceneProperties")
  52865. value = target = scene;
  52866. else
  52867. value = target = scene.getNodeByName(value);
  52868. else if (name === "parent")
  52869. value = scene.getNodeByName(value);
  52870. else if (name === "sound")
  52871. value = scene.getSoundByName(value);
  52872. else if (name !== "propertyPath") {
  52873. if (parsedAction.type === 2 && name === "operator")
  52874. value = BABYLON.ValueCondition[value];
  52875. else
  52876. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  52877. }
  52878. else {
  52879. propertyPath = value;
  52880. }
  52881. parameters.push(value);
  52882. }
  52883. }
  52884. if (combineArray === null) {
  52885. parameters.push(condition);
  52886. }
  52887. else {
  52888. parameters.push(null);
  52889. }
  52890. // If interpolate value action
  52891. if (parsedAction.name === "InterpolateValueAction") {
  52892. var param = parameters[parameters.length - 2];
  52893. parameters[parameters.length - 1] = param;
  52894. parameters[parameters.length - 2] = condition;
  52895. }
  52896. // Action or condition(s) and not CombineAction
  52897. var newAction = instanciate(parsedAction.name, parameters);
  52898. if (newAction instanceof BABYLON.Condition && condition !== null) {
  52899. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  52900. if (action)
  52901. action.then(nothing);
  52902. else
  52903. actionManager.registerAction(nothing);
  52904. action = nothing;
  52905. }
  52906. if (combineArray === null) {
  52907. if (newAction instanceof BABYLON.Condition) {
  52908. condition = newAction;
  52909. newAction = action;
  52910. }
  52911. else {
  52912. condition = null;
  52913. if (action)
  52914. action.then(newAction);
  52915. else
  52916. actionManager.registerAction(newAction);
  52917. }
  52918. }
  52919. else {
  52920. combineArray.push(newAction);
  52921. }
  52922. for (var i = 0; i < parsedAction.children.length; i++)
  52923. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  52924. };
  52925. // triggers
  52926. for (var i = 0; i < parsedActions.children.length; i++) {
  52927. var triggerParams;
  52928. var trigger = parsedActions.children[i];
  52929. if (trigger.properties.length > 0) {
  52930. var param = trigger.properties[0].value;
  52931. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  52932. if (value._meshId) {
  52933. value.mesh = scene.getMeshByID(value._meshId);
  52934. }
  52935. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  52936. }
  52937. else
  52938. triggerParams = ActionManager[trigger.name];
  52939. for (var j = 0; j < trigger.children.length; j++) {
  52940. if (!trigger.detached)
  52941. traverse(trigger.children[j], triggerParams, null, null);
  52942. }
  52943. }
  52944. };
  52945. /**
  52946. * Get a trigger name by index
  52947. * @param trigger defines the trigger index
  52948. * @returns a trigger name
  52949. */
  52950. ActionManager.GetTriggerName = function (trigger) {
  52951. switch (trigger) {
  52952. case 0: return "NothingTrigger";
  52953. case 1: return "OnPickTrigger";
  52954. case 2: return "OnLeftPickTrigger";
  52955. case 3: return "OnRightPickTrigger";
  52956. case 4: return "OnCenterPickTrigger";
  52957. case 5: return "OnPickDownTrigger";
  52958. case 6: return "OnPickUpTrigger";
  52959. case 7: return "OnLongPressTrigger";
  52960. case 8: return "OnPointerOverTrigger";
  52961. case 9: return "OnPointerOutTrigger";
  52962. case 10: return "OnEveryFrameTrigger";
  52963. case 11: return "OnIntersectionEnterTrigger";
  52964. case 12: return "OnIntersectionExitTrigger";
  52965. case 13: return "OnKeyDownTrigger";
  52966. case 14: return "OnKeyUpTrigger";
  52967. case 15: return "OnPickOutTrigger";
  52968. default: return "";
  52969. }
  52970. };
  52971. // Statics
  52972. ActionManager._NothingTrigger = 0;
  52973. ActionManager._OnPickTrigger = 1;
  52974. ActionManager._OnLeftPickTrigger = 2;
  52975. ActionManager._OnRightPickTrigger = 3;
  52976. ActionManager._OnCenterPickTrigger = 4;
  52977. ActionManager._OnPickDownTrigger = 5;
  52978. ActionManager._OnDoublePickTrigger = 6;
  52979. ActionManager._OnPickUpTrigger = 7;
  52980. ActionManager._OnLongPressTrigger = 8;
  52981. ActionManager._OnPointerOverTrigger = 9;
  52982. ActionManager._OnPointerOutTrigger = 10;
  52983. ActionManager._OnEveryFrameTrigger = 11;
  52984. ActionManager._OnIntersectionEnterTrigger = 12;
  52985. ActionManager._OnIntersectionExitTrigger = 13;
  52986. ActionManager._OnKeyDownTrigger = 14;
  52987. ActionManager._OnKeyUpTrigger = 15;
  52988. ActionManager._OnPickOutTrigger = 16;
  52989. /** Gets the list of active triggers */
  52990. ActionManager.Triggers = {};
  52991. return ActionManager;
  52992. }());
  52993. BABYLON.ActionManager = ActionManager;
  52994. })(BABYLON || (BABYLON = {}));
  52995. //# sourceMappingURL=babylon.actionManager.js.map
  52996. var BABYLON;
  52997. (function (BABYLON) {
  52998. var InterpolateValueAction = /** @class */ (function (_super) {
  52999. __extends(InterpolateValueAction, _super);
  53000. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  53001. if (duration === void 0) { duration = 1000; }
  53002. var _this = _super.call(this, triggerOptions, condition) || this;
  53003. _this.propertyPath = propertyPath;
  53004. _this.value = value;
  53005. _this.duration = duration;
  53006. _this.stopOtherAnimations = stopOtherAnimations;
  53007. _this.onInterpolationDone = onInterpolationDone;
  53008. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  53009. _this._target = _this._effectiveTarget = target;
  53010. return _this;
  53011. }
  53012. InterpolateValueAction.prototype._prepare = function () {
  53013. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53014. this._property = this._getProperty(this.propertyPath);
  53015. };
  53016. InterpolateValueAction.prototype.execute = function () {
  53017. var _this = this;
  53018. var scene = this._actionManager.getScene();
  53019. var keys = [
  53020. {
  53021. frame: 0,
  53022. value: this._effectiveTarget[this._property]
  53023. }, {
  53024. frame: 100,
  53025. value: this.value
  53026. }
  53027. ];
  53028. var dataType;
  53029. if (typeof this.value === "number") {
  53030. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  53031. }
  53032. else if (this.value instanceof BABYLON.Color3) {
  53033. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  53034. }
  53035. else if (this.value instanceof BABYLON.Vector3) {
  53036. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  53037. }
  53038. else if (this.value instanceof BABYLON.Matrix) {
  53039. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  53040. }
  53041. else if (this.value instanceof BABYLON.Quaternion) {
  53042. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  53043. }
  53044. else {
  53045. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  53046. return;
  53047. }
  53048. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  53049. animation.setKeys(keys);
  53050. if (this.stopOtherAnimations) {
  53051. scene.stopAnimation(this._effectiveTarget);
  53052. }
  53053. var wrapper = function () {
  53054. _this.onInterpolationDoneObservable.notifyObservers(_this);
  53055. if (_this.onInterpolationDone) {
  53056. _this.onInterpolationDone();
  53057. }
  53058. };
  53059. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  53060. };
  53061. InterpolateValueAction.prototype.serialize = function (parent) {
  53062. return _super.prototype._serialize.call(this, {
  53063. name: "InterpolateValueAction",
  53064. properties: [
  53065. BABYLON.Action._GetTargetProperty(this._target),
  53066. { name: "propertyPath", value: this.propertyPath },
  53067. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  53068. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  53069. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  53070. ]
  53071. }, parent);
  53072. };
  53073. return InterpolateValueAction;
  53074. }(BABYLON.Action));
  53075. BABYLON.InterpolateValueAction = InterpolateValueAction;
  53076. })(BABYLON || (BABYLON = {}));
  53077. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  53078. var BABYLON;
  53079. (function (BABYLON) {
  53080. var SwitchBooleanAction = /** @class */ (function (_super) {
  53081. __extends(SwitchBooleanAction, _super);
  53082. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  53083. var _this = _super.call(this, triggerOptions, condition) || this;
  53084. _this.propertyPath = propertyPath;
  53085. _this._target = _this._effectiveTarget = target;
  53086. return _this;
  53087. }
  53088. SwitchBooleanAction.prototype._prepare = function () {
  53089. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53090. this._property = this._getProperty(this.propertyPath);
  53091. };
  53092. SwitchBooleanAction.prototype.execute = function () {
  53093. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  53094. };
  53095. SwitchBooleanAction.prototype.serialize = function (parent) {
  53096. return _super.prototype._serialize.call(this, {
  53097. name: "SwitchBooleanAction",
  53098. properties: [
  53099. BABYLON.Action._GetTargetProperty(this._target),
  53100. { name: "propertyPath", value: this.propertyPath }
  53101. ]
  53102. }, parent);
  53103. };
  53104. return SwitchBooleanAction;
  53105. }(BABYLON.Action));
  53106. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  53107. var SetStateAction = /** @class */ (function (_super) {
  53108. __extends(SetStateAction, _super);
  53109. function SetStateAction(triggerOptions, target, value, condition) {
  53110. var _this = _super.call(this, triggerOptions, condition) || this;
  53111. _this.value = value;
  53112. _this._target = target;
  53113. return _this;
  53114. }
  53115. SetStateAction.prototype.execute = function () {
  53116. this._target.state = this.value;
  53117. };
  53118. SetStateAction.prototype.serialize = function (parent) {
  53119. return _super.prototype._serialize.call(this, {
  53120. name: "SetStateAction",
  53121. properties: [
  53122. BABYLON.Action._GetTargetProperty(this._target),
  53123. { name: "value", value: this.value }
  53124. ]
  53125. }, parent);
  53126. };
  53127. return SetStateAction;
  53128. }(BABYLON.Action));
  53129. BABYLON.SetStateAction = SetStateAction;
  53130. var SetValueAction = /** @class */ (function (_super) {
  53131. __extends(SetValueAction, _super);
  53132. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  53133. var _this = _super.call(this, triggerOptions, condition) || this;
  53134. _this.propertyPath = propertyPath;
  53135. _this.value = value;
  53136. _this._target = _this._effectiveTarget = target;
  53137. return _this;
  53138. }
  53139. SetValueAction.prototype._prepare = function () {
  53140. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53141. this._property = this._getProperty(this.propertyPath);
  53142. };
  53143. SetValueAction.prototype.execute = function () {
  53144. this._effectiveTarget[this._property] = this.value;
  53145. if (this._target.markAsDirty) {
  53146. this._target.markAsDirty(this._property);
  53147. }
  53148. };
  53149. SetValueAction.prototype.serialize = function (parent) {
  53150. return _super.prototype._serialize.call(this, {
  53151. name: "SetValueAction",
  53152. properties: [
  53153. BABYLON.Action._GetTargetProperty(this._target),
  53154. { name: "propertyPath", value: this.propertyPath },
  53155. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53156. ]
  53157. }, parent);
  53158. };
  53159. return SetValueAction;
  53160. }(BABYLON.Action));
  53161. BABYLON.SetValueAction = SetValueAction;
  53162. var IncrementValueAction = /** @class */ (function (_super) {
  53163. __extends(IncrementValueAction, _super);
  53164. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  53165. var _this = _super.call(this, triggerOptions, condition) || this;
  53166. _this.propertyPath = propertyPath;
  53167. _this.value = value;
  53168. _this._target = _this._effectiveTarget = target;
  53169. return _this;
  53170. }
  53171. IncrementValueAction.prototype._prepare = function () {
  53172. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53173. this._property = this._getProperty(this.propertyPath);
  53174. if (typeof this._effectiveTarget[this._property] !== "number") {
  53175. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  53176. }
  53177. };
  53178. IncrementValueAction.prototype.execute = function () {
  53179. this._effectiveTarget[this._property] += this.value;
  53180. if (this._target.markAsDirty) {
  53181. this._target.markAsDirty(this._property);
  53182. }
  53183. };
  53184. IncrementValueAction.prototype.serialize = function (parent) {
  53185. return _super.prototype._serialize.call(this, {
  53186. name: "IncrementValueAction",
  53187. properties: [
  53188. BABYLON.Action._GetTargetProperty(this._target),
  53189. { name: "propertyPath", value: this.propertyPath },
  53190. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53191. ]
  53192. }, parent);
  53193. };
  53194. return IncrementValueAction;
  53195. }(BABYLON.Action));
  53196. BABYLON.IncrementValueAction = IncrementValueAction;
  53197. var PlayAnimationAction = /** @class */ (function (_super) {
  53198. __extends(PlayAnimationAction, _super);
  53199. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  53200. var _this = _super.call(this, triggerOptions, condition) || this;
  53201. _this.from = from;
  53202. _this.to = to;
  53203. _this.loop = loop;
  53204. _this._target = target;
  53205. return _this;
  53206. }
  53207. PlayAnimationAction.prototype._prepare = function () {
  53208. };
  53209. PlayAnimationAction.prototype.execute = function () {
  53210. var scene = this._actionManager.getScene();
  53211. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  53212. };
  53213. PlayAnimationAction.prototype.serialize = function (parent) {
  53214. return _super.prototype._serialize.call(this, {
  53215. name: "PlayAnimationAction",
  53216. properties: [
  53217. BABYLON.Action._GetTargetProperty(this._target),
  53218. { name: "from", value: String(this.from) },
  53219. { name: "to", value: String(this.to) },
  53220. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  53221. ]
  53222. }, parent);
  53223. };
  53224. return PlayAnimationAction;
  53225. }(BABYLON.Action));
  53226. BABYLON.PlayAnimationAction = PlayAnimationAction;
  53227. var StopAnimationAction = /** @class */ (function (_super) {
  53228. __extends(StopAnimationAction, _super);
  53229. function StopAnimationAction(triggerOptions, target, condition) {
  53230. var _this = _super.call(this, triggerOptions, condition) || this;
  53231. _this._target = target;
  53232. return _this;
  53233. }
  53234. StopAnimationAction.prototype._prepare = function () {
  53235. };
  53236. StopAnimationAction.prototype.execute = function () {
  53237. var scene = this._actionManager.getScene();
  53238. scene.stopAnimation(this._target);
  53239. };
  53240. StopAnimationAction.prototype.serialize = function (parent) {
  53241. return _super.prototype._serialize.call(this, {
  53242. name: "StopAnimationAction",
  53243. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  53244. }, parent);
  53245. };
  53246. return StopAnimationAction;
  53247. }(BABYLON.Action));
  53248. BABYLON.StopAnimationAction = StopAnimationAction;
  53249. var DoNothingAction = /** @class */ (function (_super) {
  53250. __extends(DoNothingAction, _super);
  53251. function DoNothingAction(triggerOptions, condition) {
  53252. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  53253. return _super.call(this, triggerOptions, condition) || this;
  53254. }
  53255. DoNothingAction.prototype.execute = function () {
  53256. };
  53257. DoNothingAction.prototype.serialize = function (parent) {
  53258. return _super.prototype._serialize.call(this, {
  53259. name: "DoNothingAction",
  53260. properties: []
  53261. }, parent);
  53262. };
  53263. return DoNothingAction;
  53264. }(BABYLON.Action));
  53265. BABYLON.DoNothingAction = DoNothingAction;
  53266. var CombineAction = /** @class */ (function (_super) {
  53267. __extends(CombineAction, _super);
  53268. function CombineAction(triggerOptions, children, condition) {
  53269. var _this = _super.call(this, triggerOptions, condition) || this;
  53270. _this.children = children;
  53271. return _this;
  53272. }
  53273. CombineAction.prototype._prepare = function () {
  53274. for (var index = 0; index < this.children.length; index++) {
  53275. this.children[index]._actionManager = this._actionManager;
  53276. this.children[index]._prepare();
  53277. }
  53278. };
  53279. CombineAction.prototype.execute = function (evt) {
  53280. for (var index = 0; index < this.children.length; index++) {
  53281. this.children[index].execute(evt);
  53282. }
  53283. };
  53284. CombineAction.prototype.serialize = function (parent) {
  53285. var serializationObject = _super.prototype._serialize.call(this, {
  53286. name: "CombineAction",
  53287. properties: [],
  53288. combine: []
  53289. }, parent);
  53290. for (var i = 0; i < this.children.length; i++) {
  53291. serializationObject.combine.push(this.children[i].serialize(null));
  53292. }
  53293. return serializationObject;
  53294. };
  53295. return CombineAction;
  53296. }(BABYLON.Action));
  53297. BABYLON.CombineAction = CombineAction;
  53298. var ExecuteCodeAction = /** @class */ (function (_super) {
  53299. __extends(ExecuteCodeAction, _super);
  53300. function ExecuteCodeAction(triggerOptions, func, condition) {
  53301. var _this = _super.call(this, triggerOptions, condition) || this;
  53302. _this.func = func;
  53303. return _this;
  53304. }
  53305. ExecuteCodeAction.prototype.execute = function (evt) {
  53306. this.func(evt);
  53307. };
  53308. return ExecuteCodeAction;
  53309. }(BABYLON.Action));
  53310. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  53311. var SetParentAction = /** @class */ (function (_super) {
  53312. __extends(SetParentAction, _super);
  53313. function SetParentAction(triggerOptions, target, parent, condition) {
  53314. var _this = _super.call(this, triggerOptions, condition) || this;
  53315. _this._target = target;
  53316. _this._parent = parent;
  53317. return _this;
  53318. }
  53319. SetParentAction.prototype._prepare = function () {
  53320. };
  53321. SetParentAction.prototype.execute = function () {
  53322. if (this._target.parent === this._parent) {
  53323. return;
  53324. }
  53325. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  53326. invertParentWorldMatrix.invert();
  53327. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  53328. this._target.parent = this._parent;
  53329. };
  53330. SetParentAction.prototype.serialize = function (parent) {
  53331. return _super.prototype._serialize.call(this, {
  53332. name: "SetParentAction",
  53333. properties: [
  53334. BABYLON.Action._GetTargetProperty(this._target),
  53335. BABYLON.Action._GetTargetProperty(this._parent),
  53336. ]
  53337. }, parent);
  53338. };
  53339. return SetParentAction;
  53340. }(BABYLON.Action));
  53341. BABYLON.SetParentAction = SetParentAction;
  53342. var PlaySoundAction = /** @class */ (function (_super) {
  53343. __extends(PlaySoundAction, _super);
  53344. function PlaySoundAction(triggerOptions, sound, condition) {
  53345. var _this = _super.call(this, triggerOptions, condition) || this;
  53346. _this._sound = sound;
  53347. return _this;
  53348. }
  53349. PlaySoundAction.prototype._prepare = function () {
  53350. };
  53351. PlaySoundAction.prototype.execute = function () {
  53352. if (this._sound !== undefined)
  53353. this._sound.play();
  53354. };
  53355. PlaySoundAction.prototype.serialize = function (parent) {
  53356. return _super.prototype._serialize.call(this, {
  53357. name: "PlaySoundAction",
  53358. properties: [{ name: "sound", value: this._sound.name }]
  53359. }, parent);
  53360. };
  53361. return PlaySoundAction;
  53362. }(BABYLON.Action));
  53363. BABYLON.PlaySoundAction = PlaySoundAction;
  53364. var StopSoundAction = /** @class */ (function (_super) {
  53365. __extends(StopSoundAction, _super);
  53366. function StopSoundAction(triggerOptions, sound, condition) {
  53367. var _this = _super.call(this, triggerOptions, condition) || this;
  53368. _this._sound = sound;
  53369. return _this;
  53370. }
  53371. StopSoundAction.prototype._prepare = function () {
  53372. };
  53373. StopSoundAction.prototype.execute = function () {
  53374. if (this._sound !== undefined)
  53375. this._sound.stop();
  53376. };
  53377. StopSoundAction.prototype.serialize = function (parent) {
  53378. return _super.prototype._serialize.call(this, {
  53379. name: "StopSoundAction",
  53380. properties: [{ name: "sound", value: this._sound.name }]
  53381. }, parent);
  53382. };
  53383. return StopSoundAction;
  53384. }(BABYLON.Action));
  53385. BABYLON.StopSoundAction = StopSoundAction;
  53386. })(BABYLON || (BABYLON = {}));
  53387. //# sourceMappingURL=babylon.directActions.js.map
  53388. var BABYLON;
  53389. (function (BABYLON) {
  53390. var SpriteManager = /** @class */ (function () {
  53391. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  53392. if (epsilon === void 0) { epsilon = 0.01; }
  53393. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  53394. this.name = name;
  53395. this.sprites = new Array();
  53396. this.renderingGroupId = 0;
  53397. this.layerMask = 0x0FFFFFFF;
  53398. this.fogEnabled = true;
  53399. this.isPickable = false;
  53400. /**
  53401. * An event triggered when the manager is disposed.
  53402. */
  53403. this.onDisposeObservable = new BABYLON.Observable();
  53404. this._vertexBuffers = {};
  53405. this._capacity = capacity;
  53406. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  53407. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53408. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53409. if (cellSize.width && cellSize.height) {
  53410. this.cellWidth = cellSize.width;
  53411. this.cellHeight = cellSize.height;
  53412. }
  53413. else if (cellSize !== undefined) {
  53414. this.cellWidth = cellSize;
  53415. this.cellHeight = cellSize;
  53416. }
  53417. else {
  53418. return;
  53419. }
  53420. this._epsilon = epsilon;
  53421. this._scene = scene;
  53422. this._scene.spriteManagers.push(this);
  53423. var indices = [];
  53424. var index = 0;
  53425. for (var count = 0; count < capacity; count++) {
  53426. indices.push(index);
  53427. indices.push(index + 1);
  53428. indices.push(index + 2);
  53429. indices.push(index);
  53430. indices.push(index + 2);
  53431. indices.push(index + 3);
  53432. index += 4;
  53433. }
  53434. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  53435. // VBO
  53436. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  53437. this._vertexData = new Float32Array(capacity * 16 * 4);
  53438. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  53439. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  53440. var options = this._buffer.createVertexBuffer("options", 4, 4);
  53441. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  53442. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  53443. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  53444. this._vertexBuffers["options"] = options;
  53445. this._vertexBuffers["cellInfo"] = cellInfo;
  53446. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  53447. // Effects
  53448. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  53449. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  53450. }
  53451. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  53452. set: function (callback) {
  53453. if (this._onDisposeObserver) {
  53454. this.onDisposeObservable.remove(this._onDisposeObserver);
  53455. }
  53456. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  53457. },
  53458. enumerable: true,
  53459. configurable: true
  53460. });
  53461. Object.defineProperty(SpriteManager.prototype, "texture", {
  53462. get: function () {
  53463. return this._spriteTexture;
  53464. },
  53465. set: function (value) {
  53466. this._spriteTexture = value;
  53467. },
  53468. enumerable: true,
  53469. configurable: true
  53470. });
  53471. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  53472. var arrayOffset = index * 16;
  53473. if (offsetX === 0)
  53474. offsetX = this._epsilon;
  53475. else if (offsetX === 1)
  53476. offsetX = 1 - this._epsilon;
  53477. if (offsetY === 0)
  53478. offsetY = this._epsilon;
  53479. else if (offsetY === 1)
  53480. offsetY = 1 - this._epsilon;
  53481. this._vertexData[arrayOffset] = sprite.position.x;
  53482. this._vertexData[arrayOffset + 1] = sprite.position.y;
  53483. this._vertexData[arrayOffset + 2] = sprite.position.z;
  53484. this._vertexData[arrayOffset + 3] = sprite.angle;
  53485. this._vertexData[arrayOffset + 4] = sprite.width;
  53486. this._vertexData[arrayOffset + 5] = sprite.height;
  53487. this._vertexData[arrayOffset + 6] = offsetX;
  53488. this._vertexData[arrayOffset + 7] = offsetY;
  53489. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  53490. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  53491. var offset = (sprite.cellIndex / rowSize) >> 0;
  53492. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  53493. this._vertexData[arrayOffset + 11] = offset;
  53494. // Color
  53495. this._vertexData[arrayOffset + 12] = sprite.color.r;
  53496. this._vertexData[arrayOffset + 13] = sprite.color.g;
  53497. this._vertexData[arrayOffset + 14] = sprite.color.b;
  53498. this._vertexData[arrayOffset + 15] = sprite.color.a;
  53499. };
  53500. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  53501. var count = Math.min(this._capacity, this.sprites.length);
  53502. var min = BABYLON.Vector3.Zero();
  53503. var max = BABYLON.Vector3.Zero();
  53504. var distance = Number.MAX_VALUE;
  53505. var currentSprite = null;
  53506. var cameraSpacePosition = BABYLON.Vector3.Zero();
  53507. var cameraView = camera.getViewMatrix();
  53508. for (var index = 0; index < count; index++) {
  53509. var sprite = this.sprites[index];
  53510. if (!sprite) {
  53511. continue;
  53512. }
  53513. if (predicate) {
  53514. if (!predicate(sprite)) {
  53515. continue;
  53516. }
  53517. }
  53518. else if (!sprite.isPickable) {
  53519. continue;
  53520. }
  53521. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  53522. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  53523. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  53524. if (ray.intersectsBoxMinMax(min, max)) {
  53525. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  53526. if (distance > currentDistance) {
  53527. distance = currentDistance;
  53528. currentSprite = sprite;
  53529. if (fastCheck) {
  53530. break;
  53531. }
  53532. }
  53533. }
  53534. }
  53535. if (currentSprite) {
  53536. var result = new BABYLON.PickingInfo();
  53537. result.hit = true;
  53538. result.pickedSprite = currentSprite;
  53539. result.distance = distance;
  53540. return result;
  53541. }
  53542. return null;
  53543. };
  53544. SpriteManager.prototype.render = function () {
  53545. // Check
  53546. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  53547. return;
  53548. var engine = this._scene.getEngine();
  53549. var baseSize = this._spriteTexture.getBaseSize();
  53550. // Sprites
  53551. var deltaTime = engine.getDeltaTime();
  53552. var max = Math.min(this._capacity, this.sprites.length);
  53553. var rowSize = baseSize.width / this.cellWidth;
  53554. var offset = 0;
  53555. for (var index = 0; index < max; index++) {
  53556. var sprite = this.sprites[index];
  53557. if (!sprite || !sprite.isVisible) {
  53558. continue;
  53559. }
  53560. sprite._animate(deltaTime);
  53561. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  53562. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  53563. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  53564. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  53565. }
  53566. this._buffer.update(this._vertexData);
  53567. // Render
  53568. var effect = this._effectBase;
  53569. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  53570. effect = this._effectFog;
  53571. }
  53572. engine.enableEffect(effect);
  53573. var viewMatrix = this._scene.getViewMatrix();
  53574. effect.setTexture("diffuseSampler", this._spriteTexture);
  53575. effect.setMatrix("view", viewMatrix);
  53576. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  53577. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  53578. // Fog
  53579. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  53580. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  53581. effect.setColor3("vFogColor", this._scene.fogColor);
  53582. }
  53583. // VBOs
  53584. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  53585. // Draw order
  53586. engine.setDepthFunctionToLessOrEqual();
  53587. effect.setBool("alphaTest", true);
  53588. engine.setColorWrite(false);
  53589. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  53590. engine.setColorWrite(true);
  53591. effect.setBool("alphaTest", false);
  53592. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  53593. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  53594. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  53595. };
  53596. SpriteManager.prototype.dispose = function () {
  53597. if (this._buffer) {
  53598. this._buffer.dispose();
  53599. this._buffer = null;
  53600. }
  53601. if (this._indexBuffer) {
  53602. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  53603. this._indexBuffer = null;
  53604. }
  53605. if (this._spriteTexture) {
  53606. this._spriteTexture.dispose();
  53607. this._spriteTexture = null;
  53608. }
  53609. // Remove from scene
  53610. var index = this._scene.spriteManagers.indexOf(this);
  53611. this._scene.spriteManagers.splice(index, 1);
  53612. // Callback
  53613. this.onDisposeObservable.notifyObservers(this);
  53614. this.onDisposeObservable.clear();
  53615. };
  53616. return SpriteManager;
  53617. }());
  53618. BABYLON.SpriteManager = SpriteManager;
  53619. })(BABYLON || (BABYLON = {}));
  53620. //# sourceMappingURL=babylon.spriteManager.js.map
  53621. var BABYLON;
  53622. (function (BABYLON) {
  53623. var Sprite = /** @class */ (function () {
  53624. function Sprite(name, manager) {
  53625. this.name = name;
  53626. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  53627. this.width = 1.0;
  53628. this.height = 1.0;
  53629. this.angle = 0;
  53630. this.cellIndex = 0;
  53631. this.invertU = 0;
  53632. this.invertV = 0;
  53633. this.animations = new Array();
  53634. this.isPickable = false;
  53635. this._animationStarted = false;
  53636. this._loopAnimation = false;
  53637. this._fromIndex = 0;
  53638. this._toIndex = 0;
  53639. this._delay = 0;
  53640. this._direction = 1;
  53641. this._time = 0;
  53642. /**
  53643. * Gets or sets a boolean indicating if the sprite is visible (renderable). Default is true
  53644. */
  53645. this.isVisible = true;
  53646. this._manager = manager;
  53647. this._manager.sprites.push(this);
  53648. this.position = BABYLON.Vector3.Zero();
  53649. }
  53650. Object.defineProperty(Sprite.prototype, "size", {
  53651. get: function () {
  53652. return this.width;
  53653. },
  53654. set: function (value) {
  53655. this.width = value;
  53656. this.height = value;
  53657. },
  53658. enumerable: true,
  53659. configurable: true
  53660. });
  53661. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  53662. this._fromIndex = from;
  53663. this._toIndex = to;
  53664. this._loopAnimation = loop;
  53665. this._delay = delay;
  53666. this._animationStarted = true;
  53667. this._direction = from < to ? 1 : -1;
  53668. this.cellIndex = from;
  53669. this._time = 0;
  53670. this._onAnimationEnd = onAnimationEnd;
  53671. };
  53672. Sprite.prototype.stopAnimation = function () {
  53673. this._animationStarted = false;
  53674. };
  53675. Sprite.prototype._animate = function (deltaTime) {
  53676. if (!this._animationStarted)
  53677. return;
  53678. this._time += deltaTime;
  53679. if (this._time > this._delay) {
  53680. this._time = this._time % this._delay;
  53681. this.cellIndex += this._direction;
  53682. if (this.cellIndex > this._toIndex) {
  53683. if (this._loopAnimation) {
  53684. this.cellIndex = this._fromIndex;
  53685. }
  53686. else {
  53687. this.cellIndex = this._toIndex;
  53688. this._animationStarted = false;
  53689. if (this._onAnimationEnd) {
  53690. this._onAnimationEnd();
  53691. }
  53692. if (this.disposeWhenFinishedAnimating) {
  53693. this.dispose();
  53694. }
  53695. }
  53696. }
  53697. }
  53698. };
  53699. Sprite.prototype.dispose = function () {
  53700. for (var i = 0; i < this._manager.sprites.length; i++) {
  53701. if (this._manager.sprites[i] == this) {
  53702. this._manager.sprites.splice(i, 1);
  53703. }
  53704. }
  53705. };
  53706. return Sprite;
  53707. }());
  53708. BABYLON.Sprite = Sprite;
  53709. })(BABYLON || (BABYLON = {}));
  53710. //# sourceMappingURL=babylon.sprite.js.map
  53711. var BABYLON;
  53712. (function (BABYLON) {
  53713. var IntersectionInfo = /** @class */ (function () {
  53714. function IntersectionInfo(bu, bv, distance) {
  53715. this.bu = bu;
  53716. this.bv = bv;
  53717. this.distance = distance;
  53718. this.faceId = 0;
  53719. this.subMeshId = 0;
  53720. }
  53721. return IntersectionInfo;
  53722. }());
  53723. BABYLON.IntersectionInfo = IntersectionInfo;
  53724. /**
  53725. * Information about the result of picking within a scene
  53726. * See https://doc.babylonjs.com/babylon101/picking_collisions
  53727. */
  53728. var PickingInfo = /** @class */ (function () {
  53729. function PickingInfo() {
  53730. /**
  53731. * If the pick collided with an object
  53732. */
  53733. this.hit = false;
  53734. /**
  53735. * Distance away where the pick collided
  53736. */
  53737. this.distance = 0;
  53738. /**
  53739. * The location of pick collision
  53740. */
  53741. this.pickedPoint = null;
  53742. /**
  53743. * The mesh corrisponding the the pick collision
  53744. */
  53745. this.pickedMesh = null;
  53746. /** (See getTextureCoordinates) The barycentric U coordinate that is used when calulating the texture coordinates of the collision.*/
  53747. this.bu = 0;
  53748. /** (See getTextureCoordinates) The barycentric V coordinate that is used when calulating the texture coordinates of the collision.*/
  53749. this.bv = 0;
  53750. /** The id of the face on the mesh that was picked */
  53751. this.faceId = -1;
  53752. /** Id of the the submesh that was picked */
  53753. this.subMeshId = 0;
  53754. /** If a sprite was picked, this will be the sprite the pick collided with */
  53755. this.pickedSprite = null;
  53756. /**
  53757. * If a mesh was used to do the picking (eg. 6dof controller) this will be populated.
  53758. */
  53759. this.originMesh = null;
  53760. /**
  53761. * The ray that was used to perform the picking.
  53762. */
  53763. this.ray = null;
  53764. }
  53765. /**
  53766. * Gets the normal corrispodning to the face the pick collided with
  53767. * @param useWorldCoordinates If the resulting normal should be relative to the world (default: false)
  53768. * @param useVerticesNormals If the vertices normals should be used to calculate the normal instead of the normal map
  53769. * @returns The normal corrispodning to the face the pick collided with
  53770. */
  53771. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  53772. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  53773. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  53774. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  53775. return null;
  53776. }
  53777. var indices = this.pickedMesh.getIndices();
  53778. if (!indices) {
  53779. return null;
  53780. }
  53781. var result;
  53782. if (useVerticesNormals) {
  53783. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  53784. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  53785. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  53786. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  53787. normal0 = normal0.scale(this.bu);
  53788. normal1 = normal1.scale(this.bv);
  53789. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  53790. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  53791. }
  53792. else {
  53793. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  53794. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  53795. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  53796. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  53797. var p1p2 = vertex1.subtract(vertex2);
  53798. var p3p2 = vertex3.subtract(vertex2);
  53799. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  53800. }
  53801. if (useWorldCoordinates) {
  53802. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  53803. }
  53804. return BABYLON.Vector3.Normalize(result);
  53805. };
  53806. /**
  53807. * Gets the texture coordinates of where the pick occured
  53808. * @returns the vector containing the coordnates of the texture
  53809. */
  53810. PickingInfo.prototype.getTextureCoordinates = function () {
  53811. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  53812. return null;
  53813. }
  53814. var indices = this.pickedMesh.getIndices();
  53815. if (!indices) {
  53816. return null;
  53817. }
  53818. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  53819. if (!uvs) {
  53820. return null;
  53821. }
  53822. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  53823. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  53824. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  53825. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  53826. uv1 = uv1.scale(this.bu);
  53827. uv2 = uv2.scale(this.bv);
  53828. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  53829. };
  53830. return PickingInfo;
  53831. }());
  53832. BABYLON.PickingInfo = PickingInfo;
  53833. })(BABYLON || (BABYLON = {}));
  53834. //# sourceMappingURL=babylon.pickingInfo.js.map
  53835. var BABYLON;
  53836. (function (BABYLON) {
  53837. var Ray = /** @class */ (function () {
  53838. function Ray(origin, direction, length) {
  53839. if (length === void 0) { length = Number.MAX_VALUE; }
  53840. this.origin = origin;
  53841. this.direction = direction;
  53842. this.length = length;
  53843. }
  53844. // Methods
  53845. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  53846. var d = 0.0;
  53847. var maxValue = Number.MAX_VALUE;
  53848. var inv;
  53849. var min;
  53850. var max;
  53851. var temp;
  53852. if (Math.abs(this.direction.x) < 0.0000001) {
  53853. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  53854. return false;
  53855. }
  53856. }
  53857. else {
  53858. inv = 1.0 / this.direction.x;
  53859. min = (minimum.x - this.origin.x) * inv;
  53860. max = (maximum.x - this.origin.x) * inv;
  53861. if (max === -Infinity) {
  53862. max = Infinity;
  53863. }
  53864. if (min > max) {
  53865. temp = min;
  53866. min = max;
  53867. max = temp;
  53868. }
  53869. d = Math.max(min, d);
  53870. maxValue = Math.min(max, maxValue);
  53871. if (d > maxValue) {
  53872. return false;
  53873. }
  53874. }
  53875. if (Math.abs(this.direction.y) < 0.0000001) {
  53876. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  53877. return false;
  53878. }
  53879. }
  53880. else {
  53881. inv = 1.0 / this.direction.y;
  53882. min = (minimum.y - this.origin.y) * inv;
  53883. max = (maximum.y - this.origin.y) * inv;
  53884. if (max === -Infinity) {
  53885. max = Infinity;
  53886. }
  53887. if (min > max) {
  53888. temp = min;
  53889. min = max;
  53890. max = temp;
  53891. }
  53892. d = Math.max(min, d);
  53893. maxValue = Math.min(max, maxValue);
  53894. if (d > maxValue) {
  53895. return false;
  53896. }
  53897. }
  53898. if (Math.abs(this.direction.z) < 0.0000001) {
  53899. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  53900. return false;
  53901. }
  53902. }
  53903. else {
  53904. inv = 1.0 / this.direction.z;
  53905. min = (minimum.z - this.origin.z) * inv;
  53906. max = (maximum.z - this.origin.z) * inv;
  53907. if (max === -Infinity) {
  53908. max = Infinity;
  53909. }
  53910. if (min > max) {
  53911. temp = min;
  53912. min = max;
  53913. max = temp;
  53914. }
  53915. d = Math.max(min, d);
  53916. maxValue = Math.min(max, maxValue);
  53917. if (d > maxValue) {
  53918. return false;
  53919. }
  53920. }
  53921. return true;
  53922. };
  53923. Ray.prototype.intersectsBox = function (box) {
  53924. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  53925. };
  53926. Ray.prototype.intersectsSphere = function (sphere) {
  53927. var x = sphere.center.x - this.origin.x;
  53928. var y = sphere.center.y - this.origin.y;
  53929. var z = sphere.center.z - this.origin.z;
  53930. var pyth = (x * x) + (y * y) + (z * z);
  53931. var rr = sphere.radius * sphere.radius;
  53932. if (pyth <= rr) {
  53933. return true;
  53934. }
  53935. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  53936. if (dot < 0.0) {
  53937. return false;
  53938. }
  53939. var temp = pyth - (dot * dot);
  53940. return temp <= rr;
  53941. };
  53942. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  53943. if (!this._edge1) {
  53944. this._edge1 = BABYLON.Vector3.Zero();
  53945. this._edge2 = BABYLON.Vector3.Zero();
  53946. this._pvec = BABYLON.Vector3.Zero();
  53947. this._tvec = BABYLON.Vector3.Zero();
  53948. this._qvec = BABYLON.Vector3.Zero();
  53949. }
  53950. vertex1.subtractToRef(vertex0, this._edge1);
  53951. vertex2.subtractToRef(vertex0, this._edge2);
  53952. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  53953. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  53954. if (det === 0) {
  53955. return null;
  53956. }
  53957. var invdet = 1 / det;
  53958. this.origin.subtractToRef(vertex0, this._tvec);
  53959. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  53960. if (bu < 0 || bu > 1.0) {
  53961. return null;
  53962. }
  53963. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  53964. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  53965. if (bv < 0 || bu + bv > 1.0) {
  53966. return null;
  53967. }
  53968. //check if the distance is longer than the predefined length.
  53969. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  53970. if (distance > this.length) {
  53971. return null;
  53972. }
  53973. return new BABYLON.IntersectionInfo(bu, bv, distance);
  53974. };
  53975. Ray.prototype.intersectsPlane = function (plane) {
  53976. var distance;
  53977. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  53978. if (Math.abs(result1) < 9.99999997475243E-07) {
  53979. return null;
  53980. }
  53981. else {
  53982. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  53983. distance = (-plane.d - result2) / result1;
  53984. if (distance < 0.0) {
  53985. if (distance < -9.99999997475243E-07) {
  53986. return null;
  53987. }
  53988. else {
  53989. return 0;
  53990. }
  53991. }
  53992. return distance;
  53993. }
  53994. };
  53995. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  53996. var tm = BABYLON.Tmp.Matrix[0];
  53997. mesh.getWorldMatrix().invertToRef(tm);
  53998. if (this._tmpRay) {
  53999. Ray.TransformToRef(this, tm, this._tmpRay);
  54000. }
  54001. else {
  54002. this._tmpRay = Ray.Transform(this, tm);
  54003. }
  54004. return mesh.intersects(this._tmpRay, fastCheck);
  54005. };
  54006. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  54007. if (results) {
  54008. results.length = 0;
  54009. }
  54010. else {
  54011. results = [];
  54012. }
  54013. for (var i = 0; i < meshes.length; i++) {
  54014. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  54015. if (pickInfo.hit) {
  54016. results.push(pickInfo);
  54017. }
  54018. }
  54019. results.sort(this._comparePickingInfo);
  54020. return results;
  54021. };
  54022. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  54023. if (pickingInfoA.distance < pickingInfoB.distance) {
  54024. return -1;
  54025. }
  54026. else if (pickingInfoA.distance > pickingInfoB.distance) {
  54027. return 1;
  54028. }
  54029. else {
  54030. return 0;
  54031. }
  54032. };
  54033. /**
  54034. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  54035. * @param sega the first point of the segment to test the intersection against
  54036. * @param segb the second point of the segment to test the intersection against
  54037. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  54038. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  54039. */
  54040. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  54041. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  54042. var u = segb.subtract(sega);
  54043. var v = rsegb.subtract(this.origin);
  54044. var w = sega.subtract(this.origin);
  54045. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  54046. var b = BABYLON.Vector3.Dot(u, v);
  54047. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  54048. var d = BABYLON.Vector3.Dot(u, w);
  54049. var e = BABYLON.Vector3.Dot(v, w);
  54050. var D = a * c - b * b; // always >= 0
  54051. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  54052. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  54053. // compute the line parameters of the two closest points
  54054. if (D < Ray.smallnum) { // the lines are almost parallel
  54055. sN = 0.0; // force using point P0 on segment S1
  54056. sD = 1.0; // to prevent possible division by 0.0 later
  54057. tN = e;
  54058. tD = c;
  54059. }
  54060. else { // get the closest points on the infinite lines
  54061. sN = (b * e - c * d);
  54062. tN = (a * e - b * d);
  54063. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  54064. sN = 0.0;
  54065. tN = e;
  54066. tD = c;
  54067. }
  54068. else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  54069. sN = sD;
  54070. tN = e + b;
  54071. tD = c;
  54072. }
  54073. }
  54074. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  54075. tN = 0.0;
  54076. // recompute sc for this edge
  54077. if (-d < 0.0) {
  54078. sN = 0.0;
  54079. }
  54080. else if (-d > a)
  54081. sN = sD;
  54082. else {
  54083. sN = -d;
  54084. sD = a;
  54085. }
  54086. }
  54087. else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  54088. tN = tD;
  54089. // recompute sc for this edge
  54090. if ((-d + b) < 0.0) {
  54091. sN = 0;
  54092. }
  54093. else if ((-d + b) > a) {
  54094. sN = sD;
  54095. }
  54096. else {
  54097. sN = (-d + b);
  54098. sD = a;
  54099. }
  54100. }
  54101. // finally do the division to get sc and tc
  54102. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  54103. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  54104. // get the difference of the two closest points
  54105. var qtc = v.multiplyByFloats(tc, tc, tc);
  54106. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  54107. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  54108. if (isIntersected) {
  54109. return qtc.length();
  54110. }
  54111. return -1;
  54112. };
  54113. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54114. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  54115. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  54116. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  54117. this.direction.normalize();
  54118. return this;
  54119. };
  54120. // Statics
  54121. Ray.Zero = function () {
  54122. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  54123. };
  54124. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54125. var result = Ray.Zero();
  54126. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  54127. };
  54128. /**
  54129. * 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
  54130. * transformed to the given world matrix.
  54131. * @param origin The origin point
  54132. * @param end The end point
  54133. * @param world a matrix to transform the ray to. Default is the identity matrix.
  54134. */
  54135. Ray.CreateNewFromTo = function (origin, end, world) {
  54136. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  54137. var direction = end.subtract(origin);
  54138. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  54139. direction.normalize();
  54140. return Ray.Transform(new Ray(origin, direction, length), world);
  54141. };
  54142. Ray.Transform = function (ray, matrix) {
  54143. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  54144. Ray.TransformToRef(ray, matrix, result);
  54145. return result;
  54146. };
  54147. Ray.TransformToRef = function (ray, matrix, result) {
  54148. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  54149. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  54150. result.length = ray.length;
  54151. var dir = result.direction;
  54152. var len = dir.length();
  54153. if (!(len === 0 || len === 1)) {
  54154. var num = 1.0 / len;
  54155. dir.x *= num;
  54156. dir.y *= num;
  54157. dir.z *= num;
  54158. result.length *= len;
  54159. }
  54160. };
  54161. Ray.smallnum = 0.00000001;
  54162. Ray.rayl = 10e8;
  54163. return Ray;
  54164. }());
  54165. BABYLON.Ray = Ray;
  54166. })(BABYLON || (BABYLON = {}));
  54167. //# sourceMappingURL=babylon.ray.js.map
  54168. var BABYLON;
  54169. (function (BABYLON) {
  54170. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  54171. if (boxMin.x > sphereCenter.x + sphereRadius)
  54172. return false;
  54173. if (sphereCenter.x - sphereRadius > boxMax.x)
  54174. return false;
  54175. if (boxMin.y > sphereCenter.y + sphereRadius)
  54176. return false;
  54177. if (sphereCenter.y - sphereRadius > boxMax.y)
  54178. return false;
  54179. if (boxMin.z > sphereCenter.z + sphereRadius)
  54180. return false;
  54181. if (sphereCenter.z - sphereRadius > boxMax.z)
  54182. return false;
  54183. return true;
  54184. };
  54185. var getLowestRoot = (function () {
  54186. var result = { root: 0, found: false };
  54187. return function (a, b, c, maxR) {
  54188. result.root = 0;
  54189. result.found = false;
  54190. var determinant = b * b - 4.0 * a * c;
  54191. if (determinant < 0)
  54192. return result;
  54193. var sqrtD = Math.sqrt(determinant);
  54194. var r1 = (-b - sqrtD) / (2.0 * a);
  54195. var r2 = (-b + sqrtD) / (2.0 * a);
  54196. if (r1 > r2) {
  54197. var temp = r2;
  54198. r2 = r1;
  54199. r1 = temp;
  54200. }
  54201. if (r1 > 0 && r1 < maxR) {
  54202. result.root = r1;
  54203. result.found = true;
  54204. return result;
  54205. }
  54206. if (r2 > 0 && r2 < maxR) {
  54207. result.root = r2;
  54208. result.found = true;
  54209. return result;
  54210. }
  54211. return result;
  54212. };
  54213. })();
  54214. var Collider = /** @class */ (function () {
  54215. function Collider() {
  54216. this._collisionPoint = BABYLON.Vector3.Zero();
  54217. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  54218. this._tempVector = BABYLON.Vector3.Zero();
  54219. this._tempVector2 = BABYLON.Vector3.Zero();
  54220. this._tempVector3 = BABYLON.Vector3.Zero();
  54221. this._tempVector4 = BABYLON.Vector3.Zero();
  54222. this._edge = BABYLON.Vector3.Zero();
  54223. this._baseToVertex = BABYLON.Vector3.Zero();
  54224. this._destinationPoint = BABYLON.Vector3.Zero();
  54225. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  54226. this._displacementVector = BABYLON.Vector3.Zero();
  54227. this._radius = BABYLON.Vector3.One();
  54228. this._retry = 0;
  54229. this._basePointWorld = BABYLON.Vector3.Zero();
  54230. this._velocityWorld = BABYLON.Vector3.Zero();
  54231. this._normalizedVelocity = BABYLON.Vector3.Zero();
  54232. this._collisionMask = -1;
  54233. }
  54234. Object.defineProperty(Collider.prototype, "collisionMask", {
  54235. get: function () {
  54236. return this._collisionMask;
  54237. },
  54238. set: function (mask) {
  54239. this._collisionMask = !isNaN(mask) ? mask : -1;
  54240. },
  54241. enumerable: true,
  54242. configurable: true
  54243. });
  54244. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  54245. /**
  54246. * Gets the plane normal used to compute the sliding response (in local space)
  54247. */
  54248. get: function () {
  54249. return this._slidePlaneNormal;
  54250. },
  54251. enumerable: true,
  54252. configurable: true
  54253. });
  54254. // Methods
  54255. Collider.prototype._initialize = function (source, dir, e) {
  54256. this._velocity = dir;
  54257. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  54258. this._basePoint = source;
  54259. source.multiplyToRef(this._radius, this._basePointWorld);
  54260. dir.multiplyToRef(this._radius, this._velocityWorld);
  54261. this._velocityWorldLength = this._velocityWorld.length();
  54262. this._epsilon = e;
  54263. this.collisionFound = false;
  54264. };
  54265. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  54266. pa.subtractToRef(point, this._tempVector);
  54267. pb.subtractToRef(point, this._tempVector2);
  54268. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  54269. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54270. if (d < 0)
  54271. return false;
  54272. pc.subtractToRef(point, this._tempVector3);
  54273. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  54274. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54275. if (d < 0)
  54276. return false;
  54277. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  54278. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54279. return d >= 0;
  54280. };
  54281. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  54282. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  54283. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  54284. if (distance > this._velocityWorldLength + max + sphereRadius) {
  54285. return false;
  54286. }
  54287. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  54288. return false;
  54289. return true;
  54290. };
  54291. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  54292. var t0;
  54293. var embeddedInPlane = false;
  54294. //defensive programming, actually not needed.
  54295. if (!trianglePlaneArray) {
  54296. trianglePlaneArray = [];
  54297. }
  54298. if (!trianglePlaneArray[faceIndex]) {
  54299. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  54300. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  54301. }
  54302. var trianglePlane = trianglePlaneArray[faceIndex];
  54303. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  54304. return;
  54305. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  54306. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  54307. if (normalDotVelocity == 0) {
  54308. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  54309. return;
  54310. embeddedInPlane = true;
  54311. t0 = 0;
  54312. }
  54313. else {
  54314. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  54315. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  54316. if (t0 > t1) {
  54317. var temp = t1;
  54318. t1 = t0;
  54319. t0 = temp;
  54320. }
  54321. if (t0 > 1.0 || t1 < 0.0)
  54322. return;
  54323. if (t0 < 0)
  54324. t0 = 0;
  54325. if (t0 > 1.0)
  54326. t0 = 1.0;
  54327. }
  54328. this._collisionPoint.copyFromFloats(0, 0, 0);
  54329. var found = false;
  54330. var t = 1.0;
  54331. if (!embeddedInPlane) {
  54332. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  54333. this._velocity.scaleToRef(t0, this._tempVector);
  54334. this._planeIntersectionPoint.addInPlace(this._tempVector);
  54335. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  54336. found = true;
  54337. t = t0;
  54338. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  54339. }
  54340. }
  54341. if (!found) {
  54342. var velocitySquaredLength = this._velocity.lengthSquared();
  54343. var a = velocitySquaredLength;
  54344. this._basePoint.subtractToRef(p1, this._tempVector);
  54345. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54346. var c = this._tempVector.lengthSquared() - 1.0;
  54347. var lowestRoot = getLowestRoot(a, b, c, t);
  54348. if (lowestRoot.found) {
  54349. t = lowestRoot.root;
  54350. found = true;
  54351. this._collisionPoint.copyFrom(p1);
  54352. }
  54353. this._basePoint.subtractToRef(p2, this._tempVector);
  54354. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54355. c = this._tempVector.lengthSquared() - 1.0;
  54356. lowestRoot = getLowestRoot(a, b, c, t);
  54357. if (lowestRoot.found) {
  54358. t = lowestRoot.root;
  54359. found = true;
  54360. this._collisionPoint.copyFrom(p2);
  54361. }
  54362. this._basePoint.subtractToRef(p3, this._tempVector);
  54363. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54364. c = this._tempVector.lengthSquared() - 1.0;
  54365. lowestRoot = getLowestRoot(a, b, c, t);
  54366. if (lowestRoot.found) {
  54367. t = lowestRoot.root;
  54368. found = true;
  54369. this._collisionPoint.copyFrom(p3);
  54370. }
  54371. p2.subtractToRef(p1, this._edge);
  54372. p1.subtractToRef(this._basePoint, this._baseToVertex);
  54373. var edgeSquaredLength = this._edge.lengthSquared();
  54374. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54375. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54376. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54377. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54378. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54379. lowestRoot = getLowestRoot(a, b, c, t);
  54380. if (lowestRoot.found) {
  54381. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54382. if (f >= 0.0 && f <= 1.0) {
  54383. t = lowestRoot.root;
  54384. found = true;
  54385. this._edge.scaleInPlace(f);
  54386. p1.addToRef(this._edge, this._collisionPoint);
  54387. }
  54388. }
  54389. p3.subtractToRef(p2, this._edge);
  54390. p2.subtractToRef(this._basePoint, this._baseToVertex);
  54391. edgeSquaredLength = this._edge.lengthSquared();
  54392. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54393. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54394. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54395. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54396. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54397. lowestRoot = getLowestRoot(a, b, c, t);
  54398. if (lowestRoot.found) {
  54399. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54400. if (f >= 0.0 && f <= 1.0) {
  54401. t = lowestRoot.root;
  54402. found = true;
  54403. this._edge.scaleInPlace(f);
  54404. p2.addToRef(this._edge, this._collisionPoint);
  54405. }
  54406. }
  54407. p1.subtractToRef(p3, this._edge);
  54408. p3.subtractToRef(this._basePoint, this._baseToVertex);
  54409. edgeSquaredLength = this._edge.lengthSquared();
  54410. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54411. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54412. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54413. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54414. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54415. lowestRoot = getLowestRoot(a, b, c, t);
  54416. if (lowestRoot.found) {
  54417. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54418. if (f >= 0.0 && f <= 1.0) {
  54419. t = lowestRoot.root;
  54420. found = true;
  54421. this._edge.scaleInPlace(f);
  54422. p3.addToRef(this._edge, this._collisionPoint);
  54423. }
  54424. }
  54425. }
  54426. if (found) {
  54427. var distToCollision = t * this._velocity.length();
  54428. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  54429. if (!this.intersectionPoint) {
  54430. this.intersectionPoint = this._collisionPoint.clone();
  54431. }
  54432. else {
  54433. this.intersectionPoint.copyFrom(this._collisionPoint);
  54434. }
  54435. this._nearestDistance = distToCollision;
  54436. this.collisionFound = true;
  54437. }
  54438. }
  54439. };
  54440. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  54441. for (var i = indexStart; i < indexEnd; i += 3) {
  54442. var p1 = pts[indices[i] - decal];
  54443. var p2 = pts[indices[i + 1] - decal];
  54444. var p3 = pts[indices[i + 2] - decal];
  54445. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  54446. }
  54447. };
  54448. Collider.prototype._getResponse = function (pos, vel) {
  54449. pos.addToRef(vel, this._destinationPoint);
  54450. vel.scaleInPlace((this._nearestDistance / vel.length()));
  54451. this._basePoint.addToRef(vel, pos);
  54452. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  54453. this._slidePlaneNormal.normalize();
  54454. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  54455. pos.addInPlace(this._displacementVector);
  54456. this.intersectionPoint.addInPlace(this._displacementVector);
  54457. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  54458. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  54459. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  54460. };
  54461. return Collider;
  54462. }());
  54463. BABYLON.Collider = Collider;
  54464. })(BABYLON || (BABYLON = {}));
  54465. //# sourceMappingURL=babylon.collider.js.map
  54466. var BABYLON;
  54467. (function (BABYLON) {
  54468. //WebWorker code will be inserted to this variable.
  54469. BABYLON.CollisionWorker = "";
  54470. /** Defines supported task for worker process */
  54471. var WorkerTaskType;
  54472. (function (WorkerTaskType) {
  54473. /** Initialization */
  54474. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  54475. /** Update of geometry */
  54476. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  54477. /** Evaluate collision */
  54478. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  54479. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  54480. /** Defines kind of replies returned by worker */
  54481. var WorkerReplyType;
  54482. (function (WorkerReplyType) {
  54483. /** Success */
  54484. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  54485. /** Unkown error */
  54486. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  54487. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  54488. var CollisionCoordinatorWorker = /** @class */ (function () {
  54489. function CollisionCoordinatorWorker() {
  54490. var _this = this;
  54491. this._scaledPosition = BABYLON.Vector3.Zero();
  54492. this._scaledVelocity = BABYLON.Vector3.Zero();
  54493. this.onMeshUpdated = function (transformNode) {
  54494. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  54495. };
  54496. this.onGeometryUpdated = function (geometry) {
  54497. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  54498. };
  54499. this._afterRender = function () {
  54500. if (!_this._init)
  54501. return;
  54502. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  54503. return;
  54504. }
  54505. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  54506. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  54507. if (_this._runningUpdated > 4) {
  54508. return;
  54509. }
  54510. ++_this._runningUpdated;
  54511. var payload = {
  54512. updatedMeshes: _this._addUpdateMeshesList,
  54513. updatedGeometries: _this._addUpdateGeometriesList,
  54514. removedGeometries: _this._toRemoveGeometryArray,
  54515. removedMeshes: _this._toRemoveMeshesArray
  54516. };
  54517. var message = {
  54518. payload: payload,
  54519. taskType: WorkerTaskType.UPDATE
  54520. };
  54521. var serializable = [];
  54522. for (var id in payload.updatedGeometries) {
  54523. if (payload.updatedGeometries.hasOwnProperty(id)) {
  54524. //prepare transferables
  54525. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  54526. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  54527. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  54528. }
  54529. }
  54530. _this._worker.postMessage(message, serializable);
  54531. _this._addUpdateMeshesList = {};
  54532. _this._addUpdateGeometriesList = {};
  54533. _this._toRemoveGeometryArray = [];
  54534. _this._toRemoveMeshesArray = [];
  54535. };
  54536. this._onMessageFromWorker = function (e) {
  54537. var returnData = e.data;
  54538. if (returnData.error != WorkerReplyType.SUCCESS) {
  54539. //TODO what errors can be returned from the worker?
  54540. BABYLON.Tools.Warn("error returned from worker!");
  54541. return;
  54542. }
  54543. switch (returnData.taskType) {
  54544. case WorkerTaskType.INIT:
  54545. _this._init = true;
  54546. //Update the worked with ALL of the scene's current state
  54547. _this._scene.meshes.forEach(function (mesh) {
  54548. _this.onMeshAdded(mesh);
  54549. });
  54550. _this._scene.getGeometries().forEach(function (geometry) {
  54551. _this.onGeometryAdded(geometry);
  54552. });
  54553. break;
  54554. case WorkerTaskType.UPDATE:
  54555. _this._runningUpdated--;
  54556. break;
  54557. case WorkerTaskType.COLLIDE:
  54558. var returnPayload = returnData.payload;
  54559. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  54560. return;
  54561. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  54562. if (callback) {
  54563. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  54564. if (mesh) {
  54565. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  54566. }
  54567. }
  54568. //cleanup
  54569. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  54570. break;
  54571. }
  54572. };
  54573. this._collisionsCallbackArray = [];
  54574. this._init = false;
  54575. this._runningUpdated = 0;
  54576. this._addUpdateMeshesList = {};
  54577. this._addUpdateGeometriesList = {};
  54578. this._toRemoveGeometryArray = [];
  54579. this._toRemoveMeshesArray = [];
  54580. }
  54581. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  54582. if (!this._init)
  54583. return;
  54584. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  54585. return;
  54586. position.divideToRef(collider._radius, this._scaledPosition);
  54587. displacement.divideToRef(collider._radius, this._scaledVelocity);
  54588. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  54589. var payload = {
  54590. collider: {
  54591. position: this._scaledPosition.asArray(),
  54592. velocity: this._scaledVelocity.asArray(),
  54593. radius: collider._radius.asArray()
  54594. },
  54595. collisionId: collisionIndex,
  54596. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  54597. maximumRetry: maximumRetry
  54598. };
  54599. var message = {
  54600. payload: payload,
  54601. taskType: WorkerTaskType.COLLIDE
  54602. };
  54603. this._worker.postMessage(message);
  54604. };
  54605. CollisionCoordinatorWorker.prototype.init = function (scene) {
  54606. this._scene = scene;
  54607. this._scene.registerAfterRender(this._afterRender);
  54608. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  54609. this._worker = new Worker(workerUrl);
  54610. this._worker.onmessage = this._onMessageFromWorker;
  54611. var message = {
  54612. payload: {},
  54613. taskType: WorkerTaskType.INIT
  54614. };
  54615. this._worker.postMessage(message);
  54616. };
  54617. CollisionCoordinatorWorker.prototype.destroy = function () {
  54618. this._scene.unregisterAfterRender(this._afterRender);
  54619. this._worker.terminate();
  54620. };
  54621. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  54622. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  54623. this.onMeshUpdated(mesh);
  54624. };
  54625. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  54626. this._toRemoveMeshesArray.push(mesh.uniqueId);
  54627. };
  54628. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  54629. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  54630. geometry.onGeometryUpdated = this.onGeometryUpdated;
  54631. this.onGeometryUpdated(geometry);
  54632. };
  54633. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  54634. this._toRemoveGeometryArray.push(geometry.id);
  54635. };
  54636. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  54637. var submeshes = [];
  54638. if (mesh.subMeshes) {
  54639. submeshes = mesh.subMeshes.map(function (sm, idx) {
  54640. var boundingInfo = sm.getBoundingInfo();
  54641. return {
  54642. position: idx,
  54643. verticesStart: sm.verticesStart,
  54644. verticesCount: sm.verticesCount,
  54645. indexStart: sm.indexStart,
  54646. indexCount: sm.indexCount,
  54647. hasMaterial: !!sm.getMaterial(),
  54648. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  54649. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  54650. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  54651. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  54652. };
  54653. });
  54654. }
  54655. var geometryId = null;
  54656. if (mesh instanceof BABYLON.Mesh) {
  54657. var geometry = mesh.geometry;
  54658. geometryId = geometry ? geometry.id : null;
  54659. }
  54660. else if (mesh instanceof BABYLON.InstancedMesh) {
  54661. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  54662. geometryId = geometry ? geometry.id : null;
  54663. }
  54664. var boundingInfo = mesh.getBoundingInfo();
  54665. return {
  54666. uniqueId: mesh.uniqueId,
  54667. id: mesh.id,
  54668. name: mesh.name,
  54669. geometryId: geometryId,
  54670. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  54671. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  54672. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  54673. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  54674. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  54675. subMeshes: submeshes,
  54676. checkCollisions: mesh.checkCollisions
  54677. };
  54678. };
  54679. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  54680. return {
  54681. id: geometry.id,
  54682. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  54683. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  54684. indices: new Uint32Array(geometry.getIndices() || []),
  54685. };
  54686. };
  54687. return CollisionCoordinatorWorker;
  54688. }());
  54689. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  54690. var CollisionCoordinatorLegacy = /** @class */ (function () {
  54691. function CollisionCoordinatorLegacy() {
  54692. this._scaledPosition = BABYLON.Vector3.Zero();
  54693. this._scaledVelocity = BABYLON.Vector3.Zero();
  54694. this._finalPosition = BABYLON.Vector3.Zero();
  54695. }
  54696. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  54697. position.divideToRef(collider._radius, this._scaledPosition);
  54698. displacement.divideToRef(collider._radius, this._scaledVelocity);
  54699. collider.collidedMesh = null;
  54700. collider._retry = 0;
  54701. collider._initialVelocity = this._scaledVelocity;
  54702. collider._initialPosition = this._scaledPosition;
  54703. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  54704. this._finalPosition.multiplyInPlace(collider._radius);
  54705. //run the callback
  54706. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  54707. };
  54708. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  54709. this._scene = scene;
  54710. };
  54711. CollisionCoordinatorLegacy.prototype.destroy = function () {
  54712. //Legacy need no destruction method.
  54713. };
  54714. //No update in legacy mode
  54715. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  54716. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  54717. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  54718. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  54719. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  54720. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  54721. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  54722. if (excludedMesh === void 0) { excludedMesh = null; }
  54723. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  54724. if (collider._retry >= maximumRetry) {
  54725. finalPosition.copyFrom(position);
  54726. return;
  54727. }
  54728. // Check if this is a mesh else camera or -1
  54729. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  54730. collider._initialize(position, velocity, closeDistance);
  54731. // Check all meshes
  54732. for (var index = 0; index < this._scene.meshes.length; index++) {
  54733. var mesh = this._scene.meshes[index];
  54734. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  54735. mesh._checkCollision(collider);
  54736. }
  54737. }
  54738. if (!collider.collisionFound) {
  54739. position.addToRef(velocity, finalPosition);
  54740. return;
  54741. }
  54742. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  54743. collider._getResponse(position, velocity);
  54744. }
  54745. if (velocity.length() <= closeDistance) {
  54746. finalPosition.copyFrom(position);
  54747. return;
  54748. }
  54749. collider._retry++;
  54750. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  54751. };
  54752. return CollisionCoordinatorLegacy;
  54753. }());
  54754. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  54755. })(BABYLON || (BABYLON = {}));
  54756. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  54757. var BABYLON;
  54758. (function (BABYLON) {
  54759. /**
  54760. * A particle represents one of the element emitted by a particle system.
  54761. * This is mainly define by its coordinates, direction, velocity and age.
  54762. */
  54763. var Particle = /** @class */ (function () {
  54764. /**
  54765. * Creates a new instance Particle
  54766. * @param particleSystem the particle system the particle belongs to
  54767. */
  54768. function Particle(
  54769. /**
  54770. * particleSystem the particle system the particle belongs to.
  54771. */
  54772. particleSystem) {
  54773. this.particleSystem = particleSystem;
  54774. /**
  54775. * The world position of the particle in the scene.
  54776. */
  54777. this.position = BABYLON.Vector3.Zero();
  54778. /**
  54779. * The world direction of the particle in the scene.
  54780. */
  54781. this.direction = BABYLON.Vector3.Zero();
  54782. /**
  54783. * The color of the particle.
  54784. */
  54785. this.color = new BABYLON.Color4(0, 0, 0, 0);
  54786. /**
  54787. * The color change of the particle per step.
  54788. */
  54789. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  54790. /**
  54791. * Defines how long will the life of the particle be.
  54792. */
  54793. this.lifeTime = 1.0;
  54794. /**
  54795. * The current age of the particle.
  54796. */
  54797. this.age = 0;
  54798. /**
  54799. * The current size of the particle.
  54800. */
  54801. this.size = 0;
  54802. /**
  54803. * The current scale of the particle.
  54804. */
  54805. this.scale = new BABYLON.Vector2(1, 1);
  54806. /**
  54807. * The current angle of the particle.
  54808. */
  54809. this.angle = 0;
  54810. /**
  54811. * Defines how fast is the angle changing.
  54812. */
  54813. this.angularSpeed = 0;
  54814. /**
  54815. * Defines the cell index used by the particle to be rendered from a sprite.
  54816. */
  54817. this.cellIndex = 0;
  54818. this._currentFrameCounter = 0;
  54819. if (!this.particleSystem.isAnimationSheetEnabled) {
  54820. return;
  54821. }
  54822. this.updateCellInfoFromSystem();
  54823. }
  54824. Particle.prototype.updateCellInfoFromSystem = function () {
  54825. this.cellIndex = this.particleSystem.startSpriteCellID;
  54826. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  54827. this.updateCellIndex = this._updateCellIndexWithSpeedCalculated;
  54828. }
  54829. else {
  54830. this.updateCellIndex = this._updateCellIndexWithCustomSpeed;
  54831. }
  54832. };
  54833. Particle.prototype._updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  54834. // (ageOffset / scaledUpdateSpeed) / available cells
  54835. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  54836. this._currentFrameCounter += scaledUpdateSpeed;
  54837. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  54838. this._currentFrameCounter = 0;
  54839. this.cellIndex++;
  54840. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  54841. this.cellIndex = this.particleSystem.endSpriteCellID;
  54842. }
  54843. }
  54844. };
  54845. Particle.prototype._updateCellIndexWithCustomSpeed = function () {
  54846. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  54847. this.cellIndex++;
  54848. this._currentFrameCounter = 0;
  54849. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  54850. if (this.particleSystem.spriteCellLoop) {
  54851. this.cellIndex = this.particleSystem.startSpriteCellID;
  54852. }
  54853. else {
  54854. this.cellIndex = this.particleSystem.endSpriteCellID;
  54855. }
  54856. }
  54857. }
  54858. else {
  54859. this._currentFrameCounter++;
  54860. }
  54861. };
  54862. /**
  54863. * Copy the properties of particle to another one.
  54864. * @param other the particle to copy the information to.
  54865. */
  54866. Particle.prototype.copyTo = function (other) {
  54867. other.position.copyFrom(this.position);
  54868. other.direction.copyFrom(this.direction);
  54869. other.color.copyFrom(this.color);
  54870. other.colorStep.copyFrom(this.colorStep);
  54871. other.lifeTime = this.lifeTime;
  54872. other.age = this.age;
  54873. other.size = this.size;
  54874. other.scale.copyFrom(this.scale);
  54875. other.angle = this.angle;
  54876. other.angularSpeed = this.angularSpeed;
  54877. other.particleSystem = this.particleSystem;
  54878. other.cellIndex = this.cellIndex;
  54879. };
  54880. return Particle;
  54881. }());
  54882. BABYLON.Particle = Particle;
  54883. })(BABYLON || (BABYLON = {}));
  54884. //# sourceMappingURL=babylon.particle.js.map
  54885. var BABYLON;
  54886. (function (BABYLON) {
  54887. /**
  54888. * This represents a particle system in Babylon.
  54889. * 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.
  54890. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  54891. * @example https://doc.babylonjs.com/babylon101/particles
  54892. */
  54893. var ParticleSystem = /** @class */ (function () {
  54894. /**
  54895. * Instantiates a particle system.
  54896. * 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.
  54897. * @param name The name of the particle system
  54898. * @param capacity The max number of particles alive at the same time
  54899. * @param scene The scene the particle system belongs to
  54900. * @param customEffect a custom effect used to change the way particles are rendered by default
  54901. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  54902. * @param epsilon Offset used to render the particles
  54903. */
  54904. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  54905. if (customEffect === void 0) { customEffect = null; }
  54906. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  54907. if (epsilon === void 0) { epsilon = 0.01; }
  54908. var _this = this;
  54909. /**
  54910. * List of animations used by the particle system.
  54911. */
  54912. this.animations = [];
  54913. /**
  54914. * The rendering group used by the Particle system to chose when to render.
  54915. */
  54916. this.renderingGroupId = 0;
  54917. /**
  54918. * The emitter represents the Mesh or position we are attaching the particle system to.
  54919. */
  54920. this.emitter = null;
  54921. /**
  54922. * The maximum number of particles to emit per frame
  54923. */
  54924. this.emitRate = 10;
  54925. /**
  54926. * If you want to launch only a few particles at once, that can be done, as well.
  54927. */
  54928. this.manualEmitCount = -1;
  54929. /**
  54930. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  54931. */
  54932. this.updateSpeed = 0.01;
  54933. /**
  54934. * The amount of time the particle system is running (depends of the overall update speed).
  54935. */
  54936. this.targetStopDuration = 0;
  54937. /**
  54938. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  54939. */
  54940. this.disposeOnStop = false;
  54941. /**
  54942. * Minimum power of emitting particles.
  54943. */
  54944. this.minEmitPower = 1;
  54945. /**
  54946. * Maximum power of emitting particles.
  54947. */
  54948. this.maxEmitPower = 1;
  54949. /**
  54950. * Minimum life time of emitting particles.
  54951. */
  54952. this.minLifeTime = 1;
  54953. /**
  54954. * Maximum life time of emitting particles.
  54955. */
  54956. this.maxLifeTime = 1;
  54957. /**
  54958. * Minimum Size of emitting particles.
  54959. */
  54960. this.minSize = 1;
  54961. /**
  54962. * Maximum Size of emitting particles.
  54963. */
  54964. this.maxSize = 1;
  54965. /**
  54966. * Minimum scale of emitting particles on X axis.
  54967. */
  54968. this.minScaleX = 1;
  54969. /**
  54970. * Maximum scale of emitting particles on X axis.
  54971. */
  54972. this.maxScaleX = 1;
  54973. /**
  54974. * Minimum scale of emitting particles on Y axis.
  54975. */
  54976. this.minScaleY = 1;
  54977. /**
  54978. * Maximum scale of emitting particles on Y axis.
  54979. */
  54980. this.maxScaleY = 1;
  54981. /**
  54982. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  54983. */
  54984. this.minAngularSpeed = 0;
  54985. /**
  54986. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  54987. */
  54988. this.maxAngularSpeed = 0;
  54989. /**
  54990. * The layer mask we are rendering the particles through.
  54991. */
  54992. this.layerMask = 0x0FFFFFFF;
  54993. /**
  54994. * This can help using your own shader to render the particle system.
  54995. * The according effect will be created
  54996. */
  54997. this.customShader = null;
  54998. /**
  54999. * By default particle system starts as soon as they are created. This prevents the
  55000. * automatic start to happen and let you decide when to start emitting particles.
  55001. */
  55002. this.preventAutoStart = false;
  55003. /**
  55004. * Callback triggered when the particle animation is ending.
  55005. */
  55006. this.onAnimationEnd = null;
  55007. /**
  55008. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  55009. */
  55010. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  55011. /**
  55012. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  55013. * to override the particles.
  55014. */
  55015. this.forceDepthWrite = false;
  55016. /**
  55017. * You can use gravity if you want to give an orientation to your particles.
  55018. */
  55019. this.gravity = BABYLON.Vector3.Zero();
  55020. /**
  55021. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  55022. */
  55023. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55024. /**
  55025. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  55026. */
  55027. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55028. /**
  55029. * Color the particle will have at the end of its lifetime.
  55030. */
  55031. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  55032. /**
  55033. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  55034. */
  55035. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55036. /**
  55037. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  55038. */
  55039. this.spriteCellLoop = true;
  55040. /**
  55041. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  55042. */
  55043. this.spriteCellChangeSpeed = 0;
  55044. /**
  55045. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  55046. */
  55047. this.startSpriteCellID = 0;
  55048. /**
  55049. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  55050. */
  55051. this.endSpriteCellID = 0;
  55052. /**
  55053. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  55054. */
  55055. this.spriteCellWidth = 0;
  55056. /**
  55057. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  55058. */
  55059. this.spriteCellHeight = 0;
  55060. /**
  55061. * An event triggered when the system is disposed.
  55062. */
  55063. this.onDisposeObservable = new BABYLON.Observable();
  55064. this._particles = new Array();
  55065. this._stockParticles = new Array();
  55066. this._newPartsExcess = 0;
  55067. this._vertexBuffers = {};
  55068. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  55069. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  55070. this._scaledDirection = BABYLON.Vector3.Zero();
  55071. this._scaledGravity = BABYLON.Vector3.Zero();
  55072. this._currentRenderId = -1;
  55073. this._started = false;
  55074. this._stopped = false;
  55075. this._actualFrame = 0;
  55076. this._vertexBufferSize = 12;
  55077. // start of sub system methods
  55078. /**
  55079. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  55080. * Its lifetime will start back at 0.
  55081. */
  55082. this.recycleParticle = function (particle) {
  55083. var lastParticle = _this._particles.pop();
  55084. if (lastParticle !== particle) {
  55085. lastParticle.copyTo(particle);
  55086. }
  55087. _this._stockParticles.push(lastParticle);
  55088. };
  55089. this._createParticle = function () {
  55090. var particle;
  55091. if (_this._stockParticles.length !== 0) {
  55092. particle = _this._stockParticles.pop();
  55093. particle.age = 0;
  55094. particle.cellIndex = _this.startSpriteCellID;
  55095. }
  55096. else {
  55097. particle = new BABYLON.Particle(_this);
  55098. }
  55099. return particle;
  55100. };
  55101. this._emitFromParticle = function (particle) {
  55102. if (!_this.subEmitters || _this.subEmitters.length === 0) {
  55103. return;
  55104. }
  55105. var templateIndex = Math.floor(Math.random() * _this.subEmitters.length);
  55106. var subSystem = _this.subEmitters[templateIndex].clone(_this.name + "_sub", particle.position.clone());
  55107. subSystem._rootParticleSystem = _this;
  55108. _this.activeSubSystems.push(subSystem);
  55109. subSystem.start();
  55110. };
  55111. this._appendParticleVertexes = null;
  55112. this.id = name;
  55113. this.name = name;
  55114. this._capacity = capacity;
  55115. this._epsilon = epsilon;
  55116. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  55117. if (isAnimationSheetEnabled) {
  55118. this._vertexBufferSize = 13;
  55119. }
  55120. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  55121. this._customEffect = customEffect;
  55122. scene.particleSystems.push(this);
  55123. this._createIndexBuffer();
  55124. // 13 floats per particle (x, y, z, r, g, b, a, angle, scaleX, scaleY, offsetX, offsetY) + 1 filler
  55125. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  55126. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  55127. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  55128. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  55129. var options = this._vertexBuffer.createVertexBuffer("options", 7, 3);
  55130. var size = this._vertexBuffer.createVertexBuffer("size", 10, 2);
  55131. if (this._isAnimationSheetEnabled) {
  55132. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 12, 1);
  55133. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  55134. }
  55135. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  55136. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  55137. this._vertexBuffers["options"] = options;
  55138. this._vertexBuffers["size"] = size;
  55139. // Default emitter type
  55140. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  55141. this.updateFunction = function (particles) {
  55142. for (var index = 0; index < particles.length; index++) {
  55143. var particle = particles[index];
  55144. particle.age += _this._scaledUpdateSpeed;
  55145. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  55146. _this._emitFromParticle(particle);
  55147. _this.recycleParticle(particle);
  55148. index--;
  55149. continue;
  55150. }
  55151. else {
  55152. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  55153. particle.color.addInPlace(_this._scaledColorStep);
  55154. if (particle.color.a < 0)
  55155. particle.color.a = 0;
  55156. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  55157. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  55158. particle.position.addInPlace(_this._scaledDirection);
  55159. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  55160. particle.direction.addInPlace(_this._scaledGravity);
  55161. if (_this._isAnimationSheetEnabled) {
  55162. particle.updateCellIndex(_this._scaledUpdateSpeed);
  55163. }
  55164. }
  55165. }
  55166. };
  55167. }
  55168. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  55169. /**
  55170. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55171. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55172. */
  55173. get: function () {
  55174. if (this.particleEmitterType.direction1) {
  55175. return this.particleEmitterType.direction1;
  55176. }
  55177. return BABYLON.Vector3.Zero();
  55178. },
  55179. set: function (value) {
  55180. if (this.particleEmitterType.direction1) {
  55181. this.particleEmitterType.direction1 = value;
  55182. }
  55183. },
  55184. enumerable: true,
  55185. configurable: true
  55186. });
  55187. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  55188. /**
  55189. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55190. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55191. */
  55192. get: function () {
  55193. if (this.particleEmitterType.direction2) {
  55194. return this.particleEmitterType.direction2;
  55195. }
  55196. return BABYLON.Vector3.Zero();
  55197. },
  55198. set: function (value) {
  55199. if (this.particleEmitterType.direction2) {
  55200. this.particleEmitterType.direction2 = value;
  55201. }
  55202. },
  55203. enumerable: true,
  55204. configurable: true
  55205. });
  55206. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  55207. /**
  55208. * 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.
  55209. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55210. */
  55211. get: function () {
  55212. if (this.particleEmitterType.minEmitBox) {
  55213. return this.particleEmitterType.minEmitBox;
  55214. }
  55215. return BABYLON.Vector3.Zero();
  55216. },
  55217. set: function (value) {
  55218. if (this.particleEmitterType.minEmitBox) {
  55219. this.particleEmitterType.minEmitBox = value;
  55220. }
  55221. },
  55222. enumerable: true,
  55223. configurable: true
  55224. });
  55225. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  55226. /**
  55227. * 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.
  55228. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55229. */
  55230. get: function () {
  55231. if (this.particleEmitterType.maxEmitBox) {
  55232. return this.particleEmitterType.maxEmitBox;
  55233. }
  55234. return BABYLON.Vector3.Zero();
  55235. },
  55236. set: function (value) {
  55237. if (this.particleEmitterType.maxEmitBox) {
  55238. this.particleEmitterType.maxEmitBox = value;
  55239. }
  55240. },
  55241. enumerable: true,
  55242. configurable: true
  55243. });
  55244. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  55245. /**
  55246. * Sets a callback that will be triggered when the system is disposed.
  55247. */
  55248. set: function (callback) {
  55249. if (this._onDisposeObserver) {
  55250. this.onDisposeObservable.remove(this._onDisposeObserver);
  55251. }
  55252. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  55253. },
  55254. enumerable: true,
  55255. configurable: true
  55256. });
  55257. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  55258. /**
  55259. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  55260. */
  55261. get: function () {
  55262. return this._isAnimationSheetEnabled;
  55263. },
  55264. enumerable: true,
  55265. configurable: true
  55266. });
  55267. Object.defineProperty(ParticleSystem.prototype, "particles", {
  55268. //end of Sub-emitter
  55269. /**
  55270. * Gets the current list of active particles
  55271. */
  55272. get: function () {
  55273. return this._particles;
  55274. },
  55275. enumerable: true,
  55276. configurable: true
  55277. });
  55278. /**
  55279. * Returns the string "ParticleSystem"
  55280. * @returns a string containing the class name
  55281. */
  55282. ParticleSystem.prototype.getClassName = function () {
  55283. return "ParticleSystem";
  55284. };
  55285. ParticleSystem.prototype._createIndexBuffer = function () {
  55286. var indices = [];
  55287. var index = 0;
  55288. for (var count = 0; count < this._capacity; count++) {
  55289. indices.push(index);
  55290. indices.push(index + 1);
  55291. indices.push(index + 2);
  55292. indices.push(index);
  55293. indices.push(index + 2);
  55294. indices.push(index + 3);
  55295. index += 4;
  55296. }
  55297. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  55298. };
  55299. /**
  55300. * Gets the maximum number of particles active at the same time.
  55301. * @returns The max number of active particles.
  55302. */
  55303. ParticleSystem.prototype.getCapacity = function () {
  55304. return this._capacity;
  55305. };
  55306. /**
  55307. * Gets Wether there are still active particles in the system.
  55308. * @returns True if it is alive, otherwise false.
  55309. */
  55310. ParticleSystem.prototype.isAlive = function () {
  55311. return this._alive;
  55312. };
  55313. /**
  55314. * Gets Wether the system has been started.
  55315. * @returns True if it has been started, otherwise false.
  55316. */
  55317. ParticleSystem.prototype.isStarted = function () {
  55318. return this._started;
  55319. };
  55320. /**
  55321. * Starts the particle system and begins to emit.
  55322. */
  55323. ParticleSystem.prototype.start = function () {
  55324. this._started = true;
  55325. this._stopped = false;
  55326. this._actualFrame = 0;
  55327. if (this.subEmitters && this.subEmitters.length != 0) {
  55328. this.activeSubSystems = new Array();
  55329. }
  55330. };
  55331. /**
  55332. * Stops the particle system.
  55333. * @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.
  55334. */
  55335. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  55336. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  55337. this._stopped = true;
  55338. if (stopSubEmitters) {
  55339. this._stopSubEmitters();
  55340. }
  55341. };
  55342. // animation sheet
  55343. /**
  55344. * Remove all active particles
  55345. */
  55346. ParticleSystem.prototype.reset = function () {
  55347. this._stockParticles = [];
  55348. this._particles = [];
  55349. };
  55350. /**
  55351. * @hidden (for internal use only)
  55352. */
  55353. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  55354. var offset = index * this._vertexBufferSize;
  55355. this._vertexData[offset] = particle.position.x;
  55356. this._vertexData[offset + 1] = particle.position.y;
  55357. this._vertexData[offset + 2] = particle.position.z;
  55358. this._vertexData[offset + 3] = particle.color.r;
  55359. this._vertexData[offset + 4] = particle.color.g;
  55360. this._vertexData[offset + 5] = particle.color.b;
  55361. this._vertexData[offset + 6] = particle.color.a;
  55362. this._vertexData[offset + 7] = particle.angle;
  55363. this._vertexData[offset + 8] = offsetX;
  55364. this._vertexData[offset + 9] = offsetY;
  55365. this._vertexData[offset + 10] = particle.scale.x * particle.size;
  55366. this._vertexData[offset + 11] = particle.scale.y * particle.size;
  55367. };
  55368. /**
  55369. * @hidden (for internal use only)
  55370. */
  55371. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  55372. if (offsetX === 0)
  55373. offsetX = this._epsilon;
  55374. else if (offsetX === 1)
  55375. offsetX = 1 - this._epsilon;
  55376. if (offsetY === 0)
  55377. offsetY = this._epsilon;
  55378. else if (offsetY === 1)
  55379. offsetY = 1 - this._epsilon;
  55380. var offset = index * this._vertexBufferSize;
  55381. this._vertexData[offset] = particle.position.x;
  55382. this._vertexData[offset + 1] = particle.position.y;
  55383. this._vertexData[offset + 2] = particle.position.z;
  55384. this._vertexData[offset + 3] = particle.color.r;
  55385. this._vertexData[offset + 4] = particle.color.g;
  55386. this._vertexData[offset + 5] = particle.color.b;
  55387. this._vertexData[offset + 6] = particle.color.a;
  55388. this._vertexData[offset + 7] = particle.angle;
  55389. this._vertexData[offset + 8] = offsetX;
  55390. this._vertexData[offset + 9] = offsetY;
  55391. this._vertexData[offset + 10] = particle.scale.x * particle.size;
  55392. this._vertexData[offset + 11] = particle.scale.y * particle.size;
  55393. this._vertexData[offset + 12] = particle.cellIndex;
  55394. };
  55395. ParticleSystem.prototype._stopSubEmitters = function () {
  55396. if (!this.activeSubSystems) {
  55397. return;
  55398. }
  55399. this.activeSubSystems.forEach(function (subSystem) {
  55400. subSystem.stop(true);
  55401. });
  55402. this.activeSubSystems = new Array();
  55403. };
  55404. ParticleSystem.prototype._removeFromRoot = function () {
  55405. if (!this._rootParticleSystem) {
  55406. return;
  55407. }
  55408. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  55409. if (index !== -1) {
  55410. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  55411. }
  55412. };
  55413. // end of sub system methods
  55414. ParticleSystem.prototype._update = function (newParticles) {
  55415. // Update current
  55416. this._alive = this._particles.length > 0;
  55417. this.updateFunction(this._particles);
  55418. // Add new ones
  55419. var worldMatrix;
  55420. if (this.emitter.position) {
  55421. var emitterMesh = this.emitter;
  55422. worldMatrix = emitterMesh.getWorldMatrix();
  55423. }
  55424. else {
  55425. var emitterPosition = this.emitter;
  55426. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  55427. }
  55428. var particle;
  55429. for (var index = 0; index < newParticles; index++) {
  55430. if (this._particles.length === this._capacity) {
  55431. break;
  55432. }
  55433. particle = this._createParticle();
  55434. this._particles.push(particle);
  55435. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  55436. if (this.startPositionFunction) {
  55437. this.startPositionFunction(worldMatrix, particle.position, particle);
  55438. }
  55439. else {
  55440. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  55441. }
  55442. if (this.startDirectionFunction) {
  55443. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  55444. }
  55445. else {
  55446. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  55447. }
  55448. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  55449. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  55450. particle.scale.copyFromFloats(BABYLON.Scalar.RandomRange(this.minScaleX, this.maxScaleX), BABYLON.Scalar.RandomRange(this.minScaleY, this.maxScaleY));
  55451. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  55452. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  55453. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  55454. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  55455. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  55456. }
  55457. };
  55458. ParticleSystem.prototype._getEffect = function () {
  55459. if (this._customEffect) {
  55460. return this._customEffect;
  55461. }
  55462. ;
  55463. var defines = [];
  55464. if (this._scene.clipPlane) {
  55465. defines.push("#define CLIPPLANE");
  55466. }
  55467. if (this._isAnimationSheetEnabled) {
  55468. defines.push("#define ANIMATESHEET");
  55469. }
  55470. // Effect
  55471. var join = defines.join("\n");
  55472. if (this._cachedDefines !== join) {
  55473. this._cachedDefines = join;
  55474. var attributesNamesOrOptions;
  55475. var effectCreationOption;
  55476. if (this._isAnimationSheetEnabled) {
  55477. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "size", "cellIndex"];
  55478. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  55479. }
  55480. else {
  55481. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "size",];
  55482. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  55483. }
  55484. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  55485. }
  55486. return this._effect;
  55487. };
  55488. /**
  55489. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  55490. */
  55491. ParticleSystem.prototype.animate = function () {
  55492. if (!this._started)
  55493. return;
  55494. var effect = this._getEffect();
  55495. // Check
  55496. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  55497. return;
  55498. if (this._currentRenderId === this._scene.getRenderId()) {
  55499. return;
  55500. }
  55501. this._currentRenderId = this._scene.getRenderId();
  55502. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  55503. // determine the number of particles we need to create
  55504. var newParticles;
  55505. if (this.manualEmitCount > -1) {
  55506. newParticles = this.manualEmitCount;
  55507. this._newPartsExcess = 0;
  55508. this.manualEmitCount = 0;
  55509. }
  55510. else {
  55511. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  55512. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  55513. }
  55514. if (this._newPartsExcess > 1.0) {
  55515. newParticles += this._newPartsExcess >> 0;
  55516. this._newPartsExcess -= this._newPartsExcess >> 0;
  55517. }
  55518. this._alive = false;
  55519. if (!this._stopped) {
  55520. this._actualFrame += this._scaledUpdateSpeed;
  55521. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  55522. this.stop();
  55523. }
  55524. else {
  55525. newParticles = 0;
  55526. }
  55527. this._update(newParticles);
  55528. // Stopped?
  55529. if (this._stopped) {
  55530. if (!this._alive) {
  55531. this._started = false;
  55532. if (this.onAnimationEnd) {
  55533. this.onAnimationEnd();
  55534. }
  55535. if (this.disposeOnStop) {
  55536. this._scene._toBeDisposed.push(this);
  55537. }
  55538. }
  55539. }
  55540. // Animation sheet
  55541. if (this._isAnimationSheetEnabled) {
  55542. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  55543. }
  55544. else {
  55545. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  55546. }
  55547. // Update VBO
  55548. var offset = 0;
  55549. for (var index = 0; index < this._particles.length; index++) {
  55550. var particle = this._particles[index];
  55551. this._appendParticleVertexes(offset, particle);
  55552. offset += 4;
  55553. }
  55554. if (this._vertexBuffer) {
  55555. this._vertexBuffer.update(this._vertexData);
  55556. }
  55557. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  55558. this.stop();
  55559. }
  55560. };
  55561. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  55562. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  55563. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  55564. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  55565. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  55566. };
  55567. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  55568. this._appendParticleVertex(offset++, particle, 0, 0);
  55569. this._appendParticleVertex(offset++, particle, 1, 0);
  55570. this._appendParticleVertex(offset++, particle, 1, 1);
  55571. this._appendParticleVertex(offset++, particle, 0, 1);
  55572. };
  55573. /**
  55574. * Rebuilds the particle system.
  55575. */
  55576. ParticleSystem.prototype.rebuild = function () {
  55577. this._createIndexBuffer();
  55578. if (this._vertexBuffer) {
  55579. this._vertexBuffer._rebuild();
  55580. }
  55581. };
  55582. /**
  55583. * Is this system ready to be used/rendered
  55584. * @return true if the system is ready
  55585. */
  55586. ParticleSystem.prototype.isReady = function () {
  55587. var effect = this._getEffect();
  55588. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  55589. return false;
  55590. }
  55591. return true;
  55592. };
  55593. /**
  55594. * Renders the particle system in its current state.
  55595. * @returns the current number of particles
  55596. */
  55597. ParticleSystem.prototype.render = function () {
  55598. var effect = this._getEffect();
  55599. // Check
  55600. if (!this.isReady() || !this._particles.length) {
  55601. return 0;
  55602. }
  55603. var engine = this._scene.getEngine();
  55604. // Render
  55605. engine.enableEffect(effect);
  55606. engine.setState(false);
  55607. var viewMatrix = this._scene.getViewMatrix();
  55608. effect.setTexture("diffuseSampler", this.particleTexture);
  55609. effect.setMatrix("view", viewMatrix);
  55610. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  55611. if (this._isAnimationSheetEnabled && this.particleTexture) {
  55612. var baseSize = this.particleTexture.getBaseSize();
  55613. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  55614. }
  55615. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  55616. if (this._scene.clipPlane) {
  55617. var clipPlane = this._scene.clipPlane;
  55618. var invView = viewMatrix.clone();
  55619. invView.invert();
  55620. effect.setMatrix("invView", invView);
  55621. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  55622. }
  55623. // VBOs
  55624. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  55625. // Draw order
  55626. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  55627. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  55628. }
  55629. else {
  55630. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  55631. }
  55632. if (this.forceDepthWrite) {
  55633. engine.setDepthWrite(true);
  55634. }
  55635. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  55636. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  55637. return this._particles.length;
  55638. };
  55639. /**
  55640. * Disposes the particle system and free the associated resources
  55641. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  55642. */
  55643. ParticleSystem.prototype.dispose = function (disposeTexture) {
  55644. if (disposeTexture === void 0) { disposeTexture = true; }
  55645. if (this._vertexBuffer) {
  55646. this._vertexBuffer.dispose();
  55647. this._vertexBuffer = null;
  55648. }
  55649. if (this._indexBuffer) {
  55650. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  55651. this._indexBuffer = null;
  55652. }
  55653. if (disposeTexture && this.particleTexture) {
  55654. this.particleTexture.dispose();
  55655. this.particleTexture = null;
  55656. }
  55657. this._removeFromRoot();
  55658. // Remove from scene
  55659. var index = this._scene.particleSystems.indexOf(this);
  55660. if (index > -1) {
  55661. this._scene.particleSystems.splice(index, 1);
  55662. }
  55663. // Callback
  55664. this.onDisposeObservable.notifyObservers(this);
  55665. this.onDisposeObservable.clear();
  55666. };
  55667. /**
  55668. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  55669. * @param radius The radius of the sphere to emit from
  55670. * @returns the emitter
  55671. */
  55672. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  55673. if (radius === void 0) { radius = 1; }
  55674. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  55675. this.particleEmitterType = particleEmitter;
  55676. return particleEmitter;
  55677. };
  55678. /**
  55679. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  55680. * @param radius The radius of the sphere to emit from
  55681. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  55682. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  55683. * @returns the emitter
  55684. */
  55685. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  55686. if (radius === void 0) { radius = 1; }
  55687. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  55688. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  55689. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  55690. this.particleEmitterType = particleEmitter;
  55691. return particleEmitter;
  55692. };
  55693. /**
  55694. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  55695. * @param radius The radius of the cone to emit from
  55696. * @param angle The base angle of the cone
  55697. * @returns the emitter
  55698. */
  55699. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  55700. if (radius === void 0) { radius = 1; }
  55701. if (angle === void 0) { angle = Math.PI / 4; }
  55702. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  55703. this.particleEmitterType = particleEmitter;
  55704. return particleEmitter;
  55705. };
  55706. // 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.
  55707. /**
  55708. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  55709. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  55710. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  55711. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  55712. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  55713. * @returns the emitter
  55714. */
  55715. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  55716. var particleEmitter = new BABYLON.BoxParticleEmitter();
  55717. this.particleEmitterType = particleEmitter;
  55718. this.direction1 = direction1;
  55719. this.direction2 = direction2;
  55720. this.minEmitBox = minEmitBox;
  55721. this.maxEmitBox = maxEmitBox;
  55722. return particleEmitter;
  55723. };
  55724. // Clone
  55725. /**
  55726. * Clones the particle system.
  55727. * @param name The name of the cloned object
  55728. * @param newEmitter The new emitter to use
  55729. * @returns the cloned particle system
  55730. */
  55731. ParticleSystem.prototype.clone = function (name, newEmitter) {
  55732. var custom = null;
  55733. var program = null;
  55734. if (this.customShader != null) {
  55735. program = this.customShader;
  55736. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  55737. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  55738. }
  55739. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  55740. result.customShader = program;
  55741. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  55742. if (newEmitter === undefined) {
  55743. newEmitter = this.emitter;
  55744. }
  55745. result.emitter = newEmitter;
  55746. if (this.particleTexture) {
  55747. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  55748. }
  55749. if (!this.preventAutoStart) {
  55750. result.start();
  55751. }
  55752. return result;
  55753. };
  55754. /**
  55755. * Serializes the particle system to a JSON object.
  55756. * @returns the JSON object
  55757. */
  55758. ParticleSystem.prototype.serialize = function () {
  55759. var serializationObject = {};
  55760. serializationObject.name = this.name;
  55761. serializationObject.id = this.id;
  55762. // Emitter
  55763. if (this.emitter.position) {
  55764. var emitterMesh = this.emitter;
  55765. serializationObject.emitterId = emitterMesh.id;
  55766. }
  55767. else {
  55768. var emitterPosition = this.emitter;
  55769. serializationObject.emitter = emitterPosition.asArray();
  55770. }
  55771. serializationObject.capacity = this.getCapacity();
  55772. if (this.particleTexture) {
  55773. serializationObject.textureName = this.particleTexture.name;
  55774. }
  55775. // Animations
  55776. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  55777. // Particle system
  55778. serializationObject.minAngularSpeed = this.minAngularSpeed;
  55779. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  55780. serializationObject.minSize = this.minSize;
  55781. serializationObject.maxSize = this.maxSize;
  55782. serializationObject.minScaleX = this.minScaleX;
  55783. serializationObject.maxScaleX = this.maxScaleX;
  55784. serializationObject.minScaleY = this.minScaleY;
  55785. serializationObject.maxScaleY = this.maxScaleY;
  55786. serializationObject.minEmitPower = this.minEmitPower;
  55787. serializationObject.maxEmitPower = this.maxEmitPower;
  55788. serializationObject.minLifeTime = this.minLifeTime;
  55789. serializationObject.maxLifeTime = this.maxLifeTime;
  55790. serializationObject.emitRate = this.emitRate;
  55791. serializationObject.minEmitBox = this.minEmitBox.asArray();
  55792. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  55793. serializationObject.gravity = this.gravity.asArray();
  55794. serializationObject.direction1 = this.direction1.asArray();
  55795. serializationObject.direction2 = this.direction2.asArray();
  55796. serializationObject.color1 = this.color1.asArray();
  55797. serializationObject.color2 = this.color2.asArray();
  55798. serializationObject.colorDead = this.colorDead.asArray();
  55799. serializationObject.updateSpeed = this.updateSpeed;
  55800. serializationObject.targetStopDuration = this.targetStopDuration;
  55801. serializationObject.textureMask = this.textureMask.asArray();
  55802. serializationObject.blendMode = this.blendMode;
  55803. serializationObject.customShader = this.customShader;
  55804. serializationObject.preventAutoStart = this.preventAutoStart;
  55805. serializationObject.startSpriteCellID = this.startSpriteCellID;
  55806. serializationObject.endSpriteCellID = this.endSpriteCellID;
  55807. serializationObject.spriteCellLoop = this.spriteCellLoop;
  55808. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  55809. serializationObject.spriteCellWidth = this.spriteCellWidth;
  55810. serializationObject.spriteCellHeight = this.spriteCellHeight;
  55811. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  55812. // Emitter
  55813. if (this.particleEmitterType) {
  55814. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  55815. }
  55816. return serializationObject;
  55817. };
  55818. /**
  55819. * Parses a JSON object to create a particle system.
  55820. * @param parsedParticleSystem The JSON object to parse
  55821. * @param scene The scene to create the particle system in
  55822. * @param rootUrl The root url to use to load external dependencies like texture
  55823. * @returns the Parsed particle system
  55824. */
  55825. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  55826. var name = parsedParticleSystem.name;
  55827. var custom = null;
  55828. var program = null;
  55829. if (parsedParticleSystem.customShader) {
  55830. program = parsedParticleSystem.customShader;
  55831. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  55832. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  55833. }
  55834. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  55835. particleSystem.customShader = program;
  55836. if (parsedParticleSystem.id) {
  55837. particleSystem.id = parsedParticleSystem.id;
  55838. }
  55839. // Auto start
  55840. if (parsedParticleSystem.preventAutoStart) {
  55841. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  55842. }
  55843. // Texture
  55844. if (parsedParticleSystem.textureName) {
  55845. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  55846. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  55847. }
  55848. // Emitter
  55849. if (parsedParticleSystem.emitterId) {
  55850. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  55851. }
  55852. else {
  55853. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  55854. }
  55855. // Animations
  55856. if (parsedParticleSystem.animations) {
  55857. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  55858. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  55859. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  55860. }
  55861. }
  55862. if (parsedParticleSystem.autoAnimate) {
  55863. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  55864. }
  55865. // Particle system
  55866. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  55867. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  55868. particleSystem.minSize = parsedParticleSystem.minSize;
  55869. particleSystem.maxSize = parsedParticleSystem.maxSize;
  55870. if (parsedParticleSystem.minScaleX) {
  55871. particleSystem.minScaleX = parsedParticleSystem.minScaleX;
  55872. particleSystem.maxScaleX = parsedParticleSystem.maxScaleX;
  55873. particleSystem.minScaleY = parsedParticleSystem.minScaleY;
  55874. particleSystem.maxScaleY = parsedParticleSystem.maxScaleY;
  55875. }
  55876. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  55877. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  55878. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  55879. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  55880. particleSystem.emitRate = parsedParticleSystem.emitRate;
  55881. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  55882. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  55883. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  55884. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  55885. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  55886. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  55887. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  55888. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  55889. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  55890. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  55891. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  55892. particleSystem.blendMode = parsedParticleSystem.blendMode;
  55893. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  55894. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  55895. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  55896. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  55897. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  55898. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  55899. if (!particleSystem.preventAutoStart) {
  55900. particleSystem.start();
  55901. }
  55902. return particleSystem;
  55903. };
  55904. /**
  55905. * Source color is added to the destination color without alpha affecting the result.
  55906. */
  55907. ParticleSystem.BLENDMODE_ONEONE = 0;
  55908. /**
  55909. * Blend current color and particle color using particle’s alpha.
  55910. */
  55911. ParticleSystem.BLENDMODE_STANDARD = 1;
  55912. return ParticleSystem;
  55913. }());
  55914. BABYLON.ParticleSystem = ParticleSystem;
  55915. })(BABYLON || (BABYLON = {}));
  55916. //# sourceMappingURL=babylon.particleSystem.js.map
  55917. //# sourceMappingURL=babylon.IParticleEmitterType.js.map
  55918. var BABYLON;
  55919. (function (BABYLON) {
  55920. /**
  55921. * Particle emitter emitting particles from the inside of a box.
  55922. * It emits the particles randomly between 2 given directions.
  55923. */
  55924. var BoxParticleEmitter = /** @class */ (function () {
  55925. /**
  55926. * Creates a new instance BoxParticleEmitter
  55927. */
  55928. function BoxParticleEmitter() {
  55929. /**
  55930. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55931. */
  55932. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  55933. /**
  55934. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55935. */
  55936. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  55937. /**
  55938. * 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.
  55939. */
  55940. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  55941. /**
  55942. * 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.
  55943. */
  55944. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  55945. }
  55946. /**
  55947. * Called by the particle System when the direction is computed for the created particle.
  55948. * @param emitPower is the power of the particle (speed)
  55949. * @param worldMatrix is the world matrix of the particle system
  55950. * @param directionToUpdate is the direction vector to update with the result
  55951. * @param particle is the particle we are computed the direction for
  55952. */
  55953. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  55954. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  55955. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  55956. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  55957. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  55958. };
  55959. /**
  55960. * Called by the particle System when the position is computed for the created particle.
  55961. * @param worldMatrix is the world matrix of the particle system
  55962. * @param positionToUpdate is the position vector to update with the result
  55963. * @param particle is the particle we are computed the position for
  55964. */
  55965. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  55966. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  55967. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  55968. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  55969. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  55970. };
  55971. /**
  55972. * Clones the current emitter and returns a copy of it
  55973. * @returns the new emitter
  55974. */
  55975. BoxParticleEmitter.prototype.clone = function () {
  55976. var newOne = new BoxParticleEmitter();
  55977. BABYLON.Tools.DeepCopy(this, newOne);
  55978. return newOne;
  55979. };
  55980. /**
  55981. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  55982. * @param effect defines the update shader
  55983. */
  55984. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  55985. effect.setVector3("direction1", this.direction1);
  55986. effect.setVector3("direction2", this.direction2);
  55987. effect.setVector3("minEmitBox", this.minEmitBox);
  55988. effect.setVector3("maxEmitBox", this.maxEmitBox);
  55989. };
  55990. /**
  55991. * Returns a string to use to update the GPU particles update shader
  55992. * @returns a string containng the defines string
  55993. */
  55994. BoxParticleEmitter.prototype.getEffectDefines = function () {
  55995. return "#define BOXEMITTER";
  55996. };
  55997. /**
  55998. * Returns the string "BoxEmitter"
  55999. * @returns a string containing the class name
  56000. */
  56001. BoxParticleEmitter.prototype.getClassName = function () {
  56002. return "BoxEmitter";
  56003. };
  56004. /**
  56005. * Serializes the particle system to a JSON object.
  56006. * @returns the JSON object
  56007. */
  56008. BoxParticleEmitter.prototype.serialize = function () {
  56009. var serializationObject = {};
  56010. serializationObject.type = this.getClassName();
  56011. serializationObject.direction1 = this.direction1.asArray();
  56012. serializationObject.direction2 = this.direction2.asArray();
  56013. serializationObject.minEmitBox = this.minEmitBox.asArray();
  56014. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  56015. return serializationObject;
  56016. };
  56017. /**
  56018. * Parse properties from a JSON object
  56019. * @param serializationObject defines the JSON object
  56020. */
  56021. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  56022. this.direction1.copyFrom(serializationObject.direction1);
  56023. this.direction2.copyFrom(serializationObject.direction2);
  56024. this.minEmitBox.copyFrom(serializationObject.minEmitBox);
  56025. this.maxEmitBox.copyFrom(serializationObject.maxEmitBox);
  56026. };
  56027. return BoxParticleEmitter;
  56028. }());
  56029. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  56030. })(BABYLON || (BABYLON = {}));
  56031. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  56032. var BABYLON;
  56033. (function (BABYLON) {
  56034. /**
  56035. * Particle emitter emitting particles from the inside of a cone.
  56036. * It emits the particles alongside the cone volume from the base to the particle.
  56037. * The emission direction might be randomized.
  56038. */
  56039. var ConeParticleEmitter = /** @class */ (function () {
  56040. /**
  56041. * Creates a new instance ConeParticleEmitter
  56042. * @param radius the radius of the emission cone (1 by default)
  56043. * @param angles the cone base angle (PI by default)
  56044. * @param directionRandomizer defines how much to randomize the particle direction [0-1] (default is 0)
  56045. */
  56046. function ConeParticleEmitter(radius, angle,
  56047. /** defines how much to randomize the particle direction [0-1] (default is 0) */
  56048. directionRandomizer) {
  56049. if (radius === void 0) { radius = 1; }
  56050. if (angle === void 0) { angle = Math.PI; }
  56051. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  56052. this.directionRandomizer = directionRandomizer;
  56053. this.angle = angle;
  56054. this.radius = radius;
  56055. }
  56056. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  56057. /**
  56058. * Gets or sets the radius of the emission cone
  56059. */
  56060. get: function () {
  56061. return this._radius;
  56062. },
  56063. set: function (value) {
  56064. this._radius = value;
  56065. this._buildHeight();
  56066. },
  56067. enumerable: true,
  56068. configurable: true
  56069. });
  56070. Object.defineProperty(ConeParticleEmitter.prototype, "angle", {
  56071. /**
  56072. * Gets or sets the angle of the emission cone
  56073. */
  56074. get: function () {
  56075. return this._angle;
  56076. },
  56077. set: function (value) {
  56078. this._angle = value;
  56079. this._buildHeight();
  56080. },
  56081. enumerable: true,
  56082. configurable: true
  56083. });
  56084. ConeParticleEmitter.prototype._buildHeight = function () {
  56085. if (this._angle !== 0) {
  56086. this._height = this._radius / Math.tan(this._angle / 2);
  56087. }
  56088. else {
  56089. this._height = 1;
  56090. }
  56091. };
  56092. /**
  56093. * Called by the particle System when the direction is computed for the created particle.
  56094. * @param emitPower is the power of the particle (speed)
  56095. * @param worldMatrix is the world matrix of the particle system
  56096. * @param directionToUpdate is the direction vector to update with the result
  56097. * @param particle is the particle we are computed the direction for
  56098. */
  56099. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  56100. if (this._angle === 0) {
  56101. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  56102. }
  56103. else {
  56104. // measure the direction Vector from the emitter to the particle.
  56105. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  56106. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56107. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56108. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56109. direction.x += randX;
  56110. direction.y += randY;
  56111. direction.z += randZ;
  56112. direction.normalize();
  56113. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  56114. }
  56115. };
  56116. /**
  56117. * Called by the particle System when the position is computed for the created particle.
  56118. * @param worldMatrix is the world matrix of the particle system
  56119. * @param positionToUpdate is the position vector to update with the result
  56120. * @param particle is the particle we are computed the position for
  56121. */
  56122. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56123. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  56124. var h = BABYLON.Scalar.RandomRange(0, 1);
  56125. // Better distribution in a cone at normal angles.
  56126. h = 1 - h * h;
  56127. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  56128. radius = radius * h;
  56129. var randX = radius * Math.sin(s);
  56130. var randZ = radius * Math.cos(s);
  56131. var randY = h * this._height;
  56132. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56133. };
  56134. /**
  56135. * Clones the current emitter and returns a copy of it
  56136. * @returns the new emitter
  56137. */
  56138. ConeParticleEmitter.prototype.clone = function () {
  56139. var newOne = new ConeParticleEmitter(this._radius, this._angle, this.directionRandomizer);
  56140. BABYLON.Tools.DeepCopy(this, newOne);
  56141. return newOne;
  56142. };
  56143. /**
  56144. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56145. * @param effect defines the update shader
  56146. */
  56147. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  56148. effect.setFloat("radius", this._radius);
  56149. effect.setFloat("coneAngle", this._angle);
  56150. effect.setFloat("height", this._height);
  56151. effect.setFloat("directionRandomizer", this.directionRandomizer);
  56152. };
  56153. /**
  56154. * Returns a string to use to update the GPU particles update shader
  56155. * @returns a string containng the defines string
  56156. */
  56157. ConeParticleEmitter.prototype.getEffectDefines = function () {
  56158. return "#define CONEEMITTER";
  56159. };
  56160. /**
  56161. * Returns the string "BoxEmitter"
  56162. * @returns a string containing the class name
  56163. */
  56164. ConeParticleEmitter.prototype.getClassName = function () {
  56165. return "ConeEmitter";
  56166. };
  56167. /**
  56168. * Serializes the particle system to a JSON object.
  56169. * @returns the JSON object
  56170. */
  56171. ConeParticleEmitter.prototype.serialize = function () {
  56172. var serializationObject = {};
  56173. serializationObject.type = this.getClassName();
  56174. serializationObject.radius = this._radius;
  56175. serializationObject.angle = this._angle;
  56176. serializationObject.directionRandomizer = this.directionRandomizer;
  56177. return serializationObject;
  56178. };
  56179. /**
  56180. * Parse properties from a JSON object
  56181. * @param serializationObject defines the JSON object
  56182. */
  56183. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  56184. this.radius = serializationObject.radius;
  56185. this.angle = serializationObject.angle;
  56186. this.directionRandomizer = serializationObject.directionRandomizer;
  56187. };
  56188. return ConeParticleEmitter;
  56189. }());
  56190. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  56191. })(BABYLON || (BABYLON = {}));
  56192. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  56193. var BABYLON;
  56194. (function (BABYLON) {
  56195. /**
  56196. * Particle emitter emitting particles from the inside of a sphere.
  56197. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  56198. */
  56199. var SphereParticleEmitter = /** @class */ (function () {
  56200. /**
  56201. * Creates a new instance SphereParticleEmitter
  56202. * @param radius the radius of the emission sphere (1 by default)
  56203. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  56204. */
  56205. function SphereParticleEmitter(
  56206. /**
  56207. * The radius of the emission sphere.
  56208. */
  56209. radius,
  56210. /**
  56211. * How much to randomize the particle direction [0-1].
  56212. */
  56213. directionRandomizer) {
  56214. if (radius === void 0) { radius = 1; }
  56215. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  56216. this.radius = radius;
  56217. this.directionRandomizer = directionRandomizer;
  56218. }
  56219. /**
  56220. * Called by the particle System when the direction is computed for the created particle.
  56221. * @param emitPower is the power of the particle (speed)
  56222. * @param worldMatrix is the world matrix of the particle system
  56223. * @param directionToUpdate is the direction vector to update with the result
  56224. * @param particle is the particle we are computed the direction for
  56225. */
  56226. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  56227. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  56228. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56229. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56230. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56231. direction.x += randX;
  56232. direction.y += randY;
  56233. direction.z += randZ;
  56234. direction.normalize();
  56235. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  56236. };
  56237. /**
  56238. * Called by the particle System when the position is computed for the created particle.
  56239. * @param worldMatrix is the world matrix of the particle system
  56240. * @param positionToUpdate is the position vector to update with the result
  56241. * @param particle is the particle we are computed the position for
  56242. */
  56243. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56244. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  56245. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  56246. var randRadius = BABYLON.Scalar.RandomRange(0, this.radius);
  56247. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  56248. var randY = randRadius * Math.cos(theta);
  56249. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  56250. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56251. };
  56252. /**
  56253. * Clones the current emitter and returns a copy of it
  56254. * @returns the new emitter
  56255. */
  56256. SphereParticleEmitter.prototype.clone = function () {
  56257. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  56258. BABYLON.Tools.DeepCopy(this, newOne);
  56259. return newOne;
  56260. };
  56261. /**
  56262. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56263. * @param effect defines the update shader
  56264. */
  56265. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  56266. effect.setFloat("radius", this.radius);
  56267. effect.setFloat("directionRandomizer", this.directionRandomizer);
  56268. };
  56269. /**
  56270. * Returns a string to use to update the GPU particles update shader
  56271. * @returns a string containng the defines string
  56272. */
  56273. SphereParticleEmitter.prototype.getEffectDefines = function () {
  56274. return "#define SPHEREEMITTER";
  56275. };
  56276. /**
  56277. * Returns the string "SphereParticleEmitter"
  56278. * @returns a string containing the class name
  56279. */
  56280. SphereParticleEmitter.prototype.getClassName = function () {
  56281. return "SphereParticleEmitter";
  56282. };
  56283. /**
  56284. * Serializes the particle system to a JSON object.
  56285. * @returns the JSON object
  56286. */
  56287. SphereParticleEmitter.prototype.serialize = function () {
  56288. var serializationObject = {};
  56289. serializationObject.type = this.getClassName();
  56290. serializationObject.radius = this.radius;
  56291. serializationObject.directionRandomizer = this.directionRandomizer;
  56292. return serializationObject;
  56293. };
  56294. /**
  56295. * Parse properties from a JSON object
  56296. * @param serializationObject defines the JSON object
  56297. */
  56298. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  56299. this.radius = serializationObject.radius;
  56300. this.directionRandomizer = serializationObject.directionRandomizer;
  56301. };
  56302. return SphereParticleEmitter;
  56303. }());
  56304. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  56305. /**
  56306. * Particle emitter emitting particles from the inside of a sphere.
  56307. * It emits the particles randomly between two vectors.
  56308. */
  56309. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  56310. __extends(SphereDirectedParticleEmitter, _super);
  56311. /**
  56312. * Creates a new instance SphereDirectedParticleEmitter
  56313. * @param radius the radius of the emission sphere (1 by default)
  56314. * @param direction1 the min limit of the emission direction (up vector by default)
  56315. * @param direction2 the max limit of the emission direction (up vector by default)
  56316. */
  56317. function SphereDirectedParticleEmitter(radius,
  56318. /**
  56319. * The min limit of the emission direction.
  56320. */
  56321. direction1,
  56322. /**
  56323. * The max limit of the emission direction.
  56324. */
  56325. direction2) {
  56326. if (radius === void 0) { radius = 1; }
  56327. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  56328. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  56329. var _this = _super.call(this, radius) || this;
  56330. _this.direction1 = direction1;
  56331. _this.direction2 = direction2;
  56332. return _this;
  56333. }
  56334. /**
  56335. * Called by the particle System when the direction is computed for the created particle.
  56336. * @param emitPower is the power of the particle (speed)
  56337. * @param worldMatrix is the world matrix of the particle system
  56338. * @param directionToUpdate is the direction vector to update with the result
  56339. * @param particle is the particle we are computed the direction for
  56340. */
  56341. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  56342. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  56343. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  56344. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  56345. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  56346. };
  56347. /**
  56348. * Clones the current emitter and returns a copy of it
  56349. * @returns the new emitter
  56350. */
  56351. SphereDirectedParticleEmitter.prototype.clone = function () {
  56352. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  56353. BABYLON.Tools.DeepCopy(this, newOne);
  56354. return newOne;
  56355. };
  56356. /**
  56357. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56358. * @param effect defines the update shader
  56359. */
  56360. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  56361. effect.setFloat("radius", this.radius);
  56362. effect.setVector3("direction1", this.direction1);
  56363. effect.setVector3("direction2", this.direction2);
  56364. };
  56365. /**
  56366. * Returns a string to use to update the GPU particles update shader
  56367. * @returns a string containng the defines string
  56368. */
  56369. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  56370. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  56371. };
  56372. /**
  56373. * Returns the string "SphereDirectedParticleEmitter"
  56374. * @returns a string containing the class name
  56375. */
  56376. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  56377. return "SphereDirectedParticleEmitter";
  56378. };
  56379. /**
  56380. * Serializes the particle system to a JSON object.
  56381. * @returns the JSON object
  56382. */
  56383. SphereDirectedParticleEmitter.prototype.serialize = function () {
  56384. var serializationObject = _super.prototype.serialize.call(this);
  56385. serializationObject.direction1 = this.direction1.asArray();
  56386. serializationObject.direction2 = this.direction2.asArray();
  56387. return serializationObject;
  56388. };
  56389. /**
  56390. * Parse properties from a JSON object
  56391. * @param serializationObject defines the JSON object
  56392. */
  56393. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  56394. _super.prototype.parse.call(this, serializationObject);
  56395. this.direction1.copyFrom(serializationObject.direction1);
  56396. this.direction2.copyFrom(serializationObject.direction2);
  56397. };
  56398. return SphereDirectedParticleEmitter;
  56399. }(SphereParticleEmitter));
  56400. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  56401. })(BABYLON || (BABYLON = {}));
  56402. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  56403. var __assign = (this && this.__assign) || Object.assign || function(t) {
  56404. for (var s, i = 1, n = arguments.length; i < n; i++) {
  56405. s = arguments[i];
  56406. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  56407. t[p] = s[p];
  56408. }
  56409. return t;
  56410. };
  56411. var BABYLON;
  56412. (function (BABYLON) {
  56413. /**
  56414. * This represents a GPU particle system in Babylon
  56415. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  56416. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  56417. */
  56418. var GPUParticleSystem = /** @class */ (function () {
  56419. /**
  56420. * Instantiates a GPU particle system.
  56421. * 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.
  56422. * @param name The name of the particle system
  56423. * @param capacity The max number of particles alive at the same time
  56424. * @param scene The scene the particle system belongs to
  56425. */
  56426. function GPUParticleSystem(name, options, scene) {
  56427. /**
  56428. * The emitter represents the Mesh or position we are attaching the particle system to.
  56429. */
  56430. this.emitter = null;
  56431. /**
  56432. * The rendering group used by the Particle system to chose when to render.
  56433. */
  56434. this.renderingGroupId = 0;
  56435. /**
  56436. * The layer mask we are rendering the particles through.
  56437. */
  56438. this.layerMask = 0x0FFFFFFF;
  56439. this._targetIndex = 0;
  56440. this._currentRenderId = -1;
  56441. this._started = false;
  56442. this._stopped = false;
  56443. this._timeDelta = 0;
  56444. this._attributesStrideSize = 18;
  56445. this._actualFrame = 0;
  56446. /**
  56447. * List of animations used by the particle system.
  56448. */
  56449. this.animations = [];
  56450. /**
  56451. * An event triggered when the system is disposed.
  56452. */
  56453. this.onDisposeObservable = new BABYLON.Observable();
  56454. /**
  56455. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  56456. */
  56457. this.updateSpeed = 0.01;
  56458. /**
  56459. * The amount of time the particle system is running (depends of the overall update speed).
  56460. */
  56461. this.targetStopDuration = 0;
  56462. /**
  56463. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  56464. */
  56465. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  56466. /**
  56467. * Minimum life time of emitting particles.
  56468. */
  56469. this.minLifeTime = 1;
  56470. /**
  56471. * Maximum life time of emitting particles.
  56472. */
  56473. this.maxLifeTime = 1;
  56474. /**
  56475. * Minimum Size of emitting particles.
  56476. */
  56477. this.minSize = 1;
  56478. /**
  56479. * Maximum Size of emitting particles.
  56480. */
  56481. this.maxSize = 1;
  56482. /**
  56483. * Minimum scale of emitting particles on X axis.
  56484. */
  56485. this.minScaleX = 1;
  56486. /**
  56487. * Maximum scale of emitting particles on X axis.
  56488. */
  56489. this.maxScaleX = 1;
  56490. /**
  56491. * Minimum scale of emitting particles on Y axis.
  56492. */
  56493. this.minScaleY = 1;
  56494. /**
  56495. * Maximum scale of emitting particles on Y axis.
  56496. */
  56497. this.maxScaleY = 1;
  56498. /**
  56499. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  56500. */
  56501. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56502. /**
  56503. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  56504. */
  56505. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56506. /**
  56507. * Color the particle will have at the end of its lifetime.
  56508. */
  56509. this.colorDead = new BABYLON.Color4(0, 0, 0, 0);
  56510. /**
  56511. * The maximum number of particles to emit per frame until we reach the activeParticleCount value
  56512. */
  56513. this.emitRate = 100;
  56514. /**
  56515. * You can use gravity if you want to give an orientation to your particles.
  56516. */
  56517. this.gravity = BABYLON.Vector3.Zero();
  56518. /**
  56519. * Minimum power of emitting particles.
  56520. */
  56521. this.minEmitPower = 1;
  56522. /**
  56523. * Maximum power of emitting particles.
  56524. */
  56525. this.maxEmitPower = 1;
  56526. /**
  56527. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  56528. */
  56529. this.minAngularSpeed = 0;
  56530. /**
  56531. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  56532. */
  56533. this.maxAngularSpeed = 0;
  56534. /**
  56535. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  56536. * to override the particles.
  56537. */
  56538. this.forceDepthWrite = false;
  56539. this.id = name;
  56540. this.name = name;
  56541. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  56542. this._engine = this._scene.getEngine();
  56543. var fullOptions = __assign({ capacity: 50000, randomTextureSize: this._engine.getCaps().maxTextureSize }, options);
  56544. this._capacity = fullOptions.capacity;
  56545. this._activeCount = fullOptions.capacity;
  56546. this._currentActiveCount = 0;
  56547. this._scene.particleSystems.push(this);
  56548. this._updateEffectOptions = {
  56549. attributes: ["position", "age", "life", "seed", "size", "color", "direction", "angle"],
  56550. uniformsNames: ["currentCount", "timeDelta", "generalRandoms", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "scaleRange", "gravity", "emitPower",
  56551. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "coneAngle", "stopFactor",
  56552. "angleRange"],
  56553. uniformBuffersNames: [],
  56554. samplers: ["randomSampler"],
  56555. defines: "",
  56556. fallbacks: null,
  56557. onCompiled: null,
  56558. onError: null,
  56559. indexParameters: null,
  56560. maxSimultaneousLights: 0,
  56561. transformFeedbackVaryings: ["outPosition", "outAge", "outLife", "outSeed", "outSize", "outColor", "outDirection", "outAngle"]
  56562. };
  56563. // Random data
  56564. var maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  56565. var d = [];
  56566. for (var i = 0; i < maxTextureSize; ++i) {
  56567. d.push(Math.random());
  56568. d.push(Math.random());
  56569. d.push(Math.random());
  56570. d.push(Math.random());
  56571. }
  56572. 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);
  56573. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  56574. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  56575. this._randomTextureSize = maxTextureSize;
  56576. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  56577. }
  56578. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  56579. /**
  56580. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  56581. */
  56582. get: function () {
  56583. if (!BABYLON.Engine.LastCreatedEngine) {
  56584. return false;
  56585. }
  56586. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  56587. },
  56588. enumerable: true,
  56589. configurable: true
  56590. });
  56591. Object.defineProperty(GPUParticleSystem.prototype, "direction1", {
  56592. /**
  56593. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56594. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56595. */
  56596. get: function () {
  56597. if (this.particleEmitterType.direction1) {
  56598. return this.particleEmitterType.direction1;
  56599. }
  56600. return BABYLON.Vector3.Zero();
  56601. },
  56602. set: function (value) {
  56603. if (this.particleEmitterType.direction1) {
  56604. this.particleEmitterType.direction1 = value;
  56605. }
  56606. },
  56607. enumerable: true,
  56608. configurable: true
  56609. });
  56610. Object.defineProperty(GPUParticleSystem.prototype, "direction2", {
  56611. /**
  56612. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56613. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56614. */
  56615. get: function () {
  56616. if (this.particleEmitterType.direction2) {
  56617. return this.particleEmitterType.direction2;
  56618. }
  56619. return BABYLON.Vector3.Zero();
  56620. },
  56621. set: function (value) {
  56622. if (this.particleEmitterType.direction2) {
  56623. this.particleEmitterType.direction2 = value;
  56624. }
  56625. },
  56626. enumerable: true,
  56627. configurable: true
  56628. });
  56629. Object.defineProperty(GPUParticleSystem.prototype, "minEmitBox", {
  56630. /**
  56631. * 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.
  56632. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56633. */
  56634. get: function () {
  56635. if (this.particleEmitterType.minEmitBox) {
  56636. return this.particleEmitterType.minEmitBox;
  56637. }
  56638. return BABYLON.Vector3.Zero();
  56639. },
  56640. set: function (value) {
  56641. if (this.particleEmitterType.minEmitBox) {
  56642. this.particleEmitterType.minEmitBox = value;
  56643. }
  56644. },
  56645. enumerable: true,
  56646. configurable: true
  56647. });
  56648. Object.defineProperty(GPUParticleSystem.prototype, "maxEmitBox", {
  56649. /**
  56650. * 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.
  56651. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56652. */
  56653. get: function () {
  56654. if (this.particleEmitterType.maxEmitBox) {
  56655. return this.particleEmitterType.maxEmitBox;
  56656. }
  56657. return BABYLON.Vector3.Zero();
  56658. },
  56659. set: function (value) {
  56660. if (this.particleEmitterType.maxEmitBox) {
  56661. this.particleEmitterType.maxEmitBox = value;
  56662. }
  56663. },
  56664. enumerable: true,
  56665. configurable: true
  56666. });
  56667. /**
  56668. * Gets the maximum number of particles active at the same time.
  56669. * @returns The max number of active particles.
  56670. */
  56671. GPUParticleSystem.prototype.getCapacity = function () {
  56672. return this._capacity;
  56673. };
  56674. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  56675. /**
  56676. * Gets or set the number of active particles
  56677. */
  56678. get: function () {
  56679. return this._activeCount;
  56680. },
  56681. set: function (value) {
  56682. this._activeCount = Math.min(value, this._capacity);
  56683. },
  56684. enumerable: true,
  56685. configurable: true
  56686. });
  56687. /**
  56688. * Is this system ready to be used/rendered
  56689. * @return true if the system is ready
  56690. */
  56691. GPUParticleSystem.prototype.isReady = function () {
  56692. if (!this._updateEffect) {
  56693. this._recreateUpdateEffect();
  56694. this._recreateRenderEffect();
  56695. return false;
  56696. }
  56697. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  56698. return false;
  56699. }
  56700. return true;
  56701. };
  56702. /**
  56703. * Gets Wether the system has been started.
  56704. * @returns True if it has been started, otherwise false.
  56705. */
  56706. GPUParticleSystem.prototype.isStarted = function () {
  56707. return this._started;
  56708. };
  56709. /**
  56710. * Starts the particle system and begins to emit.
  56711. */
  56712. GPUParticleSystem.prototype.start = function () {
  56713. this._started = true;
  56714. this._stopped = false;
  56715. };
  56716. /**
  56717. * Stops the particle system.
  56718. */
  56719. GPUParticleSystem.prototype.stop = function () {
  56720. this._stopped = true;
  56721. };
  56722. /**
  56723. * Remove all active particles
  56724. */
  56725. GPUParticleSystem.prototype.reset = function () {
  56726. this._releaseBuffers();
  56727. this._releaseVAOs();
  56728. this._currentActiveCount = 0;
  56729. this._targetIndex = 0;
  56730. };
  56731. /**
  56732. * Returns the string "GPUParticleSystem"
  56733. * @returns a string containing the class name
  56734. */
  56735. GPUParticleSystem.prototype.getClassName = function () {
  56736. return "GPUParticleSystem";
  56737. };
  56738. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  56739. var updateVertexBuffers = {};
  56740. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  56741. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  56742. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  56743. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 1);
  56744. updateVertexBuffers["size"] = source.createVertexBuffer("size", 6, 3);
  56745. updateVertexBuffers["color"] = source.createVertexBuffer("color", 9, 4);
  56746. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", 13, 3);
  56747. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", 16, 2);
  56748. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  56749. this._engine.bindArrayBuffer(null);
  56750. return vao;
  56751. };
  56752. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  56753. var renderVertexBuffers = {};
  56754. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  56755. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  56756. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  56757. renderVertexBuffers["size"] = source.createVertexBuffer("size", 6, 3, this._attributesStrideSize, true);
  56758. renderVertexBuffers["color"] = source.createVertexBuffer("color", 9, 4, this._attributesStrideSize, true);
  56759. renderVertexBuffers["angle"] = source.createVertexBuffer("angle", 16, 2, this._attributesStrideSize, true);
  56760. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  56761. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  56762. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  56763. this._engine.bindArrayBuffer(null);
  56764. return vao;
  56765. };
  56766. GPUParticleSystem.prototype._initialize = function (force) {
  56767. if (force === void 0) { force = false; }
  56768. if (this._buffer0 && !force) {
  56769. return;
  56770. }
  56771. var engine = this._scene.getEngine();
  56772. var data = new Array();
  56773. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  56774. // position
  56775. data.push(0.0);
  56776. data.push(0.0);
  56777. data.push(0.0);
  56778. // Age and life
  56779. data.push(0.0); // create the particle as a dead one to create a new one at start
  56780. data.push(0.0);
  56781. // Seed
  56782. data.push(Math.random());
  56783. // Size
  56784. data.push(0.0);
  56785. data.push(0.0);
  56786. data.push(0.0);
  56787. // color
  56788. data.push(0.0);
  56789. data.push(0.0);
  56790. data.push(0.0);
  56791. data.push(0.0);
  56792. // direction
  56793. data.push(0.0);
  56794. data.push(0.0);
  56795. data.push(0.0);
  56796. // angle
  56797. data.push(0.0);
  56798. data.push(0.0);
  56799. }
  56800. // Sprite data
  56801. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  56802. -0.5, 0.5, 0, 1,
  56803. -0.5, -0.5, 0, 0,
  56804. 0.5, -0.5, 1, 0]);
  56805. // Buffers
  56806. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  56807. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  56808. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  56809. // Update VAO
  56810. this._updateVAO = [];
  56811. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  56812. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  56813. // Render VAO
  56814. this._renderVAO = [];
  56815. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  56816. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  56817. // Links
  56818. this._sourceBuffer = this._buffer0;
  56819. this._targetBuffer = this._buffer1;
  56820. };
  56821. /** @hidden */
  56822. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  56823. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  56824. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  56825. return;
  56826. }
  56827. this._updateEffectOptions.defines = defines;
  56828. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  56829. };
  56830. /** @hidden */
  56831. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  56832. var defines = "";
  56833. if (this._scene.clipPlane) {
  56834. defines = "\n#define CLIPPLANE";
  56835. }
  56836. if (this._renderEffect && this._renderEffect.defines === defines) {
  56837. return;
  56838. }
  56839. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv", "angle"], ["view", "projection", "colorDead", "invView", "vClipPlane"], ["textureSampler"], this._scene.getEngine(), defines);
  56840. };
  56841. /**
  56842. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  56843. */
  56844. GPUParticleSystem.prototype.animate = function () {
  56845. this._timeDelta = this.updateSpeed * this._scene.getAnimationRatio();
  56846. this._actualFrame += this._timeDelta;
  56847. if (!this._stopped) {
  56848. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  56849. this.stop();
  56850. }
  56851. }
  56852. };
  56853. /**
  56854. * Renders the particle system in its current state.
  56855. * @returns the current number of particles
  56856. */
  56857. GPUParticleSystem.prototype.render = function () {
  56858. if (!this._started) {
  56859. return 0;
  56860. }
  56861. this._recreateUpdateEffect();
  56862. this._recreateRenderEffect();
  56863. if (!this.isReady()) {
  56864. return 0;
  56865. }
  56866. if (this._currentRenderId === this._scene.getRenderId()) {
  56867. return 0;
  56868. }
  56869. this._currentRenderId = this._scene.getRenderId();
  56870. // Get everything ready to render
  56871. this._initialize();
  56872. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + (this.emitRate * this._timeDelta) | 0);
  56873. // Enable update effect
  56874. this._engine.enableEffect(this._updateEffect);
  56875. this._engine.setState(false);
  56876. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  56877. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  56878. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  56879. this._updateEffect.setFloat3("generalRandoms", Math.random(), Math.random(), Math.random());
  56880. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  56881. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  56882. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  56883. this._updateEffect.setDirectColor4("color1", this.color1);
  56884. this._updateEffect.setDirectColor4("color2", this.color2);
  56885. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  56886. this._updateEffect.setFloat4("scaleRange", this.minScaleX, this.maxScaleX, this.minScaleY, this.maxScaleY);
  56887. this._updateEffect.setFloat2("angleRange", this.minAngularSpeed, this.maxAngularSpeed);
  56888. this._updateEffect.setVector3("gravity", this.gravity);
  56889. if (this.particleEmitterType) {
  56890. this.particleEmitterType.applyToShader(this._updateEffect);
  56891. }
  56892. var emitterWM;
  56893. if (this.emitter.position) {
  56894. var emitterMesh = this.emitter;
  56895. emitterWM = emitterMesh.getWorldMatrix();
  56896. }
  56897. else {
  56898. var emitterPosition = this.emitter;
  56899. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  56900. }
  56901. this._updateEffect.setMatrix("emitterWM", emitterWM);
  56902. // Bind source VAO
  56903. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  56904. // Update
  56905. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  56906. this._engine.setRasterizerState(false);
  56907. this._engine.beginTransformFeedback();
  56908. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  56909. this._engine.endTransformFeedback();
  56910. this._engine.setRasterizerState(true);
  56911. this._engine.bindTransformFeedbackBuffer(null);
  56912. // Enable render effect
  56913. this._engine.enableEffect(this._renderEffect);
  56914. var viewMatrix = this._scene.getViewMatrix();
  56915. this._renderEffect.setMatrix("view", viewMatrix);
  56916. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  56917. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  56918. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  56919. if (this._scene.clipPlane) {
  56920. var clipPlane = this._scene.clipPlane;
  56921. var invView = viewMatrix.clone();
  56922. invView.invert();
  56923. this._renderEffect.setMatrix("invView", invView);
  56924. this._renderEffect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  56925. }
  56926. // Draw order
  56927. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_ONEONE) {
  56928. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  56929. }
  56930. else {
  56931. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  56932. }
  56933. if (this.forceDepthWrite) {
  56934. this._engine.setDepthWrite(true);
  56935. }
  56936. // Bind source VAO
  56937. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  56938. // Render
  56939. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  56940. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  56941. // Switch VAOs
  56942. this._targetIndex++;
  56943. if (this._targetIndex === 2) {
  56944. this._targetIndex = 0;
  56945. }
  56946. // Switch buffers
  56947. var tmpBuffer = this._sourceBuffer;
  56948. this._sourceBuffer = this._targetBuffer;
  56949. this._targetBuffer = tmpBuffer;
  56950. return this._currentActiveCount;
  56951. };
  56952. /**
  56953. * Rebuilds the particle system
  56954. */
  56955. GPUParticleSystem.prototype.rebuild = function () {
  56956. this._initialize(true);
  56957. };
  56958. GPUParticleSystem.prototype._releaseBuffers = function () {
  56959. if (this._buffer0) {
  56960. this._buffer0.dispose();
  56961. this._buffer0 = null;
  56962. }
  56963. if (this._buffer1) {
  56964. this._buffer1.dispose();
  56965. this._buffer1 = null;
  56966. }
  56967. if (this._spriteBuffer) {
  56968. this._spriteBuffer.dispose();
  56969. this._spriteBuffer = null;
  56970. }
  56971. };
  56972. GPUParticleSystem.prototype._releaseVAOs = function () {
  56973. if (!this._updateVAO) {
  56974. return;
  56975. }
  56976. for (var index = 0; index < this._updateVAO.length; index++) {
  56977. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  56978. }
  56979. this._updateVAO = [];
  56980. for (var index = 0; index < this._renderVAO.length; index++) {
  56981. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  56982. }
  56983. this._renderVAO = [];
  56984. };
  56985. /**
  56986. * Disposes the particle system and free the associated resources
  56987. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  56988. */
  56989. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  56990. if (disposeTexture === void 0) { disposeTexture = true; }
  56991. var index = this._scene.particleSystems.indexOf(this);
  56992. if (index > -1) {
  56993. this._scene.particleSystems.splice(index, 1);
  56994. }
  56995. this._releaseBuffers();
  56996. this._releaseVAOs();
  56997. if (this._randomTexture) {
  56998. this._randomTexture.dispose();
  56999. this._randomTexture = null;
  57000. }
  57001. if (disposeTexture && this.particleTexture) {
  57002. this.particleTexture.dispose();
  57003. this.particleTexture = null;
  57004. }
  57005. // Callback
  57006. this.onDisposeObservable.notifyObservers(this);
  57007. this.onDisposeObservable.clear();
  57008. };
  57009. /**
  57010. * Clones the particle system.
  57011. * @param name The name of the cloned object
  57012. * @param newEmitter The new emitter to use
  57013. * @returns the cloned particle system
  57014. */
  57015. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  57016. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  57017. BABYLON.Tools.DeepCopy(this, result);
  57018. if (newEmitter === undefined) {
  57019. newEmitter = this.emitter;
  57020. }
  57021. result.emitter = newEmitter;
  57022. if (this.particleTexture) {
  57023. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  57024. }
  57025. return result;
  57026. };
  57027. /**
  57028. * Serializes the particle system to a JSON object.
  57029. * @returns the JSON object
  57030. */
  57031. GPUParticleSystem.prototype.serialize = function () {
  57032. var serializationObject = {};
  57033. serializationObject.name = this.name;
  57034. serializationObject.id = this.id;
  57035. // Emitter
  57036. if (this.emitter.position) {
  57037. var emitterMesh = this.emitter;
  57038. serializationObject.emitterId = emitterMesh.id;
  57039. }
  57040. else {
  57041. var emitterPosition = this.emitter;
  57042. serializationObject.emitter = emitterPosition.asArray();
  57043. }
  57044. serializationObject.capacity = this.getCapacity();
  57045. if (this.particleTexture) {
  57046. serializationObject.textureName = this.particleTexture.name;
  57047. }
  57048. // Animations
  57049. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  57050. // Particle system
  57051. serializationObject.activeParticleCount = this.activeParticleCount;
  57052. serializationObject.randomTextureSize = this._randomTextureSize;
  57053. serializationObject.minSize = this.minSize;
  57054. serializationObject.maxSize = this.maxSize;
  57055. serializationObject.minEmitPower = this.minEmitPower;
  57056. serializationObject.maxEmitPower = this.maxEmitPower;
  57057. serializationObject.minLifeTime = this.minLifeTime;
  57058. serializationObject.maxLifeTime = this.maxLifeTime;
  57059. serializationObject.minAngularSpeed = this.minAngularSpeed;
  57060. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  57061. serializationObject.emitRate = this.emitRate;
  57062. serializationObject.gravity = this.gravity.asArray();
  57063. serializationObject.color1 = this.color1.asArray();
  57064. serializationObject.color2 = this.color2.asArray();
  57065. serializationObject.colorDead = this.colorDead.asArray();
  57066. serializationObject.updateSpeed = this.updateSpeed;
  57067. serializationObject.targetStopDuration = this.targetStopDuration;
  57068. serializationObject.blendMode = this.blendMode;
  57069. // Emitter
  57070. if (this.particleEmitterType) {
  57071. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  57072. }
  57073. return serializationObject;
  57074. };
  57075. /**
  57076. * Parses a JSON object to create a GPU particle system.
  57077. * @param parsedParticleSystem The JSON object to parse
  57078. * @param scene The scene to create the particle system in
  57079. * @param rootUrl The root url to use to load external dependencies like texture
  57080. * @returns the parsed GPU particle system
  57081. */
  57082. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  57083. var name = parsedParticleSystem.name;
  57084. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  57085. if (parsedParticleSystem.id) {
  57086. particleSystem.id = parsedParticleSystem.id;
  57087. }
  57088. // Texture
  57089. if (parsedParticleSystem.textureName) {
  57090. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  57091. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  57092. }
  57093. // Emitter
  57094. if (parsedParticleSystem.emitterId) {
  57095. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  57096. }
  57097. else {
  57098. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  57099. }
  57100. // Animations
  57101. if (parsedParticleSystem.animations) {
  57102. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  57103. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  57104. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  57105. }
  57106. }
  57107. // Particle system
  57108. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  57109. particleSystem.minSize = parsedParticleSystem.minSize;
  57110. particleSystem.maxSize = parsedParticleSystem.maxSize;
  57111. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  57112. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  57113. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  57114. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  57115. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  57116. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  57117. particleSystem.emitRate = parsedParticleSystem.emitRate;
  57118. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  57119. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  57120. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  57121. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  57122. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  57123. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  57124. particleSystem.blendMode = parsedParticleSystem.blendMode;
  57125. // Emitter
  57126. if (parsedParticleSystem.particleEmitterType) {
  57127. var emitterType = void 0;
  57128. switch (parsedParticleSystem.particleEmitterType.type) {
  57129. case "SphereEmitter":
  57130. emitterType = new BABYLON.SphereParticleEmitter();
  57131. break;
  57132. case "SphereDirectedParticleEmitter":
  57133. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  57134. break;
  57135. case "ConeEmitter":
  57136. emitterType = new BABYLON.ConeParticleEmitter();
  57137. break;
  57138. case "BoxEmitter":
  57139. default:
  57140. emitterType = new BABYLON.BoxParticleEmitter();
  57141. break;
  57142. }
  57143. emitterType.parse(parsedParticleSystem.particleEmitterType);
  57144. particleSystem.particleEmitterType = emitterType;
  57145. }
  57146. return particleSystem;
  57147. };
  57148. return GPUParticleSystem;
  57149. }());
  57150. BABYLON.GPUParticleSystem = GPUParticleSystem;
  57151. })(BABYLON || (BABYLON = {}));
  57152. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  57153. var BABYLON;
  57154. (function (BABYLON) {
  57155. /**
  57156. * Represents one particle of a solid particle system.
  57157. */
  57158. var SolidParticle = /** @class */ (function () {
  57159. /**
  57160. * Creates a Solid Particle object.
  57161. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  57162. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  57163. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  57164. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  57165. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  57166. * @param shapeId (integer) is the model shape identifier in the SPS.
  57167. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  57168. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  57169. */
  57170. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  57171. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  57172. /**
  57173. * particle global index
  57174. */
  57175. this.idx = 0;
  57176. /**
  57177. * The color of the particle
  57178. */
  57179. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57180. /**
  57181. * The world space position of the particle.
  57182. */
  57183. this.position = BABYLON.Vector3.Zero();
  57184. /**
  57185. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  57186. */
  57187. this.rotation = BABYLON.Vector3.Zero();
  57188. /**
  57189. * The scaling of the particle.
  57190. */
  57191. this.scaling = BABYLON.Vector3.One();
  57192. /**
  57193. * The uvs of the particle.
  57194. */
  57195. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  57196. /**
  57197. * The current speed of the particle.
  57198. */
  57199. this.velocity = BABYLON.Vector3.Zero();
  57200. /**
  57201. * The pivot point in the particle local space.
  57202. */
  57203. this.pivot = BABYLON.Vector3.Zero();
  57204. /**
  57205. * Must the particle be translated from its pivot point in its local space ?
  57206. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  57207. * Default : false
  57208. */
  57209. this.translateFromPivot = false;
  57210. /**
  57211. * Is the particle active or not ?
  57212. */
  57213. this.alive = true;
  57214. /**
  57215. * Is the particle visible or not ?
  57216. */
  57217. this.isVisible = true;
  57218. /**
  57219. * Index of this particle in the global "positions" array (Internal use)
  57220. */
  57221. this._pos = 0;
  57222. /**
  57223. * Index of this particle in the global "indices" array (Internal use)
  57224. */
  57225. this._ind = 0;
  57226. /**
  57227. * ModelShape id of this particle
  57228. */
  57229. this.shapeId = 0;
  57230. /**
  57231. * Index of the particle in its shape id (Internal use)
  57232. */
  57233. this.idxInShape = 0;
  57234. /**
  57235. * Still set as invisible in order to skip useless computations (Internal use)
  57236. */
  57237. this._stillInvisible = false;
  57238. /**
  57239. * Last computed particle rotation matrix
  57240. */
  57241. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  57242. /**
  57243. * Parent particle Id, if any.
  57244. * Default null.
  57245. */
  57246. this.parentId = null;
  57247. /**
  57248. * Internal global position in the SPS.
  57249. */
  57250. this._globalPosition = BABYLON.Vector3.Zero();
  57251. this.idx = particleIndex;
  57252. this._pos = positionIndex;
  57253. this._ind = indiceIndex;
  57254. this._model = model;
  57255. this.shapeId = shapeId;
  57256. this.idxInShape = idxInShape;
  57257. this._sps = sps;
  57258. if (modelBoundingInfo) {
  57259. this._modelBoundingInfo = modelBoundingInfo;
  57260. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  57261. }
  57262. }
  57263. Object.defineProperty(SolidParticle.prototype, "scale", {
  57264. /**
  57265. * Legacy support, changed scale to scaling
  57266. */
  57267. get: function () {
  57268. return this.scaling;
  57269. },
  57270. /**
  57271. * Legacy support, changed scale to scaling
  57272. */
  57273. set: function (scale) {
  57274. this.scaling = scale;
  57275. },
  57276. enumerable: true,
  57277. configurable: true
  57278. });
  57279. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  57280. /**
  57281. * Legacy support, changed quaternion to rotationQuaternion
  57282. */
  57283. get: function () {
  57284. return this.rotationQuaternion;
  57285. },
  57286. /**
  57287. * Legacy support, changed quaternion to rotationQuaternion
  57288. */
  57289. set: function (q) {
  57290. this.rotationQuaternion = q;
  57291. },
  57292. enumerable: true,
  57293. configurable: true
  57294. });
  57295. /**
  57296. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  57297. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  57298. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  57299. * @returns true if it intersects
  57300. */
  57301. SolidParticle.prototype.intersectsMesh = function (target) {
  57302. if (!this._boundingInfo || !target._boundingInfo) {
  57303. return false;
  57304. }
  57305. if (this._sps._bSphereOnly) {
  57306. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  57307. }
  57308. return this._boundingInfo.intersects(target._boundingInfo, false);
  57309. };
  57310. return SolidParticle;
  57311. }());
  57312. BABYLON.SolidParticle = SolidParticle;
  57313. /**
  57314. * Represents the shape of the model used by one particle of a solid particle system.
  57315. * SPS internal tool, don't use it manually.
  57316. */
  57317. var ModelShape = /** @class */ (function () {
  57318. /**
  57319. * 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.
  57320. * SPS internal tool, don't use it manually.
  57321. * @hidden
  57322. */
  57323. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  57324. /**
  57325. * length of the shape in the model indices array (internal use)
  57326. */
  57327. this._indicesLength = 0;
  57328. this.shapeID = id;
  57329. this._shape = shape;
  57330. this._indicesLength = indicesLength;
  57331. this._shapeUV = shapeUV;
  57332. this._positionFunction = posFunction;
  57333. this._vertexFunction = vtxFunction;
  57334. }
  57335. return ModelShape;
  57336. }());
  57337. BABYLON.ModelShape = ModelShape;
  57338. /**
  57339. * Represents a Depth Sorted Particle in the solid particle system.
  57340. */
  57341. var DepthSortedParticle = /** @class */ (function () {
  57342. function DepthSortedParticle() {
  57343. /**
  57344. * Index of the particle in the "indices" array
  57345. */
  57346. this.ind = 0;
  57347. /**
  57348. * Length of the particle shape in the "indices" array
  57349. */
  57350. this.indicesLength = 0;
  57351. /**
  57352. * Squared distance from the particle to the camera
  57353. */
  57354. this.sqDistance = 0.0;
  57355. }
  57356. return DepthSortedParticle;
  57357. }());
  57358. BABYLON.DepthSortedParticle = DepthSortedParticle;
  57359. })(BABYLON || (BABYLON = {}));
  57360. //# sourceMappingURL=babylon.solidParticle.js.map
  57361. var BABYLON;
  57362. (function (BABYLON) {
  57363. /**
  57364. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  57365. *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.
  57366. * The SPS is also a particle system. It provides some methods to manage the particles.
  57367. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  57368. *
  57369. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  57370. */
  57371. var SolidParticleSystem = /** @class */ (function () {
  57372. /**
  57373. * Creates a SPS (Solid Particle System) object.
  57374. * @param name (String) is the SPS name, this will be the underlying mesh name.
  57375. * @param scene (Scene) is the scene in which the SPS is added.
  57376. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  57377. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  57378. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  57379. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  57380. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  57381. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  57382. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  57383. */
  57384. function SolidParticleSystem(name, scene, options) {
  57385. /**
  57386. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  57387. * Example : var p = SPS.particles[i];
  57388. */
  57389. this.particles = new Array();
  57390. /**
  57391. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  57392. */
  57393. this.nbParticles = 0;
  57394. /**
  57395. * If the particles must ever face the camera (default false). Useful for planar particles.
  57396. */
  57397. this.billboard = false;
  57398. /**
  57399. * Recompute normals when adding a shape
  57400. */
  57401. this.recomputeNormals = true;
  57402. /**
  57403. * This a counter ofr your own usage. It's not set by any SPS functions.
  57404. */
  57405. this.counter = 0;
  57406. /**
  57407. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  57408. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  57409. */
  57410. this.vars = {};
  57411. /**
  57412. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  57413. */
  57414. this._bSphereOnly = false;
  57415. /**
  57416. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  57417. */
  57418. this._bSphereRadiusFactor = 1.0;
  57419. this._positions = new Array();
  57420. this._indices = new Array();
  57421. this._normals = new Array();
  57422. this._colors = new Array();
  57423. this._uvs = new Array();
  57424. this._index = 0; // indices index
  57425. this._updatable = true;
  57426. this._pickable = false;
  57427. this._isVisibilityBoxLocked = false;
  57428. this._alwaysVisible = false;
  57429. this._depthSort = false;
  57430. this._shapeCounter = 0;
  57431. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  57432. this._color = new BABYLON.Color4(0, 0, 0, 0);
  57433. this._computeParticleColor = true;
  57434. this._computeParticleTexture = true;
  57435. this._computeParticleRotation = true;
  57436. this._computeParticleVertex = false;
  57437. this._computeBoundingBox = false;
  57438. this._depthSortParticles = true;
  57439. this._cam_axisZ = BABYLON.Vector3.Zero();
  57440. this._cam_axisY = BABYLON.Vector3.Zero();
  57441. this._cam_axisX = BABYLON.Vector3.Zero();
  57442. this._axisZ = BABYLON.Axis.Z;
  57443. this._camDir = BABYLON.Vector3.Zero();
  57444. this._camInvertedPosition = BABYLON.Vector3.Zero();
  57445. this._rotMatrix = new BABYLON.Matrix();
  57446. this._invertMatrix = new BABYLON.Matrix();
  57447. this._rotated = BABYLON.Vector3.Zero();
  57448. this._quaternion = new BABYLON.Quaternion();
  57449. this._vertex = BABYLON.Vector3.Zero();
  57450. this._normal = BABYLON.Vector3.Zero();
  57451. this._yaw = 0.0;
  57452. this._pitch = 0.0;
  57453. this._roll = 0.0;
  57454. this._halfroll = 0.0;
  57455. this._halfpitch = 0.0;
  57456. this._halfyaw = 0.0;
  57457. this._sinRoll = 0.0;
  57458. this._cosRoll = 0.0;
  57459. this._sinPitch = 0.0;
  57460. this._cosPitch = 0.0;
  57461. this._sinYaw = 0.0;
  57462. this._cosYaw = 0.0;
  57463. this._mustUnrotateFixedNormals = false;
  57464. this._minimum = BABYLON.Vector3.Zero();
  57465. this._maximum = BABYLON.Vector3.Zero();
  57466. this._minBbox = BABYLON.Vector3.Zero();
  57467. this._maxBbox = BABYLON.Vector3.Zero();
  57468. this._particlesIntersect = false;
  57469. this._depthSortFunction = function (p1, p2) {
  57470. return (p2.sqDistance - p1.sqDistance);
  57471. };
  57472. this._needs32Bits = false;
  57473. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  57474. this._scaledPivot = BABYLON.Vector3.Zero();
  57475. this._particleHasParent = false;
  57476. this.name = name;
  57477. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  57478. this._camera = scene.activeCamera;
  57479. this._pickable = options ? options.isPickable : false;
  57480. this._depthSort = options ? options.enableDepthSort : false;
  57481. this._particlesIntersect = options ? options.particleIntersection : false;
  57482. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  57483. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  57484. if (options && options.updatable !== undefined) {
  57485. this._updatable = options.updatable;
  57486. }
  57487. else {
  57488. this._updatable = true;
  57489. }
  57490. if (this._pickable) {
  57491. this.pickedParticles = [];
  57492. }
  57493. if (this._depthSort) {
  57494. this.depthSortedParticles = [];
  57495. }
  57496. }
  57497. /**
  57498. * Builds the SPS underlying mesh. Returns a standard Mesh.
  57499. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  57500. * @returns the created mesh
  57501. */
  57502. SolidParticleSystem.prototype.buildMesh = function () {
  57503. if (this.nbParticles === 0) {
  57504. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  57505. this.addShape(triangle, 1);
  57506. triangle.dispose();
  57507. }
  57508. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  57509. this._positions32 = new Float32Array(this._positions);
  57510. this._uvs32 = new Float32Array(this._uvs);
  57511. this._colors32 = new Float32Array(this._colors);
  57512. if (this.recomputeNormals) {
  57513. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  57514. }
  57515. this._normals32 = new Float32Array(this._normals);
  57516. this._fixedNormal32 = new Float32Array(this._normals);
  57517. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  57518. this._unrotateFixedNormals();
  57519. }
  57520. var vertexData = new BABYLON.VertexData();
  57521. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  57522. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  57523. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  57524. if (this._uvs32.length > 0) {
  57525. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  57526. }
  57527. if (this._colors32.length > 0) {
  57528. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  57529. }
  57530. var mesh = new BABYLON.Mesh(this.name, this._scene);
  57531. vertexData.applyToMesh(mesh, this._updatable);
  57532. this.mesh = mesh;
  57533. this.mesh.isPickable = this._pickable;
  57534. // free memory
  57535. if (!this._depthSort) {
  57536. this._indices = null;
  57537. }
  57538. this._positions = null;
  57539. this._normals = null;
  57540. this._uvs = null;
  57541. this._colors = null;
  57542. if (!this._updatable) {
  57543. this.particles.length = 0;
  57544. }
  57545. return mesh;
  57546. };
  57547. /**
  57548. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  57549. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  57550. * Thus the particles generated from `digest()` have their property `position` set yet.
  57551. * @param mesh ( Mesh ) is the mesh to be digested
  57552. * @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
  57553. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  57554. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  57555. * @returns the current SPS
  57556. */
  57557. SolidParticleSystem.prototype.digest = function (mesh, options) {
  57558. var size = (options && options.facetNb) || 1;
  57559. var number = (options && options.number) || 0;
  57560. var delta = (options && options.delta) || 0;
  57561. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  57562. var meshInd = mesh.getIndices();
  57563. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  57564. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  57565. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  57566. var f = 0; // facet counter
  57567. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  57568. // compute size from number
  57569. if (number) {
  57570. number = (number > totalFacets) ? totalFacets : number;
  57571. size = Math.round(totalFacets / number);
  57572. delta = 0;
  57573. }
  57574. else {
  57575. size = (size > totalFacets) ? totalFacets : size;
  57576. }
  57577. var facetPos = []; // submesh positions
  57578. var facetInd = []; // submesh indices
  57579. var facetUV = []; // submesh UV
  57580. var facetCol = []; // submesh colors
  57581. var barycenter = BABYLON.Vector3.Zero();
  57582. var sizeO = size;
  57583. while (f < totalFacets) {
  57584. size = sizeO + Math.floor((1 + delta) * Math.random());
  57585. if (f > totalFacets - size) {
  57586. size = totalFacets - f;
  57587. }
  57588. // reset temp arrays
  57589. facetPos.length = 0;
  57590. facetInd.length = 0;
  57591. facetUV.length = 0;
  57592. facetCol.length = 0;
  57593. // iterate over "size" facets
  57594. var fi = 0;
  57595. for (var j = f * 3; j < (f + size) * 3; j++) {
  57596. facetInd.push(fi);
  57597. var i = meshInd[j];
  57598. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  57599. if (meshUV) {
  57600. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  57601. }
  57602. if (meshCol) {
  57603. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  57604. }
  57605. fi++;
  57606. }
  57607. // create a model shape for each single particle
  57608. var idx = this.nbParticles;
  57609. var shape = this._posToShape(facetPos);
  57610. var shapeUV = this._uvsToShapeUV(facetUV);
  57611. // compute the barycenter of the shape
  57612. var v;
  57613. for (v = 0; v < shape.length; v++) {
  57614. barycenter.addInPlace(shape[v]);
  57615. }
  57616. barycenter.scaleInPlace(1 / shape.length);
  57617. // shift the shape from its barycenter to the origin
  57618. for (v = 0; v < shape.length; v++) {
  57619. shape[v].subtractInPlace(barycenter);
  57620. }
  57621. var bInfo;
  57622. if (this._particlesIntersect) {
  57623. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  57624. }
  57625. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  57626. // add the particle in the SPS
  57627. var currentPos = this._positions.length;
  57628. var currentInd = this._indices.length;
  57629. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  57630. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  57631. // initialize the particle position
  57632. this.particles[this.nbParticles].position.addInPlace(barycenter);
  57633. this._index += shape.length;
  57634. idx++;
  57635. this.nbParticles++;
  57636. this._shapeCounter++;
  57637. f += size;
  57638. }
  57639. return this;
  57640. };
  57641. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  57642. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  57643. var index = 0;
  57644. var idx = 0;
  57645. for (var p = 0; p < this.particles.length; p++) {
  57646. this._particle = this.particles[p];
  57647. this._shape = this._particle._model._shape;
  57648. if (this._particle.rotationQuaternion) {
  57649. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  57650. }
  57651. else {
  57652. this._yaw = this._particle.rotation.y;
  57653. this._pitch = this._particle.rotation.x;
  57654. this._roll = this._particle.rotation.z;
  57655. this._quaternionRotationYPR();
  57656. }
  57657. this._quaternionToRotationMatrix();
  57658. this._rotMatrix.invertToRef(this._invertMatrix);
  57659. for (var pt = 0; pt < this._shape.length; pt++) {
  57660. idx = index + pt * 3;
  57661. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  57662. this._fixedNormal32[idx] = this._normal.x;
  57663. this._fixedNormal32[idx + 1] = this._normal.y;
  57664. this._fixedNormal32[idx + 2] = this._normal.z;
  57665. }
  57666. index = idx + 3;
  57667. }
  57668. };
  57669. //reset copy
  57670. SolidParticleSystem.prototype._resetCopy = function () {
  57671. this._copy.position.x = 0;
  57672. this._copy.position.y = 0;
  57673. this._copy.position.z = 0;
  57674. this._copy.rotation.x = 0;
  57675. this._copy.rotation.y = 0;
  57676. this._copy.rotation.z = 0;
  57677. this._copy.rotationQuaternion = null;
  57678. this._copy.scaling.x = 1.0;
  57679. this._copy.scaling.y = 1.0;
  57680. this._copy.scaling.z = 1.0;
  57681. this._copy.uvs.x = 0;
  57682. this._copy.uvs.y = 0;
  57683. this._copy.uvs.z = 1.0;
  57684. this._copy.uvs.w = 1.0;
  57685. this._copy.color = null;
  57686. this._copy.translateFromPivot = false;
  57687. };
  57688. // _meshBuilder : inserts the shape model in the global SPS mesh
  57689. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  57690. var i;
  57691. var u = 0;
  57692. var c = 0;
  57693. var n = 0;
  57694. this._resetCopy();
  57695. if (options && options.positionFunction) { // call to custom positionFunction
  57696. options.positionFunction(this._copy, idx, idxInShape);
  57697. this._mustUnrotateFixedNormals = true;
  57698. }
  57699. if (this._copy.rotationQuaternion) {
  57700. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  57701. }
  57702. else {
  57703. this._yaw = this._copy.rotation.y;
  57704. this._pitch = this._copy.rotation.x;
  57705. this._roll = this._copy.rotation.z;
  57706. this._quaternionRotationYPR();
  57707. }
  57708. this._quaternionToRotationMatrix();
  57709. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  57710. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  57711. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  57712. if (this._copy.translateFromPivot) {
  57713. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  57714. }
  57715. else {
  57716. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  57717. }
  57718. for (i = 0; i < shape.length; i++) {
  57719. this._vertex.x = shape[i].x;
  57720. this._vertex.y = shape[i].y;
  57721. this._vertex.z = shape[i].z;
  57722. if (options && options.vertexFunction) {
  57723. options.vertexFunction(this._copy, this._vertex, i);
  57724. }
  57725. this._vertex.x *= this._copy.scaling.x;
  57726. this._vertex.y *= this._copy.scaling.y;
  57727. this._vertex.z *= this._copy.scaling.z;
  57728. this._vertex.x -= this._scaledPivot.x;
  57729. this._vertex.y -= this._scaledPivot.y;
  57730. this._vertex.z -= this._scaledPivot.z;
  57731. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  57732. this._rotated.addInPlace(this._pivotBackTranslation);
  57733. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  57734. if (meshUV) {
  57735. 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);
  57736. u += 2;
  57737. }
  57738. if (this._copy.color) {
  57739. this._color = this._copy.color;
  57740. }
  57741. else if (meshCol && meshCol[c] !== undefined) {
  57742. this._color.r = meshCol[c];
  57743. this._color.g = meshCol[c + 1];
  57744. this._color.b = meshCol[c + 2];
  57745. this._color.a = meshCol[c + 3];
  57746. }
  57747. else {
  57748. this._color.r = 1.0;
  57749. this._color.g = 1.0;
  57750. this._color.b = 1.0;
  57751. this._color.a = 1.0;
  57752. }
  57753. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  57754. c += 4;
  57755. if (!this.recomputeNormals && meshNor) {
  57756. this._normal.x = meshNor[n];
  57757. this._normal.y = meshNor[n + 1];
  57758. this._normal.z = meshNor[n + 2];
  57759. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  57760. normals.push(this._normal.x, this._normal.y, this._normal.z);
  57761. n += 3;
  57762. }
  57763. }
  57764. for (i = 0; i < meshInd.length; i++) {
  57765. var current_ind = p + meshInd[i];
  57766. indices.push(current_ind);
  57767. if (current_ind > 65535) {
  57768. this._needs32Bits = true;
  57769. }
  57770. }
  57771. if (this._pickable) {
  57772. var nbfaces = meshInd.length / 3;
  57773. for (i = 0; i < nbfaces; i++) {
  57774. this.pickedParticles.push({ idx: idx, faceId: i });
  57775. }
  57776. }
  57777. if (this._depthSort) {
  57778. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  57779. }
  57780. return this._copy;
  57781. };
  57782. // returns a shape array from positions array
  57783. SolidParticleSystem.prototype._posToShape = function (positions) {
  57784. var shape = [];
  57785. for (var i = 0; i < positions.length; i += 3) {
  57786. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  57787. }
  57788. return shape;
  57789. };
  57790. // returns a shapeUV array from a Vector4 uvs
  57791. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  57792. var shapeUV = [];
  57793. if (uvs) {
  57794. for (var i = 0; i < uvs.length; i++)
  57795. shapeUV.push(uvs[i]);
  57796. }
  57797. return shapeUV;
  57798. };
  57799. // adds a new particle object in the particles array
  57800. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  57801. if (bInfo === void 0) { bInfo = null; }
  57802. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  57803. this.particles.push(sp);
  57804. return sp;
  57805. };
  57806. /**
  57807. * Adds some particles to the SPS from the model shape. Returns the shape id.
  57808. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  57809. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  57810. * @param nb (positive integer) the number of particles to be created from this model
  57811. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  57812. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  57813. * @returns the number of shapes in the system
  57814. */
  57815. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  57816. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  57817. var meshInd = mesh.getIndices();
  57818. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  57819. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  57820. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  57821. var bbInfo;
  57822. if (this._particlesIntersect) {
  57823. bbInfo = mesh.getBoundingInfo();
  57824. }
  57825. var shape = this._posToShape(meshPos);
  57826. var shapeUV = this._uvsToShapeUV(meshUV);
  57827. var posfunc = options ? options.positionFunction : null;
  57828. var vtxfunc = options ? options.vertexFunction : null;
  57829. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  57830. // particles
  57831. var sp;
  57832. var currentCopy;
  57833. var idx = this.nbParticles;
  57834. for (var i = 0; i < nb; i++) {
  57835. var currentPos = this._positions.length;
  57836. var currentInd = this._indices.length;
  57837. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  57838. if (this._updatable) {
  57839. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  57840. sp.position.copyFrom(currentCopy.position);
  57841. sp.rotation.copyFrom(currentCopy.rotation);
  57842. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  57843. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  57844. }
  57845. if (currentCopy.color && sp.color) {
  57846. sp.color.copyFrom(currentCopy.color);
  57847. }
  57848. sp.scaling.copyFrom(currentCopy.scaling);
  57849. sp.uvs.copyFrom(currentCopy.uvs);
  57850. }
  57851. this._index += shape.length;
  57852. idx++;
  57853. }
  57854. this.nbParticles += nb;
  57855. this._shapeCounter++;
  57856. return this._shapeCounter - 1;
  57857. };
  57858. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  57859. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  57860. this._resetCopy();
  57861. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  57862. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  57863. }
  57864. if (this._copy.rotationQuaternion) {
  57865. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  57866. }
  57867. else {
  57868. this._yaw = this._copy.rotation.y;
  57869. this._pitch = this._copy.rotation.x;
  57870. this._roll = this._copy.rotation.z;
  57871. this._quaternionRotationYPR();
  57872. }
  57873. this._quaternionToRotationMatrix();
  57874. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  57875. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  57876. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  57877. if (this._copy.translateFromPivot) {
  57878. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  57879. }
  57880. else {
  57881. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  57882. }
  57883. this._shape = particle._model._shape;
  57884. for (var pt = 0; pt < this._shape.length; pt++) {
  57885. this._vertex.x = this._shape[pt].x;
  57886. this._vertex.y = this._shape[pt].y;
  57887. this._vertex.z = this._shape[pt].z;
  57888. if (particle._model._vertexFunction) {
  57889. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  57890. }
  57891. this._vertex.x *= this._copy.scaling.x;
  57892. this._vertex.y *= this._copy.scaling.y;
  57893. this._vertex.z *= this._copy.scaling.z;
  57894. this._vertex.x -= this._scaledPivot.x;
  57895. this._vertex.y -= this._scaledPivot.y;
  57896. this._vertex.z -= this._scaledPivot.z;
  57897. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  57898. this._rotated.addInPlace(this._pivotBackTranslation);
  57899. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  57900. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  57901. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  57902. }
  57903. particle.position.x = 0.0;
  57904. particle.position.y = 0.0;
  57905. particle.position.z = 0.0;
  57906. particle.rotation.x = 0.0;
  57907. particle.rotation.y = 0.0;
  57908. particle.rotation.z = 0.0;
  57909. particle.rotationQuaternion = null;
  57910. particle.scaling.x = 1.0;
  57911. particle.scaling.y = 1.0;
  57912. particle.scaling.z = 1.0;
  57913. particle.uvs.x = 0.0;
  57914. particle.uvs.y = 0.0;
  57915. particle.uvs.z = 1.0;
  57916. particle.uvs.w = 1.0;
  57917. particle.pivot.x = 0.0;
  57918. particle.pivot.y = 0.0;
  57919. particle.pivot.z = 0.0;
  57920. particle.translateFromPivot = false;
  57921. particle.parentId = null;
  57922. };
  57923. /**
  57924. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  57925. * @returns the SPS.
  57926. */
  57927. SolidParticleSystem.prototype.rebuildMesh = function () {
  57928. for (var p = 0; p < this.particles.length; p++) {
  57929. this._rebuildParticle(this.particles[p]);
  57930. }
  57931. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  57932. return this;
  57933. };
  57934. /**
  57935. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  57936. * This method calls `updateParticle()` for each particle of the SPS.
  57937. * For an animated SPS, it is usually called within the render loop.
  57938. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  57939. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  57940. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  57941. * @returns the SPS.
  57942. */
  57943. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  57944. if (start === void 0) { start = 0; }
  57945. if (end === void 0) { end = this.nbParticles - 1; }
  57946. if (update === void 0) { update = true; }
  57947. if (!this._updatable) {
  57948. return this;
  57949. }
  57950. // custom beforeUpdate
  57951. this.beforeUpdateParticles(start, end, update);
  57952. this._cam_axisX.x = 1.0;
  57953. this._cam_axisX.y = 0.0;
  57954. this._cam_axisX.z = 0.0;
  57955. this._cam_axisY.x = 0.0;
  57956. this._cam_axisY.y = 1.0;
  57957. this._cam_axisY.z = 0.0;
  57958. this._cam_axisZ.x = 0.0;
  57959. this._cam_axisZ.y = 0.0;
  57960. this._cam_axisZ.z = 1.0;
  57961. // cases when the World Matrix is to be computed first
  57962. if (this.billboard || this._depthSort) {
  57963. this.mesh.computeWorldMatrix(true);
  57964. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  57965. }
  57966. // if the particles will always face the camera
  57967. if (this.billboard) {
  57968. // compute the camera position and un-rotate it by the current mesh rotation
  57969. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  57970. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  57971. this._cam_axisZ.normalize();
  57972. // same for camera up vector extracted from the cam view matrix
  57973. var view = this._camera.getViewMatrix(true);
  57974. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  57975. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  57976. this._cam_axisY.normalize();
  57977. this._cam_axisX.normalize();
  57978. }
  57979. // if depthSort, compute the camera global position in the mesh local system
  57980. if (this._depthSort) {
  57981. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  57982. }
  57983. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  57984. var idx = 0; // current position index in the global array positions32
  57985. var index = 0; // position start index in the global array positions32 of the current particle
  57986. var colidx = 0; // current color index in the global array colors32
  57987. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  57988. var uvidx = 0; // current uv index in the global array uvs32
  57989. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  57990. var pt = 0; // current index in the particle model shape
  57991. if (this.mesh.isFacetDataEnabled) {
  57992. this._computeBoundingBox = true;
  57993. }
  57994. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  57995. if (this._computeBoundingBox) {
  57996. if (start == 0 && end == this.nbParticles - 1) { // all the particles are updated, then recompute the BBox from scratch
  57997. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  57998. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  57999. }
  58000. else { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  58001. if (this.mesh._boundingInfo) {
  58002. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  58003. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  58004. }
  58005. }
  58006. }
  58007. // particle loop
  58008. index = this.particles[start]._pos;
  58009. var vpos = (index / 3) | 0;
  58010. colorIndex = vpos * 4;
  58011. uvIndex = vpos * 2;
  58012. for (var p = start; p <= end; p++) {
  58013. this._particle = this.particles[p];
  58014. this._shape = this._particle._model._shape;
  58015. this._shapeUV = this._particle._model._shapeUV;
  58016. // call to custom user function to update the particle properties
  58017. this.updateParticle(this._particle);
  58018. // camera-particle distance for depth sorting
  58019. if (this._depthSort && this._depthSortParticles) {
  58020. var dsp = this.depthSortedParticles[p];
  58021. dsp.ind = this._particle._ind;
  58022. dsp.indicesLength = this._particle._model._indicesLength;
  58023. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  58024. }
  58025. // skip the computations for inactive or already invisible particles
  58026. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  58027. // increment indexes for the next particle
  58028. pt = this._shape.length;
  58029. index += pt * 3;
  58030. colorIndex += pt * 4;
  58031. uvIndex += pt * 2;
  58032. continue;
  58033. }
  58034. if (this._particle.isVisible) {
  58035. this._particle._stillInvisible = false; // un-mark permanent invisibility
  58036. this._particleHasParent = (this._particle.parentId !== null);
  58037. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  58038. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  58039. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  58040. // particle rotation matrix
  58041. if (this.billboard) {
  58042. this._particle.rotation.x = 0.0;
  58043. this._particle.rotation.y = 0.0;
  58044. }
  58045. if (this._computeParticleRotation || this.billboard) {
  58046. if (this._particle.rotationQuaternion) {
  58047. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  58048. }
  58049. else {
  58050. this._yaw = this._particle.rotation.y;
  58051. this._pitch = this._particle.rotation.x;
  58052. this._roll = this._particle.rotation.z;
  58053. this._quaternionRotationYPR();
  58054. }
  58055. this._quaternionToRotationMatrix();
  58056. }
  58057. if (this._particleHasParent) {
  58058. this._parent = this.particles[this._particle.parentId];
  58059. 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];
  58060. 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];
  58061. 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];
  58062. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  58063. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  58064. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  58065. if (this._computeParticleRotation || this.billboard) {
  58066. 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];
  58067. 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];
  58068. 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];
  58069. 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];
  58070. 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];
  58071. 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];
  58072. 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];
  58073. 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];
  58074. 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];
  58075. }
  58076. }
  58077. else {
  58078. this._particle._globalPosition.x = this._particle.position.x;
  58079. this._particle._globalPosition.y = this._particle.position.y;
  58080. this._particle._globalPosition.z = this._particle.position.z;
  58081. if (this._computeParticleRotation || this.billboard) {
  58082. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  58083. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  58084. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  58085. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  58086. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  58087. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  58088. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  58089. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  58090. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  58091. }
  58092. }
  58093. if (this._particle.translateFromPivot) {
  58094. this._pivotBackTranslation.x = 0.0;
  58095. this._pivotBackTranslation.y = 0.0;
  58096. this._pivotBackTranslation.z = 0.0;
  58097. }
  58098. else {
  58099. this._pivotBackTranslation.x = this._scaledPivot.x;
  58100. this._pivotBackTranslation.y = this._scaledPivot.y;
  58101. this._pivotBackTranslation.z = this._scaledPivot.z;
  58102. }
  58103. // particle vertex loop
  58104. for (pt = 0; pt < this._shape.length; pt++) {
  58105. idx = index + pt * 3;
  58106. colidx = colorIndex + pt * 4;
  58107. uvidx = uvIndex + pt * 2;
  58108. this._vertex.x = this._shape[pt].x;
  58109. this._vertex.y = this._shape[pt].y;
  58110. this._vertex.z = this._shape[pt].z;
  58111. if (this._computeParticleVertex) {
  58112. this.updateParticleVertex(this._particle, this._vertex, pt);
  58113. }
  58114. // positions
  58115. this._vertex.x *= this._particle.scaling.x;
  58116. this._vertex.y *= this._particle.scaling.y;
  58117. this._vertex.z *= this._particle.scaling.z;
  58118. this._vertex.x -= this._scaledPivot.x;
  58119. this._vertex.y -= this._scaledPivot.y;
  58120. this._vertex.z -= this._scaledPivot.z;
  58121. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  58122. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  58123. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  58124. this._rotated.x += this._pivotBackTranslation.x;
  58125. this._rotated.y += this._pivotBackTranslation.y;
  58126. this._rotated.z += this._pivotBackTranslation.z;
  58127. 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;
  58128. 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;
  58129. 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;
  58130. if (this._computeBoundingBox) {
  58131. if (this._positions32[idx] < this._minimum.x) {
  58132. this._minimum.x = this._positions32[idx];
  58133. }
  58134. if (this._positions32[idx] > this._maximum.x) {
  58135. this._maximum.x = this._positions32[idx];
  58136. }
  58137. if (this._positions32[idx + 1] < this._minimum.y) {
  58138. this._minimum.y = this._positions32[idx + 1];
  58139. }
  58140. if (this._positions32[idx + 1] > this._maximum.y) {
  58141. this._maximum.y = this._positions32[idx + 1];
  58142. }
  58143. if (this._positions32[idx + 2] < this._minimum.z) {
  58144. this._minimum.z = this._positions32[idx + 2];
  58145. }
  58146. if (this._positions32[idx + 2] > this._maximum.z) {
  58147. this._maximum.z = this._positions32[idx + 2];
  58148. }
  58149. }
  58150. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  58151. if (!this._computeParticleVertex) {
  58152. this._normal.x = this._fixedNormal32[idx];
  58153. this._normal.y = this._fixedNormal32[idx + 1];
  58154. this._normal.z = this._fixedNormal32[idx + 2];
  58155. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  58156. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  58157. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  58158. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  58159. 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;
  58160. 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;
  58161. }
  58162. if (this._computeParticleColor && this._particle.color) {
  58163. this._colors32[colidx] = this._particle.color.r;
  58164. this._colors32[colidx + 1] = this._particle.color.g;
  58165. this._colors32[colidx + 2] = this._particle.color.b;
  58166. this._colors32[colidx + 3] = this._particle.color.a;
  58167. }
  58168. if (this._computeParticleTexture) {
  58169. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  58170. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  58171. }
  58172. }
  58173. }
  58174. // particle just set invisible : scaled to zero and positioned at the origin
  58175. else {
  58176. this._particle._stillInvisible = true; // mark the particle as invisible
  58177. for (pt = 0; pt < this._shape.length; pt++) {
  58178. idx = index + pt * 3;
  58179. colidx = colorIndex + pt * 4;
  58180. uvidx = uvIndex + pt * 2;
  58181. this._positions32[idx] = 0.0;
  58182. this._positions32[idx + 1] = 0.0;
  58183. this._positions32[idx + 2] = 0.0;
  58184. this._normals32[idx] = 0.0;
  58185. this._normals32[idx + 1] = 0.0;
  58186. this._normals32[idx + 2] = 0.0;
  58187. if (this._computeParticleColor && this._particle.color) {
  58188. this._colors32[colidx] = this._particle.color.r;
  58189. this._colors32[colidx + 1] = this._particle.color.g;
  58190. this._colors32[colidx + 2] = this._particle.color.b;
  58191. this._colors32[colidx + 3] = this._particle.color.a;
  58192. }
  58193. if (this._computeParticleTexture) {
  58194. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  58195. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  58196. }
  58197. }
  58198. }
  58199. // if the particle intersections must be computed : update the bbInfo
  58200. if (this._particlesIntersect) {
  58201. var bInfo = this._particle._boundingInfo;
  58202. var bBox = bInfo.boundingBox;
  58203. var bSphere = bInfo.boundingSphere;
  58204. if (!this._bSphereOnly) {
  58205. // place, scale and rotate the particle bbox within the SPS local system, then update it
  58206. for (var b = 0; b < bBox.vectors.length; b++) {
  58207. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  58208. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  58209. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  58210. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  58211. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  58212. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  58213. 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;
  58214. 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;
  58215. 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;
  58216. }
  58217. bBox._update(this.mesh._worldMatrix);
  58218. }
  58219. // place and scale the particle bouding sphere in the SPS local system, then update it
  58220. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  58221. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  58222. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  58223. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  58224. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  58225. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  58226. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  58227. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  58228. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  58229. 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));
  58230. bSphere._update(this.mesh._worldMatrix);
  58231. }
  58232. // increment indexes for the next particle
  58233. index = idx + 3;
  58234. colorIndex = colidx + 4;
  58235. uvIndex = uvidx + 2;
  58236. }
  58237. // if the VBO must be updated
  58238. if (update) {
  58239. if (this._computeParticleColor) {
  58240. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  58241. }
  58242. if (this._computeParticleTexture) {
  58243. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  58244. }
  58245. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  58246. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  58247. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  58248. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  58249. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  58250. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  58251. for (var i = 0; i < this._normals32.length; i++) {
  58252. this._fixedNormal32[i] = this._normals32[i];
  58253. }
  58254. }
  58255. if (!this.mesh.areNormalsFrozen) {
  58256. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  58257. }
  58258. }
  58259. if (this._depthSort && this._depthSortParticles) {
  58260. this.depthSortedParticles.sort(this._depthSortFunction);
  58261. var dspl = this.depthSortedParticles.length;
  58262. var sorted = 0;
  58263. var lind = 0;
  58264. var sind = 0;
  58265. var sid = 0;
  58266. for (sorted = 0; sorted < dspl; sorted++) {
  58267. lind = this.depthSortedParticles[sorted].indicesLength;
  58268. sind = this.depthSortedParticles[sorted].ind;
  58269. for (var i = 0; i < lind; i++) {
  58270. this._indices32[sid] = this._indices[sind + i];
  58271. sid++;
  58272. }
  58273. }
  58274. this.mesh.updateIndices(this._indices32);
  58275. }
  58276. }
  58277. if (this._computeBoundingBox) {
  58278. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  58279. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  58280. }
  58281. this.afterUpdateParticles(start, end, update);
  58282. return this;
  58283. };
  58284. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  58285. this._halfroll = this._roll * 0.5;
  58286. this._halfpitch = this._pitch * 0.5;
  58287. this._halfyaw = this._yaw * 0.5;
  58288. this._sinRoll = Math.sin(this._halfroll);
  58289. this._cosRoll = Math.cos(this._halfroll);
  58290. this._sinPitch = Math.sin(this._halfpitch);
  58291. this._cosPitch = Math.cos(this._halfpitch);
  58292. this._sinYaw = Math.sin(this._halfyaw);
  58293. this._cosYaw = Math.cos(this._halfyaw);
  58294. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  58295. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  58296. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  58297. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  58298. };
  58299. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  58300. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  58301. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  58302. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  58303. this._rotMatrix.m[3] = 0;
  58304. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  58305. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  58306. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  58307. this._rotMatrix.m[7] = 0;
  58308. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  58309. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  58310. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  58311. this._rotMatrix.m[11] = 0;
  58312. this._rotMatrix.m[12] = 0;
  58313. this._rotMatrix.m[13] = 0;
  58314. this._rotMatrix.m[14] = 0;
  58315. this._rotMatrix.m[15] = 1.0;
  58316. };
  58317. /**
  58318. * Disposes the SPS.
  58319. */
  58320. SolidParticleSystem.prototype.dispose = function () {
  58321. this.mesh.dispose();
  58322. this.vars = null;
  58323. // drop references to internal big arrays for the GC
  58324. this._positions = null;
  58325. this._indices = null;
  58326. this._normals = null;
  58327. this._uvs = null;
  58328. this._colors = null;
  58329. this._indices32 = null;
  58330. this._positions32 = null;
  58331. this._normals32 = null;
  58332. this._fixedNormal32 = null;
  58333. this._uvs32 = null;
  58334. this._colors32 = null;
  58335. this.pickedParticles = null;
  58336. };
  58337. /**
  58338. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  58339. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58340. * @returns the SPS.
  58341. */
  58342. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  58343. if (!this._isVisibilityBoxLocked) {
  58344. this.mesh.refreshBoundingInfo();
  58345. }
  58346. return this;
  58347. };
  58348. /**
  58349. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  58350. * @param size the size (float) of the visibility box
  58351. * note : this doesn't lock the SPS mesh bounding box.
  58352. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58353. */
  58354. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  58355. var vis = size / 2;
  58356. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  58357. };
  58358. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  58359. /**
  58360. * Gets whether the SPS as always visible or not
  58361. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58362. */
  58363. get: function () {
  58364. return this._alwaysVisible;
  58365. },
  58366. /**
  58367. * Sets the SPS as always visible or not
  58368. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58369. */
  58370. set: function (val) {
  58371. this._alwaysVisible = val;
  58372. this.mesh.alwaysSelectAsActiveMesh = val;
  58373. },
  58374. enumerable: true,
  58375. configurable: true
  58376. });
  58377. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  58378. /**
  58379. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  58380. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58381. */
  58382. get: function () {
  58383. return this._isVisibilityBoxLocked;
  58384. },
  58385. /**
  58386. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  58387. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58388. */
  58389. set: function (val) {
  58390. this._isVisibilityBoxLocked = val;
  58391. var boundingInfo = this.mesh.getBoundingInfo();
  58392. boundingInfo.isLocked = val;
  58393. },
  58394. enumerable: true,
  58395. configurable: true
  58396. });
  58397. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  58398. /**
  58399. * Gets if `setParticles()` computes the particle rotations or not.
  58400. * Default value : true. The SPS is faster when it's set to false.
  58401. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  58402. */
  58403. get: function () {
  58404. return this._computeParticleRotation;
  58405. },
  58406. /**
  58407. * Tells to `setParticles()` to compute the particle rotations or not.
  58408. * Default value : true. The SPS is faster when it's set to false.
  58409. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  58410. */
  58411. set: function (val) {
  58412. this._computeParticleRotation = val;
  58413. },
  58414. enumerable: true,
  58415. configurable: true
  58416. });
  58417. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  58418. /**
  58419. * Gets if `setParticles()` computes the particle colors or not.
  58420. * Default value : true. The SPS is faster when it's set to false.
  58421. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  58422. */
  58423. get: function () {
  58424. return this._computeParticleColor;
  58425. },
  58426. /**
  58427. * Tells to `setParticles()` to compute the particle colors or not.
  58428. * Default value : true. The SPS is faster when it's set to false.
  58429. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  58430. */
  58431. set: function (val) {
  58432. this._computeParticleColor = val;
  58433. },
  58434. enumerable: true,
  58435. configurable: true
  58436. });
  58437. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  58438. /**
  58439. * Gets if `setParticles()` computes the particle textures or not.
  58440. * Default value : true. The SPS is faster when it's set to false.
  58441. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  58442. */
  58443. get: function () {
  58444. return this._computeParticleTexture;
  58445. },
  58446. set: function (val) {
  58447. this._computeParticleTexture = val;
  58448. },
  58449. enumerable: true,
  58450. configurable: true
  58451. });
  58452. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  58453. /**
  58454. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  58455. * Default value : false. The SPS is faster when it's set to false.
  58456. * Note : the particle custom vertex positions aren't stored values.
  58457. */
  58458. get: function () {
  58459. return this._computeParticleVertex;
  58460. },
  58461. /**
  58462. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  58463. * Default value : false. The SPS is faster when it's set to false.
  58464. * Note : the particle custom vertex positions aren't stored values.
  58465. */
  58466. set: function (val) {
  58467. this._computeParticleVertex = val;
  58468. },
  58469. enumerable: true,
  58470. configurable: true
  58471. });
  58472. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  58473. /**
  58474. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  58475. */
  58476. get: function () {
  58477. return this._computeBoundingBox;
  58478. },
  58479. /**
  58480. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  58481. */
  58482. set: function (val) {
  58483. this._computeBoundingBox = val;
  58484. },
  58485. enumerable: true,
  58486. configurable: true
  58487. });
  58488. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  58489. /**
  58490. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  58491. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  58492. * Default : `true`
  58493. */
  58494. get: function () {
  58495. return this._depthSortParticles;
  58496. },
  58497. /**
  58498. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  58499. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  58500. * Default : `true`
  58501. */
  58502. set: function (val) {
  58503. this._depthSortParticles = val;
  58504. },
  58505. enumerable: true,
  58506. configurable: true
  58507. });
  58508. // =======================================================================
  58509. // Particle behavior logic
  58510. // these following methods may be overwritten by the user to fit his needs
  58511. /**
  58512. * This function does nothing. It may be overwritten to set all the particle first values.
  58513. * The SPS doesn't call this function, you may have to call it by your own.
  58514. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  58515. */
  58516. SolidParticleSystem.prototype.initParticles = function () {
  58517. };
  58518. /**
  58519. * This function does nothing. It may be overwritten to recycle a particle.
  58520. * The SPS doesn't call this function, you may have to call it by your own.
  58521. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  58522. * @param particle The particle to recycle
  58523. * @returns the recycled particle
  58524. */
  58525. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  58526. return particle;
  58527. };
  58528. /**
  58529. * Updates a particle : this function should be overwritten by the user.
  58530. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  58531. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  58532. * @example : just set a particle position or velocity and recycle conditions
  58533. * @param particle The particle to update
  58534. * @returns the updated particle
  58535. */
  58536. SolidParticleSystem.prototype.updateParticle = function (particle) {
  58537. return particle;
  58538. };
  58539. /**
  58540. * Updates a vertex of a particle : it can be overwritten by the user.
  58541. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  58542. * @param particle the current particle
  58543. * @param vertex the current index of the current particle
  58544. * @param pt the index of the current vertex in the particle shape
  58545. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  58546. * @example : just set a vertex particle position
  58547. * @returns the updated vertex
  58548. */
  58549. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  58550. return vertex;
  58551. };
  58552. /**
  58553. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  58554. * This does nothing and may be overwritten by the user.
  58555. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  58556. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  58557. * @param update the boolean update value actually passed to setParticles()
  58558. */
  58559. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  58560. };
  58561. /**
  58562. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  58563. * This will be passed three parameters.
  58564. * This does nothing and may be overwritten by the user.
  58565. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  58566. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  58567. * @param update the boolean update value actually passed to setParticles()
  58568. */
  58569. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  58570. };
  58571. return SolidParticleSystem;
  58572. }());
  58573. BABYLON.SolidParticleSystem = SolidParticleSystem;
  58574. })(BABYLON || (BABYLON = {}));
  58575. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  58576. var BABYLON;
  58577. (function (BABYLON) {
  58578. var ShaderMaterial = /** @class */ (function (_super) {
  58579. __extends(ShaderMaterial, _super);
  58580. function ShaderMaterial(name, scene, shaderPath, options) {
  58581. var _this = _super.call(this, name, scene) || this;
  58582. _this._textures = {};
  58583. _this._textureArrays = {};
  58584. _this._floats = {};
  58585. _this._ints = {};
  58586. _this._floatsArrays = {};
  58587. _this._colors3 = {};
  58588. _this._colors3Arrays = {};
  58589. _this._colors4 = {};
  58590. _this._vectors2 = {};
  58591. _this._vectors3 = {};
  58592. _this._vectors4 = {};
  58593. _this._matrices = {};
  58594. _this._matrices3x3 = {};
  58595. _this._matrices2x2 = {};
  58596. _this._vectors2Arrays = {};
  58597. _this._vectors3Arrays = {};
  58598. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  58599. _this._shaderPath = shaderPath;
  58600. options.needAlphaBlending = options.needAlphaBlending || false;
  58601. options.needAlphaTesting = options.needAlphaTesting || false;
  58602. options.attributes = options.attributes || ["position", "normal", "uv"];
  58603. options.uniforms = options.uniforms || ["worldViewProjection"];
  58604. options.uniformBuffers = options.uniformBuffers || [];
  58605. options.samplers = options.samplers || [];
  58606. options.defines = options.defines || [];
  58607. _this._options = options;
  58608. return _this;
  58609. }
  58610. ShaderMaterial.prototype.getClassName = function () {
  58611. return "ShaderMaterial";
  58612. };
  58613. ShaderMaterial.prototype.needAlphaBlending = function () {
  58614. return this._options.needAlphaBlending;
  58615. };
  58616. ShaderMaterial.prototype.needAlphaTesting = function () {
  58617. return this._options.needAlphaTesting;
  58618. };
  58619. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  58620. if (this._options.uniforms.indexOf(uniformName) === -1) {
  58621. this._options.uniforms.push(uniformName);
  58622. }
  58623. };
  58624. ShaderMaterial.prototype.setTexture = function (name, texture) {
  58625. if (this._options.samplers.indexOf(name) === -1) {
  58626. this._options.samplers.push(name);
  58627. }
  58628. this._textures[name] = texture;
  58629. return this;
  58630. };
  58631. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  58632. if (this._options.samplers.indexOf(name) === -1) {
  58633. this._options.samplers.push(name);
  58634. }
  58635. this._checkUniform(name);
  58636. this._textureArrays[name] = textures;
  58637. return this;
  58638. };
  58639. ShaderMaterial.prototype.setFloat = function (name, value) {
  58640. this._checkUniform(name);
  58641. this._floats[name] = value;
  58642. return this;
  58643. };
  58644. ShaderMaterial.prototype.setInt = function (name, value) {
  58645. this._checkUniform(name);
  58646. this._ints[name] = value;
  58647. return this;
  58648. };
  58649. ShaderMaterial.prototype.setFloats = function (name, value) {
  58650. this._checkUniform(name);
  58651. this._floatsArrays[name] = value;
  58652. return this;
  58653. };
  58654. ShaderMaterial.prototype.setColor3 = function (name, value) {
  58655. this._checkUniform(name);
  58656. this._colors3[name] = value;
  58657. return this;
  58658. };
  58659. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  58660. this._checkUniform(name);
  58661. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  58662. color.toArray(arr, arr.length);
  58663. return arr;
  58664. }, []);
  58665. return this;
  58666. };
  58667. ShaderMaterial.prototype.setColor4 = function (name, value) {
  58668. this._checkUniform(name);
  58669. this._colors4[name] = value;
  58670. return this;
  58671. };
  58672. ShaderMaterial.prototype.setVector2 = function (name, value) {
  58673. this._checkUniform(name);
  58674. this._vectors2[name] = value;
  58675. return this;
  58676. };
  58677. ShaderMaterial.prototype.setVector3 = function (name, value) {
  58678. this._checkUniform(name);
  58679. this._vectors3[name] = value;
  58680. return this;
  58681. };
  58682. ShaderMaterial.prototype.setVector4 = function (name, value) {
  58683. this._checkUniform(name);
  58684. this._vectors4[name] = value;
  58685. return this;
  58686. };
  58687. ShaderMaterial.prototype.setMatrix = function (name, value) {
  58688. this._checkUniform(name);
  58689. this._matrices[name] = value;
  58690. return this;
  58691. };
  58692. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  58693. this._checkUniform(name);
  58694. this._matrices3x3[name] = value;
  58695. return this;
  58696. };
  58697. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  58698. this._checkUniform(name);
  58699. this._matrices2x2[name] = value;
  58700. return this;
  58701. };
  58702. ShaderMaterial.prototype.setArray2 = function (name, value) {
  58703. this._checkUniform(name);
  58704. this._vectors2Arrays[name] = value;
  58705. return this;
  58706. };
  58707. ShaderMaterial.prototype.setArray3 = function (name, value) {
  58708. this._checkUniform(name);
  58709. this._vectors3Arrays[name] = value;
  58710. return this;
  58711. };
  58712. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  58713. if (!mesh) {
  58714. return true;
  58715. }
  58716. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  58717. return false;
  58718. }
  58719. return false;
  58720. };
  58721. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  58722. var scene = this.getScene();
  58723. var engine = scene.getEngine();
  58724. if (!this.checkReadyOnEveryCall) {
  58725. if (this._renderId === scene.getRenderId()) {
  58726. if (this._checkCache(scene, mesh, useInstances)) {
  58727. return true;
  58728. }
  58729. }
  58730. }
  58731. // Instances
  58732. var defines = [];
  58733. var attribs = [];
  58734. var fallbacks = new BABYLON.EffectFallbacks();
  58735. if (useInstances) {
  58736. defines.push("#define INSTANCES");
  58737. }
  58738. for (var index = 0; index < this._options.defines.length; index++) {
  58739. defines.push(this._options.defines[index]);
  58740. }
  58741. for (var index = 0; index < this._options.attributes.length; index++) {
  58742. attribs.push(this._options.attributes[index]);
  58743. }
  58744. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  58745. attribs.push(BABYLON.VertexBuffer.ColorKind);
  58746. defines.push("#define VERTEXCOLOR");
  58747. }
  58748. // Bones
  58749. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  58750. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  58751. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  58752. if (mesh.numBoneInfluencers > 4) {
  58753. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  58754. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  58755. }
  58756. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  58757. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  58758. fallbacks.addCPUSkinningFallback(0, mesh);
  58759. if (this._options.uniforms.indexOf("mBones") === -1) {
  58760. this._options.uniforms.push("mBones");
  58761. }
  58762. }
  58763. else {
  58764. defines.push("#define NUM_BONE_INFLUENCERS 0");
  58765. }
  58766. // Textures
  58767. for (var name in this._textures) {
  58768. if (!this._textures[name].isReady()) {
  58769. return false;
  58770. }
  58771. }
  58772. // Alpha test
  58773. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  58774. defines.push("#define ALPHATEST");
  58775. }
  58776. var previousEffect = this._effect;
  58777. var join = defines.join("\n");
  58778. this._effect = engine.createEffect(this._shaderPath, {
  58779. attributes: attribs,
  58780. uniformsNames: this._options.uniforms,
  58781. uniformBuffersNames: this._options.uniformBuffers,
  58782. samplers: this._options.samplers,
  58783. defines: join,
  58784. fallbacks: fallbacks,
  58785. onCompiled: this.onCompiled,
  58786. onError: this.onError
  58787. }, engine);
  58788. if (!this._effect.isReady()) {
  58789. return false;
  58790. }
  58791. if (previousEffect !== this._effect) {
  58792. scene.resetCachedMaterial();
  58793. }
  58794. this._renderId = scene.getRenderId();
  58795. return true;
  58796. };
  58797. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  58798. var scene = this.getScene();
  58799. if (!this._effect) {
  58800. return;
  58801. }
  58802. if (this._options.uniforms.indexOf("world") !== -1) {
  58803. this._effect.setMatrix("world", world);
  58804. }
  58805. if (this._options.uniforms.indexOf("worldView") !== -1) {
  58806. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  58807. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  58808. }
  58809. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  58810. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  58811. }
  58812. };
  58813. ShaderMaterial.prototype.bind = function (world, mesh) {
  58814. // Std values
  58815. this.bindOnlyWorldMatrix(world);
  58816. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  58817. if (this._options.uniforms.indexOf("view") !== -1) {
  58818. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  58819. }
  58820. if (this._options.uniforms.indexOf("projection") !== -1) {
  58821. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  58822. }
  58823. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  58824. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  58825. }
  58826. // Bones
  58827. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  58828. var name;
  58829. // Texture
  58830. for (name in this._textures) {
  58831. this._effect.setTexture(name, this._textures[name]);
  58832. }
  58833. // Texture arrays
  58834. for (name in this._textureArrays) {
  58835. this._effect.setTextureArray(name, this._textureArrays[name]);
  58836. }
  58837. // Int
  58838. for (name in this._ints) {
  58839. this._effect.setInt(name, this._ints[name]);
  58840. }
  58841. // Float
  58842. for (name in this._floats) {
  58843. this._effect.setFloat(name, this._floats[name]);
  58844. }
  58845. // Floats
  58846. for (name in this._floatsArrays) {
  58847. this._effect.setArray(name, this._floatsArrays[name]);
  58848. }
  58849. // Color3
  58850. for (name in this._colors3) {
  58851. this._effect.setColor3(name, this._colors3[name]);
  58852. }
  58853. for (name in this._colors3Arrays) {
  58854. this._effect.setArray3(name, this._colors3Arrays[name]);
  58855. }
  58856. // Color4
  58857. for (name in this._colors4) {
  58858. var color = this._colors4[name];
  58859. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  58860. }
  58861. // Vector2
  58862. for (name in this._vectors2) {
  58863. this._effect.setVector2(name, this._vectors2[name]);
  58864. }
  58865. // Vector3
  58866. for (name in this._vectors3) {
  58867. this._effect.setVector3(name, this._vectors3[name]);
  58868. }
  58869. // Vector4
  58870. for (name in this._vectors4) {
  58871. this._effect.setVector4(name, this._vectors4[name]);
  58872. }
  58873. // Matrix
  58874. for (name in this._matrices) {
  58875. this._effect.setMatrix(name, this._matrices[name]);
  58876. }
  58877. // Matrix 3x3
  58878. for (name in this._matrices3x3) {
  58879. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  58880. }
  58881. // Matrix 2x2
  58882. for (name in this._matrices2x2) {
  58883. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  58884. }
  58885. // Vector2Array
  58886. for (name in this._vectors2Arrays) {
  58887. this._effect.setArray2(name, this._vectors2Arrays[name]);
  58888. }
  58889. // Vector3Array
  58890. for (name in this._vectors3Arrays) {
  58891. this._effect.setArray3(name, this._vectors3Arrays[name]);
  58892. }
  58893. }
  58894. this._afterBind(mesh);
  58895. };
  58896. ShaderMaterial.prototype.getActiveTextures = function () {
  58897. var activeTextures = _super.prototype.getActiveTextures.call(this);
  58898. for (var name in this._textures) {
  58899. activeTextures.push(this._textures[name]);
  58900. }
  58901. for (var name in this._textureArrays) {
  58902. var array = this._textureArrays[name];
  58903. for (var index = 0; index < array.length; index++) {
  58904. activeTextures.push(array[index]);
  58905. }
  58906. }
  58907. return activeTextures;
  58908. };
  58909. ShaderMaterial.prototype.hasTexture = function (texture) {
  58910. if (_super.prototype.hasTexture.call(this, texture)) {
  58911. return true;
  58912. }
  58913. for (var name in this._textures) {
  58914. if (this._textures[name] === texture) {
  58915. return true;
  58916. }
  58917. }
  58918. for (var name in this._textureArrays) {
  58919. var array = this._textureArrays[name];
  58920. for (var index = 0; index < array.length; index++) {
  58921. if (array[index] === texture) {
  58922. return true;
  58923. }
  58924. }
  58925. }
  58926. return false;
  58927. };
  58928. ShaderMaterial.prototype.clone = function (name) {
  58929. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  58930. return newShaderMaterial;
  58931. };
  58932. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  58933. if (forceDisposeTextures) {
  58934. var name;
  58935. for (name in this._textures) {
  58936. this._textures[name].dispose();
  58937. }
  58938. for (name in this._textureArrays) {
  58939. var array = this._textureArrays[name];
  58940. for (var index = 0; index < array.length; index++) {
  58941. array[index].dispose();
  58942. }
  58943. }
  58944. }
  58945. this._textures = {};
  58946. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  58947. };
  58948. ShaderMaterial.prototype.serialize = function () {
  58949. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  58950. serializationObject.customType = "BABYLON.ShaderMaterial";
  58951. serializationObject.options = this._options;
  58952. serializationObject.shaderPath = this._shaderPath;
  58953. var name;
  58954. // Texture
  58955. serializationObject.textures = {};
  58956. for (name in this._textures) {
  58957. serializationObject.textures[name] = this._textures[name].serialize();
  58958. }
  58959. // Texture arrays
  58960. serializationObject.textureArrays = {};
  58961. for (name in this._textureArrays) {
  58962. serializationObject.textureArrays[name] = [];
  58963. var array = this._textureArrays[name];
  58964. for (var index = 0; index < array.length; index++) {
  58965. serializationObject.textureArrays[name].push(array[index].serialize());
  58966. }
  58967. }
  58968. // Float
  58969. serializationObject.floats = {};
  58970. for (name in this._floats) {
  58971. serializationObject.floats[name] = this._floats[name];
  58972. }
  58973. // Float s
  58974. serializationObject.FloatArrays = {};
  58975. for (name in this._floatsArrays) {
  58976. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  58977. }
  58978. // Color3
  58979. serializationObject.colors3 = {};
  58980. for (name in this._colors3) {
  58981. serializationObject.colors3[name] = this._colors3[name].asArray();
  58982. }
  58983. // Color3 array
  58984. serializationObject.colors3Arrays = {};
  58985. for (name in this._colors3Arrays) {
  58986. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  58987. }
  58988. // Color4
  58989. serializationObject.colors4 = {};
  58990. for (name in this._colors4) {
  58991. serializationObject.colors4[name] = this._colors4[name].asArray();
  58992. }
  58993. // Vector2
  58994. serializationObject.vectors2 = {};
  58995. for (name in this._vectors2) {
  58996. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  58997. }
  58998. // Vector3
  58999. serializationObject.vectors3 = {};
  59000. for (name in this._vectors3) {
  59001. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  59002. }
  59003. // Vector4
  59004. serializationObject.vectors4 = {};
  59005. for (name in this._vectors4) {
  59006. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  59007. }
  59008. // Matrix
  59009. serializationObject.matrices = {};
  59010. for (name in this._matrices) {
  59011. serializationObject.matrices[name] = this._matrices[name].asArray();
  59012. }
  59013. // Matrix 3x3
  59014. serializationObject.matrices3x3 = {};
  59015. for (name in this._matrices3x3) {
  59016. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  59017. }
  59018. // Matrix 2x2
  59019. serializationObject.matrices2x2 = {};
  59020. for (name in this._matrices2x2) {
  59021. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  59022. }
  59023. // Vector2Array
  59024. serializationObject.vectors2Arrays = {};
  59025. for (name in this._vectors2Arrays) {
  59026. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  59027. }
  59028. // Vector3Array
  59029. serializationObject.vectors3Arrays = {};
  59030. for (name in this._vectors3Arrays) {
  59031. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  59032. }
  59033. return serializationObject;
  59034. };
  59035. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  59036. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  59037. var name;
  59038. // Texture
  59039. for (name in source.textures) {
  59040. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  59041. }
  59042. // Texture arrays
  59043. for (name in source.textureArrays) {
  59044. var array = source.textureArrays[name];
  59045. var textureArray = new Array();
  59046. for (var index = 0; index < array.length; index++) {
  59047. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  59048. }
  59049. material.setTextureArray(name, textureArray);
  59050. }
  59051. // Float
  59052. for (name in source.floats) {
  59053. material.setFloat(name, source.floats[name]);
  59054. }
  59055. // Float s
  59056. for (name in source.floatsArrays) {
  59057. material.setFloats(name, source.floatsArrays[name]);
  59058. }
  59059. // Color3
  59060. for (name in source.colors3) {
  59061. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  59062. }
  59063. // Color3 arrays
  59064. for (name in source.colors3Arrays) {
  59065. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  59066. if (i % 3 === 0) {
  59067. arr.push([num]);
  59068. }
  59069. else {
  59070. arr[arr.length - 1].push(num);
  59071. }
  59072. return arr;
  59073. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  59074. material.setColor3Array(name, colors);
  59075. }
  59076. // Color4
  59077. for (name in source.colors4) {
  59078. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  59079. }
  59080. // Vector2
  59081. for (name in source.vectors2) {
  59082. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  59083. }
  59084. // Vector3
  59085. for (name in source.vectors3) {
  59086. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  59087. }
  59088. // Vector4
  59089. for (name in source.vectors4) {
  59090. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  59091. }
  59092. // Matrix
  59093. for (name in source.matrices) {
  59094. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  59095. }
  59096. // Matrix 3x3
  59097. for (name in source.matrices3x3) {
  59098. material.setMatrix3x3(name, source.matrices3x3[name]);
  59099. }
  59100. // Matrix 2x2
  59101. for (name in source.matrices2x2) {
  59102. material.setMatrix2x2(name, source.matrices2x2[name]);
  59103. }
  59104. // Vector2Array
  59105. for (name in source.vectors2Arrays) {
  59106. material.setArray2(name, source.vectors2Arrays[name]);
  59107. }
  59108. // Vector3Array
  59109. for (name in source.vectors3Arrays) {
  59110. material.setArray3(name, source.vectors3Arrays[name]);
  59111. }
  59112. return material;
  59113. };
  59114. return ShaderMaterial;
  59115. }(BABYLON.Material));
  59116. BABYLON.ShaderMaterial = ShaderMaterial;
  59117. })(BABYLON || (BABYLON = {}));
  59118. //# sourceMappingURL=babylon.shaderMaterial.js.map
  59119. var BABYLON;
  59120. (function (BABYLON) {
  59121. var GroundMesh = /** @class */ (function (_super) {
  59122. __extends(GroundMesh, _super);
  59123. function GroundMesh(name, scene) {
  59124. var _this = _super.call(this, name, scene) || this;
  59125. _this.generateOctree = false;
  59126. return _this;
  59127. }
  59128. GroundMesh.prototype.getClassName = function () {
  59129. return "GroundMesh";
  59130. };
  59131. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  59132. get: function () {
  59133. return Math.min(this._subdivisionsX, this._subdivisionsY);
  59134. },
  59135. enumerable: true,
  59136. configurable: true
  59137. });
  59138. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  59139. get: function () {
  59140. return this._subdivisionsX;
  59141. },
  59142. enumerable: true,
  59143. configurable: true
  59144. });
  59145. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  59146. get: function () {
  59147. return this._subdivisionsY;
  59148. },
  59149. enumerable: true,
  59150. configurable: true
  59151. });
  59152. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  59153. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  59154. this._subdivisionsX = chunksCount;
  59155. this._subdivisionsY = chunksCount;
  59156. this.subdivide(chunksCount);
  59157. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  59158. };
  59159. /**
  59160. * Returns a height (y) value in the Worl system :
  59161. * the ground altitude at the coordinates (x, z) expressed in the World system.
  59162. * Returns the ground y position if (x, z) are outside the ground surface.
  59163. */
  59164. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  59165. var world = this.getWorldMatrix();
  59166. var invMat = BABYLON.Tmp.Matrix[5];
  59167. world.invertToRef(invMat);
  59168. var tmpVect = BABYLON.Tmp.Vector3[8];
  59169. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  59170. x = tmpVect.x;
  59171. z = tmpVect.z;
  59172. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  59173. return this.position.y;
  59174. }
  59175. if (!this._heightQuads || this._heightQuads.length == 0) {
  59176. this._initHeightQuads();
  59177. this._computeHeightQuads();
  59178. }
  59179. var facet = this._getFacetAt(x, z);
  59180. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  59181. // return y in the World system
  59182. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  59183. return tmpVect.y;
  59184. };
  59185. /**
  59186. * Returns a normalized vector (Vector3) orthogonal to the ground
  59187. * at the ground coordinates (x, z) expressed in the World system.
  59188. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  59189. */
  59190. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  59191. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  59192. this.getNormalAtCoordinatesToRef(x, z, normal);
  59193. return normal;
  59194. };
  59195. /**
  59196. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  59197. * at the ground coordinates (x, z) expressed in the World system.
  59198. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  59199. * Returns the GroundMesh.
  59200. */
  59201. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  59202. var world = this.getWorldMatrix();
  59203. var tmpMat = BABYLON.Tmp.Matrix[5];
  59204. world.invertToRef(tmpMat);
  59205. var tmpVect = BABYLON.Tmp.Vector3[8];
  59206. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  59207. x = tmpVect.x;
  59208. z = tmpVect.z;
  59209. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  59210. return this;
  59211. }
  59212. if (!this._heightQuads || this._heightQuads.length == 0) {
  59213. this._initHeightQuads();
  59214. this._computeHeightQuads();
  59215. }
  59216. var facet = this._getFacetAt(x, z);
  59217. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  59218. return this;
  59219. };
  59220. /**
  59221. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  59222. * if the ground has been updated.
  59223. * This can be used in the render loop.
  59224. * Returns the GroundMesh.
  59225. */
  59226. GroundMesh.prototype.updateCoordinateHeights = function () {
  59227. if (!this._heightQuads || this._heightQuads.length == 0) {
  59228. this._initHeightQuads();
  59229. }
  59230. this._computeHeightQuads();
  59231. return this;
  59232. };
  59233. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  59234. GroundMesh.prototype._getFacetAt = function (x, z) {
  59235. // retrieve col and row from x, z coordinates in the ground local system
  59236. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  59237. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  59238. var quad = this._heightQuads[row * this._subdivisionsX + col];
  59239. var facet;
  59240. if (z < quad.slope.x * x + quad.slope.y) {
  59241. facet = quad.facet1;
  59242. }
  59243. else {
  59244. facet = quad.facet2;
  59245. }
  59246. return facet;
  59247. };
  59248. // Creates and populates the heightMap array with "facet" elements :
  59249. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  59250. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  59251. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  59252. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  59253. // Returns the GroundMesh.
  59254. GroundMesh.prototype._initHeightQuads = function () {
  59255. var subdivisionsX = this._subdivisionsX;
  59256. var subdivisionsY = this._subdivisionsY;
  59257. this._heightQuads = new Array();
  59258. for (var row = 0; row < subdivisionsY; row++) {
  59259. for (var col = 0; col < subdivisionsX; col++) {
  59260. 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) };
  59261. this._heightQuads[row * subdivisionsX + col] = quad;
  59262. }
  59263. }
  59264. return this;
  59265. };
  59266. // Compute each quad element values and update the the heightMap array :
  59267. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  59268. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  59269. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  59270. // Returns the GroundMesh.
  59271. GroundMesh.prototype._computeHeightQuads = function () {
  59272. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  59273. if (!positions) {
  59274. return this;
  59275. }
  59276. var v1 = BABYLON.Tmp.Vector3[3];
  59277. var v2 = BABYLON.Tmp.Vector3[2];
  59278. var v3 = BABYLON.Tmp.Vector3[1];
  59279. var v4 = BABYLON.Tmp.Vector3[0];
  59280. var v1v2 = BABYLON.Tmp.Vector3[4];
  59281. var v1v3 = BABYLON.Tmp.Vector3[5];
  59282. var v1v4 = BABYLON.Tmp.Vector3[6];
  59283. var norm1 = BABYLON.Tmp.Vector3[7];
  59284. var norm2 = BABYLON.Tmp.Vector3[8];
  59285. var i = 0;
  59286. var j = 0;
  59287. var k = 0;
  59288. var cd = 0; // 2D slope coefficient : z = cd * x + h
  59289. var h = 0;
  59290. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  59291. var d2 = 0;
  59292. var subdivisionsX = this._subdivisionsX;
  59293. var subdivisionsY = this._subdivisionsY;
  59294. for (var row = 0; row < subdivisionsY; row++) {
  59295. for (var col = 0; col < subdivisionsX; col++) {
  59296. i = col * 3;
  59297. j = row * (subdivisionsX + 1) * 3;
  59298. k = (row + 1) * (subdivisionsX + 1) * 3;
  59299. v1.x = positions[j + i];
  59300. v1.y = positions[j + i + 1];
  59301. v1.z = positions[j + i + 2];
  59302. v2.x = positions[j + i + 3];
  59303. v2.y = positions[j + i + 4];
  59304. v2.z = positions[j + i + 5];
  59305. v3.x = positions[k + i];
  59306. v3.y = positions[k + i + 1];
  59307. v3.z = positions[k + i + 2];
  59308. v4.x = positions[k + i + 3];
  59309. v4.y = positions[k + i + 4];
  59310. v4.z = positions[k + i + 5];
  59311. // 2D slope V1V4
  59312. cd = (v4.z - v1.z) / (v4.x - v1.x);
  59313. h = v1.z - cd * v1.x; // v1 belongs to the slope
  59314. // facet equations :
  59315. // we compute each facet normal vector
  59316. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  59317. // we compute the value d by applying the equation to v1 which belongs to the plane
  59318. // then we store the facet equation in a Vector4
  59319. v2.subtractToRef(v1, v1v2);
  59320. v3.subtractToRef(v1, v1v3);
  59321. v4.subtractToRef(v1, v1v4);
  59322. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  59323. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  59324. norm1.normalize();
  59325. norm2.normalize();
  59326. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  59327. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  59328. var quad = this._heightQuads[row * subdivisionsX + col];
  59329. quad.slope.copyFromFloats(cd, h);
  59330. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  59331. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  59332. }
  59333. }
  59334. return this;
  59335. };
  59336. GroundMesh.prototype.serialize = function (serializationObject) {
  59337. _super.prototype.serialize.call(this, serializationObject);
  59338. serializationObject.subdivisionsX = this._subdivisionsX;
  59339. serializationObject.subdivisionsY = this._subdivisionsY;
  59340. serializationObject.minX = this._minX;
  59341. serializationObject.maxX = this._maxX;
  59342. serializationObject.minZ = this._minZ;
  59343. serializationObject.maxZ = this._maxZ;
  59344. serializationObject.width = this._width;
  59345. serializationObject.height = this._height;
  59346. };
  59347. GroundMesh.Parse = function (parsedMesh, scene) {
  59348. var result = new GroundMesh(parsedMesh.name, scene);
  59349. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  59350. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  59351. result._minX = parsedMesh.minX;
  59352. result._maxX = parsedMesh.maxX;
  59353. result._minZ = parsedMesh.minZ;
  59354. result._maxZ = parsedMesh.maxZ;
  59355. result._width = parsedMesh.width;
  59356. result._height = parsedMesh.height;
  59357. return result;
  59358. };
  59359. return GroundMesh;
  59360. }(BABYLON.Mesh));
  59361. BABYLON.GroundMesh = GroundMesh;
  59362. })(BABYLON || (BABYLON = {}));
  59363. //# sourceMappingURL=babylon.groundMesh.js.map
  59364. var BABYLON;
  59365. (function (BABYLON) {
  59366. /**
  59367. * Creates an instance based on a source mesh.
  59368. */
  59369. var InstancedMesh = /** @class */ (function (_super) {
  59370. __extends(InstancedMesh, _super);
  59371. function InstancedMesh(name, source) {
  59372. var _this = _super.call(this, name, source.getScene()) || this;
  59373. source.instances.push(_this);
  59374. _this._sourceMesh = source;
  59375. _this.position.copyFrom(source.position);
  59376. _this.rotation.copyFrom(source.rotation);
  59377. _this.scaling.copyFrom(source.scaling);
  59378. if (source.rotationQuaternion) {
  59379. _this.rotationQuaternion = source.rotationQuaternion.clone();
  59380. }
  59381. _this.infiniteDistance = source.infiniteDistance;
  59382. _this.setPivotMatrix(source.getPivotMatrix());
  59383. _this.refreshBoundingInfo();
  59384. _this._syncSubMeshes();
  59385. return _this;
  59386. }
  59387. /**
  59388. * Returns the string "InstancedMesh".
  59389. */
  59390. InstancedMesh.prototype.getClassName = function () {
  59391. return "InstancedMesh";
  59392. };
  59393. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  59394. // Methods
  59395. get: function () {
  59396. return this._sourceMesh.receiveShadows;
  59397. },
  59398. enumerable: true,
  59399. configurable: true
  59400. });
  59401. Object.defineProperty(InstancedMesh.prototype, "material", {
  59402. get: function () {
  59403. return this._sourceMesh.material;
  59404. },
  59405. enumerable: true,
  59406. configurable: true
  59407. });
  59408. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  59409. get: function () {
  59410. return this._sourceMesh.visibility;
  59411. },
  59412. enumerable: true,
  59413. configurable: true
  59414. });
  59415. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  59416. get: function () {
  59417. return this._sourceMesh.skeleton;
  59418. },
  59419. enumerable: true,
  59420. configurable: true
  59421. });
  59422. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  59423. get: function () {
  59424. return this._sourceMesh.renderingGroupId;
  59425. },
  59426. set: function (value) {
  59427. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  59428. return;
  59429. }
  59430. //no-op with warning
  59431. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  59432. },
  59433. enumerable: true,
  59434. configurable: true
  59435. });
  59436. /**
  59437. * Returns the total number of vertices (integer).
  59438. */
  59439. InstancedMesh.prototype.getTotalVertices = function () {
  59440. return this._sourceMesh.getTotalVertices();
  59441. };
  59442. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  59443. get: function () {
  59444. return this._sourceMesh;
  59445. },
  59446. enumerable: true,
  59447. configurable: true
  59448. });
  59449. /**
  59450. * Is this node ready to be used/rendered
  59451. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  59452. * @return {boolean} is it ready
  59453. */
  59454. InstancedMesh.prototype.isReady = function (completeCheck) {
  59455. if (completeCheck === void 0) { completeCheck = false; }
  59456. return this._sourceMesh.isReady(completeCheck, true);
  59457. };
  59458. /**
  59459. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  59460. */
  59461. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  59462. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  59463. };
  59464. /**
  59465. * Sets the vertex data of the mesh geometry for the requested `kind`.
  59466. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  59467. * The `data` are either a numeric array either a Float32Array.
  59468. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  59469. * 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).
  59470. * Note that a new underlying VertexBuffer object is created each call.
  59471. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  59472. *
  59473. * Possible `kind` values :
  59474. * - BABYLON.VertexBuffer.PositionKind
  59475. * - BABYLON.VertexBuffer.UVKind
  59476. * - BABYLON.VertexBuffer.UV2Kind
  59477. * - BABYLON.VertexBuffer.UV3Kind
  59478. * - BABYLON.VertexBuffer.UV4Kind
  59479. * - BABYLON.VertexBuffer.UV5Kind
  59480. * - BABYLON.VertexBuffer.UV6Kind
  59481. * - BABYLON.VertexBuffer.ColorKind
  59482. * - BABYLON.VertexBuffer.MatricesIndicesKind
  59483. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  59484. * - BABYLON.VertexBuffer.MatricesWeightsKind
  59485. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  59486. *
  59487. * Returns the Mesh.
  59488. */
  59489. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  59490. if (this.sourceMesh) {
  59491. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  59492. }
  59493. return this.sourceMesh;
  59494. };
  59495. /**
  59496. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  59497. * If the mesh has no geometry, it is simply returned as it is.
  59498. * The `data` are either a numeric array either a Float32Array.
  59499. * No new underlying VertexBuffer object is created.
  59500. * 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.
  59501. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  59502. *
  59503. * Possible `kind` values :
  59504. * - BABYLON.VertexBuffer.PositionKind
  59505. * - BABYLON.VertexBuffer.UVKind
  59506. * - BABYLON.VertexBuffer.UV2Kind
  59507. * - BABYLON.VertexBuffer.UV3Kind
  59508. * - BABYLON.VertexBuffer.UV4Kind
  59509. * - BABYLON.VertexBuffer.UV5Kind
  59510. * - BABYLON.VertexBuffer.UV6Kind
  59511. * - BABYLON.VertexBuffer.ColorKind
  59512. * - BABYLON.VertexBuffer.MatricesIndicesKind
  59513. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  59514. * - BABYLON.VertexBuffer.MatricesWeightsKind
  59515. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  59516. *
  59517. * Returns the Mesh.
  59518. */
  59519. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  59520. if (this.sourceMesh) {
  59521. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  59522. }
  59523. return this.sourceMesh;
  59524. };
  59525. /**
  59526. * Sets the mesh indices.
  59527. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  59528. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  59529. * This method creates a new index buffer each call.
  59530. * Returns the Mesh.
  59531. */
  59532. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  59533. if (totalVertices === void 0) { totalVertices = null; }
  59534. if (this.sourceMesh) {
  59535. this.sourceMesh.setIndices(indices, totalVertices);
  59536. }
  59537. return this.sourceMesh;
  59538. };
  59539. /**
  59540. * Boolean : True if the mesh owns the requested kind of data.
  59541. */
  59542. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  59543. return this._sourceMesh.isVerticesDataPresent(kind);
  59544. };
  59545. /**
  59546. * Returns an array of indices (IndicesArray).
  59547. */
  59548. InstancedMesh.prototype.getIndices = function () {
  59549. return this._sourceMesh.getIndices();
  59550. };
  59551. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  59552. get: function () {
  59553. return this._sourceMesh._positions;
  59554. },
  59555. enumerable: true,
  59556. configurable: true
  59557. });
  59558. /**
  59559. * Sets a new updated BoundingInfo to the mesh.
  59560. * Returns the mesh.
  59561. */
  59562. InstancedMesh.prototype.refreshBoundingInfo = function () {
  59563. var meshBB = this._sourceMesh.getBoundingInfo();
  59564. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  59565. this._updateBoundingInfo();
  59566. return this;
  59567. };
  59568. InstancedMesh.prototype._preActivate = function () {
  59569. if (this._currentLOD) {
  59570. this._currentLOD._preActivate();
  59571. }
  59572. return this;
  59573. };
  59574. InstancedMesh.prototype._activate = function (renderId) {
  59575. if (this._currentLOD) {
  59576. this._currentLOD._registerInstanceForRenderId(this, renderId);
  59577. }
  59578. return this;
  59579. };
  59580. /**
  59581. * Returns the current associated LOD AbstractMesh.
  59582. */
  59583. InstancedMesh.prototype.getLOD = function (camera) {
  59584. if (!camera) {
  59585. return this;
  59586. }
  59587. var boundingInfo = this.getBoundingInfo();
  59588. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  59589. if (this._currentLOD === this.sourceMesh) {
  59590. return this;
  59591. }
  59592. return this._currentLOD;
  59593. };
  59594. InstancedMesh.prototype._syncSubMeshes = function () {
  59595. this.releaseSubMeshes();
  59596. if (this._sourceMesh.subMeshes) {
  59597. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  59598. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  59599. }
  59600. }
  59601. return this;
  59602. };
  59603. InstancedMesh.prototype._generatePointsArray = function () {
  59604. return this._sourceMesh._generatePointsArray();
  59605. };
  59606. /**
  59607. * Creates a new InstancedMesh from the current mesh.
  59608. * - name (string) : the cloned mesh name
  59609. * - newParent (optional Node) : the optional Node to parent the clone to.
  59610. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  59611. *
  59612. * Returns the clone.
  59613. */
  59614. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  59615. var result = this._sourceMesh.createInstance(name);
  59616. // Deep copy
  59617. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  59618. // Bounding info
  59619. this.refreshBoundingInfo();
  59620. // Parent
  59621. if (newParent) {
  59622. result.parent = newParent;
  59623. }
  59624. if (!doNotCloneChildren) {
  59625. // Children
  59626. for (var index = 0; index < this.getScene().meshes.length; index++) {
  59627. var mesh = this.getScene().meshes[index];
  59628. if (mesh.parent === this) {
  59629. mesh.clone(mesh.name, result);
  59630. }
  59631. }
  59632. }
  59633. result.computeWorldMatrix(true);
  59634. return result;
  59635. };
  59636. /**
  59637. * Disposes the InstancedMesh.
  59638. * Returns nothing.
  59639. */
  59640. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  59641. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  59642. // Remove from mesh
  59643. var index = this._sourceMesh.instances.indexOf(this);
  59644. this._sourceMesh.instances.splice(index, 1);
  59645. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  59646. };
  59647. return InstancedMesh;
  59648. }(BABYLON.AbstractMesh));
  59649. BABYLON.InstancedMesh = InstancedMesh;
  59650. })(BABYLON || (BABYLON = {}));
  59651. //# sourceMappingURL=babylon.instancedMesh.js.map
  59652. var BABYLON;
  59653. (function (BABYLON) {
  59654. var LinesMesh = /** @class */ (function (_super) {
  59655. __extends(LinesMesh, _super);
  59656. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  59657. if (scene === void 0) { scene = null; }
  59658. if (parent === void 0) { parent = null; }
  59659. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  59660. _this.useVertexColor = useVertexColor;
  59661. _this.useVertexAlpha = useVertexAlpha;
  59662. _this.color = new BABYLON.Color3(1, 1, 1);
  59663. _this.alpha = 1;
  59664. if (source) {
  59665. _this.color = source.color.clone();
  59666. _this.alpha = source.alpha;
  59667. _this.useVertexColor = source.useVertexColor;
  59668. _this.useVertexAlpha = source.useVertexAlpha;
  59669. }
  59670. _this._intersectionThreshold = 0.1;
  59671. var defines = [];
  59672. var options = {
  59673. attributes: [BABYLON.VertexBuffer.PositionKind],
  59674. uniforms: ["world", "viewProjection"],
  59675. needAlphaBlending: true,
  59676. defines: defines
  59677. };
  59678. if (useVertexAlpha === false) {
  59679. options.needAlphaBlending = false;
  59680. }
  59681. if (!useVertexColor) {
  59682. options.uniforms.push("color");
  59683. }
  59684. else {
  59685. options.defines.push("#define VERTEXCOLOR");
  59686. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  59687. }
  59688. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  59689. return _this;
  59690. }
  59691. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  59692. /**
  59693. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  59694. * This margin is expressed in world space coordinates, so its value may vary.
  59695. * Default value is 0.1
  59696. * @returns the intersection Threshold value.
  59697. */
  59698. get: function () {
  59699. return this._intersectionThreshold;
  59700. },
  59701. /**
  59702. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  59703. * This margin is expressed in world space coordinates, so its value may vary.
  59704. * @param value the new threshold to apply
  59705. */
  59706. set: function (value) {
  59707. if (this._intersectionThreshold === value) {
  59708. return;
  59709. }
  59710. this._intersectionThreshold = value;
  59711. if (this.geometry) {
  59712. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  59713. }
  59714. },
  59715. enumerable: true,
  59716. configurable: true
  59717. });
  59718. /**
  59719. * Returns the string "LineMesh"
  59720. */
  59721. LinesMesh.prototype.getClassName = function () {
  59722. return "LinesMesh";
  59723. };
  59724. Object.defineProperty(LinesMesh.prototype, "material", {
  59725. get: function () {
  59726. return this._colorShader;
  59727. },
  59728. set: function (value) {
  59729. // Do nothing
  59730. },
  59731. enumerable: true,
  59732. configurable: true
  59733. });
  59734. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  59735. get: function () {
  59736. return false;
  59737. },
  59738. enumerable: true,
  59739. configurable: true
  59740. });
  59741. LinesMesh.prototype.createInstance = function (name) {
  59742. throw new Error("LinesMeshes do not support createInstance.");
  59743. };
  59744. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  59745. if (!this._geometry) {
  59746. return this;
  59747. }
  59748. // VBOs
  59749. this._geometry._bind(this._colorShader.getEffect());
  59750. // Color
  59751. if (!this.useVertexColor) {
  59752. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  59753. }
  59754. return this;
  59755. };
  59756. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  59757. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  59758. return this;
  59759. }
  59760. var engine = this.getScene().getEngine();
  59761. // Draw order
  59762. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  59763. return this;
  59764. };
  59765. LinesMesh.prototype.dispose = function (doNotRecurse) {
  59766. this._colorShader.dispose();
  59767. _super.prototype.dispose.call(this, doNotRecurse);
  59768. };
  59769. /**
  59770. * Returns a new LineMesh object cloned from the current one.
  59771. */
  59772. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  59773. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  59774. };
  59775. return LinesMesh;
  59776. }(BABYLON.Mesh));
  59777. BABYLON.LinesMesh = LinesMesh;
  59778. })(BABYLON || (BABYLON = {}));
  59779. //# sourceMappingURL=babylon.linesMesh.js.map
  59780. var BABYLON;
  59781. (function (BABYLON) {
  59782. /**
  59783. * Class containing static functions to help procedurally build meshes
  59784. */
  59785. var MeshBuilder = /** @class */ (function () {
  59786. function MeshBuilder() {
  59787. }
  59788. MeshBuilder.updateSideOrientation = function (orientation) {
  59789. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  59790. return BABYLON.Mesh.DOUBLESIDE;
  59791. }
  59792. if (orientation === undefined || orientation === null) {
  59793. return BABYLON.Mesh.FRONTSIDE;
  59794. }
  59795. return orientation;
  59796. };
  59797. /**
  59798. * Creates a box mesh
  59799. * * The parameter `size` sets the size (float) of each box side (default 1)
  59800. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`)
  59801. * * 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)
  59802. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  59803. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59804. * * 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
  59805. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  59806. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  59807. * @param name defines the name of the mesh
  59808. * @param options defines the options used to create the mesh
  59809. * @param scene defines the hosting scene
  59810. * @returns the box mesh
  59811. */
  59812. MeshBuilder.CreateBox = function (name, options, scene) {
  59813. if (scene === void 0) { scene = null; }
  59814. var box = new BABYLON.Mesh(name, scene);
  59815. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  59816. box._originalBuilderSideOrientation = options.sideOrientation;
  59817. var vertexData = BABYLON.VertexData.CreateBox(options);
  59818. vertexData.applyToMesh(box, options.updatable);
  59819. return box;
  59820. };
  59821. /**
  59822. * Creates a sphere mesh
  59823. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  59824. * * 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`)
  59825. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  59826. * * 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
  59827. * * 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)
  59828. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59829. * * 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
  59830. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  59831. * @param name defines the name of the mesh
  59832. * @param options defines the options used to create the mesh
  59833. * @param scene defines the hosting scene
  59834. * @returns the sphere mesh
  59835. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  59836. */
  59837. MeshBuilder.CreateSphere = function (name, options, scene) {
  59838. var sphere = new BABYLON.Mesh(name, scene);
  59839. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  59840. sphere._originalBuilderSideOrientation = options.sideOrientation;
  59841. var vertexData = BABYLON.VertexData.CreateSphere(options);
  59842. vertexData.applyToMesh(sphere, options.updatable);
  59843. return sphere;
  59844. };
  59845. /**
  59846. * Creates a plane polygonal mesh. By default, this is a disc
  59847. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  59848. * * 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
  59849. * * 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
  59850. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59851. * * 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
  59852. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  59853. * @param name defines the name of the mesh
  59854. * @param options defines the options used to create the mesh
  59855. * @param scene defines the hosting scene
  59856. * @returns the plane polygonal mesh
  59857. * @see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  59858. */
  59859. MeshBuilder.CreateDisc = function (name, options, scene) {
  59860. if (scene === void 0) { scene = null; }
  59861. var disc = new BABYLON.Mesh(name, scene);
  59862. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  59863. disc._originalBuilderSideOrientation = options.sideOrientation;
  59864. var vertexData = BABYLON.VertexData.CreateDisc(options);
  59865. vertexData.applyToMesh(disc, options.updatable);
  59866. return disc;
  59867. };
  59868. /**
  59869. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  59870. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  59871. * * 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`)
  59872. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  59873. * * 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
  59874. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59875. * * 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
  59876. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  59877. * @param name defines the name of the mesh
  59878. * @param options defines the options used to create the mesh
  59879. * @param scene defines the hosting scene
  59880. * @returns the icosahedron mesh
  59881. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  59882. */
  59883. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  59884. var sphere = new BABYLON.Mesh(name, scene);
  59885. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  59886. sphere._originalBuilderSideOrientation = options.sideOrientation;
  59887. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  59888. vertexData.applyToMesh(sphere, options.updatable);
  59889. return sphere;
  59890. };
  59891. ;
  59892. /**
  59893. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  59894. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  59895. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  59896. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  59897. * * 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
  59898. * * 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
  59899. * * 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
  59900. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59901. * * 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
  59902. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  59903. * * 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
  59904. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  59905. * * 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
  59906. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  59907. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  59908. * @param name defines the name of the mesh
  59909. * @param options defines the options used to create the mesh
  59910. * @param scene defines the hosting scene
  59911. * @returns the ribbon mesh
  59912. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  59913. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  59914. */
  59915. MeshBuilder.CreateRibbon = function (name, options, scene) {
  59916. if (scene === void 0) { scene = null; }
  59917. var pathArray = options.pathArray;
  59918. var closeArray = options.closeArray;
  59919. var closePath = options.closePath;
  59920. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  59921. var instance = options.instance;
  59922. var updatable = options.updatable;
  59923. if (instance) { // existing ribbon instance update
  59924. // positionFunction : ribbon case
  59925. // only pathArray and sideOrientation parameters are taken into account for positions update
  59926. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  59927. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  59928. var positionFunction = function (positions) {
  59929. var minlg = pathArray[0].length;
  59930. var i = 0;
  59931. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  59932. for (var si = 1; si <= ns; si++) {
  59933. for (var p = 0; p < pathArray.length; p++) {
  59934. var path = pathArray[p];
  59935. var l = path.length;
  59936. minlg = (minlg < l) ? minlg : l;
  59937. var j = 0;
  59938. while (j < minlg) {
  59939. positions[i] = path[j].x;
  59940. positions[i + 1] = path[j].y;
  59941. positions[i + 2] = path[j].z;
  59942. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  59943. BABYLON.Tmp.Vector3[0].x = path[j].x;
  59944. }
  59945. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  59946. BABYLON.Tmp.Vector3[1].x = path[j].x;
  59947. }
  59948. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  59949. BABYLON.Tmp.Vector3[0].y = path[j].y;
  59950. }
  59951. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  59952. BABYLON.Tmp.Vector3[1].y = path[j].y;
  59953. }
  59954. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  59955. BABYLON.Tmp.Vector3[0].z = path[j].z;
  59956. }
  59957. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  59958. BABYLON.Tmp.Vector3[1].z = path[j].z;
  59959. }
  59960. j++;
  59961. i += 3;
  59962. }
  59963. if (instance._closePath) {
  59964. positions[i] = path[0].x;
  59965. positions[i + 1] = path[0].y;
  59966. positions[i + 2] = path[0].z;
  59967. i += 3;
  59968. }
  59969. }
  59970. }
  59971. };
  59972. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  59973. positionFunction(positions);
  59974. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  59975. instance._boundingInfo.update(instance._worldMatrix);
  59976. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  59977. if (options.colors) {
  59978. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  59979. for (var c = 0; c < options.colors.length; c++) {
  59980. colors[c * 4] = options.colors[c].r;
  59981. colors[c * 4 + 1] = options.colors[c].g;
  59982. colors[c * 4 + 2] = options.colors[c].b;
  59983. colors[c * 4 + 3] = options.colors[c].a;
  59984. }
  59985. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  59986. }
  59987. if (options.uvs) {
  59988. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  59989. for (var i = 0; i < options.uvs.length; i++) {
  59990. uvs[i * 2] = options.uvs[i].x;
  59991. uvs[i * 2 + 1] = options.uvs[i].y;
  59992. }
  59993. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  59994. }
  59995. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  59996. var indices = instance.getIndices();
  59997. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  59998. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  59999. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  60000. if (instance._closePath) {
  60001. var indexFirst = 0;
  60002. var indexLast = 0;
  60003. for (var p = 0; p < pathArray.length; p++) {
  60004. indexFirst = instance._idx[p] * 3;
  60005. if (p + 1 < pathArray.length) {
  60006. indexLast = (instance._idx[p + 1] - 1) * 3;
  60007. }
  60008. else {
  60009. indexLast = normals.length - 3;
  60010. }
  60011. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  60012. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  60013. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  60014. normals[indexLast] = normals[indexFirst];
  60015. normals[indexLast + 1] = normals[indexFirst + 1];
  60016. normals[indexLast + 2] = normals[indexFirst + 2];
  60017. }
  60018. }
  60019. if (!(instance.areNormalsFrozen)) {
  60020. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  60021. }
  60022. }
  60023. return instance;
  60024. }
  60025. else { // new ribbon creation
  60026. var ribbon = new BABYLON.Mesh(name, scene);
  60027. ribbon._originalBuilderSideOrientation = sideOrientation;
  60028. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  60029. if (closePath) {
  60030. ribbon._idx = vertexData._idx;
  60031. }
  60032. ribbon._closePath = closePath;
  60033. ribbon._closeArray = closeArray;
  60034. vertexData.applyToMesh(ribbon, updatable);
  60035. return ribbon;
  60036. }
  60037. };
  60038. /**
  60039. * Creates a cylinder or a cone mesh
  60040. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  60041. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  60042. * * 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.
  60043. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  60044. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  60045. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  60046. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  60047. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  60048. * * 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).
  60049. * * 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
  60050. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  60051. * * 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
  60052. * * 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.
  60053. * * If `enclose` is false, a ring surface is one element.
  60054. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  60055. * * 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
  60056. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60057. * * 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
  60058. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60059. * @param name defines the name of the mesh
  60060. * @param options defines the options used to create the mesh
  60061. * @param scene defines the hosting scene
  60062. * @returns the cylinder mesh
  60063. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  60064. */
  60065. MeshBuilder.CreateCylinder = function (name, options, scene) {
  60066. var cylinder = new BABYLON.Mesh(name, scene);
  60067. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60068. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  60069. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  60070. vertexData.applyToMesh(cylinder, options.updatable);
  60071. return cylinder;
  60072. };
  60073. /**
  60074. * Creates a torus mesh
  60075. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  60076. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  60077. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  60078. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60079. * * 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
  60080. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60081. * @param name defines the name of the mesh
  60082. * @param options defines the options used to create the mesh
  60083. * @param scene defines the hosting scene
  60084. * @returns the torus mesh
  60085. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  60086. */
  60087. MeshBuilder.CreateTorus = function (name, options, scene) {
  60088. var torus = new BABYLON.Mesh(name, scene);
  60089. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60090. torus._originalBuilderSideOrientation = options.sideOrientation;
  60091. var vertexData = BABYLON.VertexData.CreateTorus(options);
  60092. vertexData.applyToMesh(torus, options.updatable);
  60093. return torus;
  60094. };
  60095. /**
  60096. * Creates a torus knot mesh
  60097. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  60098. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  60099. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  60100. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  60101. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60102. * * 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
  60103. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60104. * @param name defines the name of the mesh
  60105. * @param options defines the options used to create the mesh
  60106. * @param scene defines the hosting scene
  60107. * @returns the torus knot mesh
  60108. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  60109. */
  60110. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  60111. var torusKnot = new BABYLON.Mesh(name, scene);
  60112. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60113. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  60114. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  60115. vertexData.applyToMesh(torusKnot, options.updatable);
  60116. return torusKnot;
  60117. };
  60118. /**
  60119. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  60120. * * 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
  60121. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  60122. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  60123. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  60124. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  60125. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  60126. * * 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
  60127. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  60128. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60129. * @see http://doc.babylonjs.com/how_to/parametric_shapes#line-system
  60130. * @param name defines the name of the new line system
  60131. * @param options defines the options used to create the line system
  60132. * @param scene defines the hosting scene
  60133. * @returns a new line system mesh
  60134. */
  60135. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  60136. var instance = options.instance;
  60137. var lines = options.lines;
  60138. var colors = options.colors;
  60139. if (instance) { // lines update
  60140. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60141. var vertexColor;
  60142. var lineColors;
  60143. if (colors) {
  60144. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  60145. }
  60146. var i = 0;
  60147. var c = 0;
  60148. for (var l = 0; l < lines.length; l++) {
  60149. var points = lines[l];
  60150. for (var p = 0; p < points.length; p++) {
  60151. positions[i] = points[p].x;
  60152. positions[i + 1] = points[p].y;
  60153. positions[i + 2] = points[p].z;
  60154. if (colors && vertexColor) {
  60155. lineColors = colors[l];
  60156. vertexColor[c] = lineColors[p].r;
  60157. vertexColor[c + 1] = lineColors[p].g;
  60158. vertexColor[c + 2] = lineColors[p].b;
  60159. vertexColor[c + 3] = lineColors[p].a;
  60160. c += 4;
  60161. }
  60162. i += 3;
  60163. }
  60164. }
  60165. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  60166. if (colors && vertexColor) {
  60167. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  60168. }
  60169. return instance;
  60170. }
  60171. // line system creation
  60172. var useVertexColor = (colors) ? true : false;
  60173. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  60174. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  60175. vertexData.applyToMesh(lineSystem, options.updatable);
  60176. return lineSystem;
  60177. };
  60178. /**
  60179. * Creates a line mesh
  60180. * 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
  60181. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  60182. * * The parameter `points` is an array successive Vector3
  60183. * * 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
  60184. * * The optional parameter `colors` is an array of successive Color4, one per line point
  60185. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  60186. * * When updating an instance, remember that only point positions can change, not the number of points
  60187. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60188. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lines
  60189. * @param name defines the name of the new line system
  60190. * @param options defines the options used to create the line system
  60191. * @param scene defines the hosting scene
  60192. * @returns a new line mesh
  60193. */
  60194. MeshBuilder.CreateLines = function (name, options, scene) {
  60195. if (scene === void 0) { scene = null; }
  60196. var colors = (options.colors) ? [options.colors] : null;
  60197. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  60198. return lines;
  60199. };
  60200. /**
  60201. * Creates a dashed line mesh
  60202. * * 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
  60203. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  60204. * * The parameter `points` is an array successive Vector3
  60205. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  60206. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  60207. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  60208. * * 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
  60209. * * When updating an instance, remember that only point positions can change, not the number of points
  60210. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60211. * @param name defines the name of the mesh
  60212. * @param options defines the options used to create the mesh
  60213. * @param scene defines the hosting scene
  60214. * @returns the dashed line mesh
  60215. * @see http://doc.babylonjs.com/how_to/parametric_shapes#dashed-lines
  60216. */
  60217. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  60218. if (scene === void 0) { scene = null; }
  60219. var points = options.points;
  60220. var instance = options.instance;
  60221. var gapSize = options.gapSize || 1;
  60222. var dashSize = options.dashSize || 3;
  60223. if (instance) { // dashed lines update
  60224. var positionFunction = function (positions) {
  60225. var curvect = BABYLON.Vector3.Zero();
  60226. var nbSeg = positions.length / 6;
  60227. var lg = 0;
  60228. var nb = 0;
  60229. var shft = 0;
  60230. var dashshft = 0;
  60231. var curshft = 0;
  60232. var p = 0;
  60233. var i = 0;
  60234. var j = 0;
  60235. for (i = 0; i < points.length - 1; i++) {
  60236. points[i + 1].subtractToRef(points[i], curvect);
  60237. lg += curvect.length();
  60238. }
  60239. shft = lg / nbSeg;
  60240. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  60241. for (i = 0; i < points.length - 1; i++) {
  60242. points[i + 1].subtractToRef(points[i], curvect);
  60243. nb = Math.floor(curvect.length() / shft);
  60244. curvect.normalize();
  60245. j = 0;
  60246. while (j < nb && p < positions.length) {
  60247. curshft = shft * j;
  60248. positions[p] = points[i].x + curshft * curvect.x;
  60249. positions[p + 1] = points[i].y + curshft * curvect.y;
  60250. positions[p + 2] = points[i].z + curshft * curvect.z;
  60251. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  60252. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  60253. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  60254. p += 6;
  60255. j++;
  60256. }
  60257. }
  60258. while (p < positions.length) {
  60259. positions[p] = points[i].x;
  60260. positions[p + 1] = points[i].y;
  60261. positions[p + 2] = points[i].z;
  60262. p += 3;
  60263. }
  60264. };
  60265. instance.updateMeshPositions(positionFunction, false);
  60266. return instance;
  60267. }
  60268. // dashed lines creation
  60269. var dashedLines = new BABYLON.LinesMesh(name, scene);
  60270. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  60271. vertexData.applyToMesh(dashedLines, options.updatable);
  60272. dashedLines.dashSize = dashSize;
  60273. dashedLines.gapSize = gapSize;
  60274. return dashedLines;
  60275. };
  60276. /**
  60277. * 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.
  60278. * * 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.
  60279. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  60280. * * 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.
  60281. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  60282. * * 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
  60283. * * 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
  60284. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  60285. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60286. * * 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
  60287. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  60288. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60289. * @param name defines the name of the mesh
  60290. * @param options defines the options used to create the mesh
  60291. * @param scene defines the hosting scene
  60292. * @returns the extruded shape mesh
  60293. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  60294. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  60295. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  60296. */
  60297. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  60298. if (scene === void 0) { scene = null; }
  60299. var path = options.path;
  60300. var shape = options.shape;
  60301. var scale = options.scale || 1;
  60302. var rotation = options.rotation || 0;
  60303. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  60304. var updatable = options.updatable;
  60305. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60306. var instance = options.instance || null;
  60307. var invertUV = options.invertUV || false;
  60308. 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);
  60309. };
  60310. /**
  60311. * Creates an custom extruded shape mesh.
  60312. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  60313. * * 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.
  60314. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  60315. * * 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
  60316. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  60317. * * 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
  60318. * * It must returns a float value that will be the scale value applied to the shape on each path point
  60319. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  60320. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  60321. * * 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
  60322. * * 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
  60323. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  60324. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60325. * * 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
  60326. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  60327. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60328. * @param name defines the name of the mesh
  60329. * @param options defines the options used to create the mesh
  60330. * @param scene defines the hosting scene
  60331. * @returns the custom extruded shape mesh
  60332. * @see http://doc.babylonjs.com/how_to/parametric_shapes#custom-extruded-shapes
  60333. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  60334. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  60335. */
  60336. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  60337. var path = options.path;
  60338. var shape = options.shape;
  60339. var scaleFunction = options.scaleFunction || (function () { return 1; });
  60340. var rotationFunction = options.rotationFunction || (function () { return 0; });
  60341. var ribbonCloseArray = options.ribbonCloseArray || false;
  60342. var ribbonClosePath = options.ribbonClosePath || false;
  60343. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  60344. var updatable = options.updatable;
  60345. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60346. var instance = options.instance;
  60347. var invertUV = options.invertUV || false;
  60348. 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);
  60349. };
  60350. /**
  60351. * Creates lathe mesh.
  60352. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  60353. * * 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
  60354. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  60355. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  60356. * * 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
  60357. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  60358. * * 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
  60359. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60360. * * 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
  60361. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  60362. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60363. * @param name defines the name of the mesh
  60364. * @param options defines the options used to create the mesh
  60365. * @param scene defines the hosting scene
  60366. * @returns the lathe mesh
  60367. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lathe
  60368. */
  60369. MeshBuilder.CreateLathe = function (name, options, scene) {
  60370. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  60371. var closed = (options.closed === undefined) ? true : options.closed;
  60372. var shape = options.shape;
  60373. var radius = options.radius || 1;
  60374. var tessellation = options.tessellation || 64;
  60375. var updatable = options.updatable;
  60376. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60377. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  60378. var pi2 = Math.PI * 2;
  60379. var paths = new Array();
  60380. var invertUV = options.invertUV || false;
  60381. var i = 0;
  60382. var p = 0;
  60383. var step = pi2 / tessellation * arc;
  60384. var rotated;
  60385. var path = new Array();
  60386. for (i = 0; i <= tessellation; i++) {
  60387. var path = [];
  60388. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  60389. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  60390. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  60391. }
  60392. for (p = 0; p < shape.length; p++) {
  60393. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  60394. path.push(rotated);
  60395. }
  60396. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  60397. 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));
  60398. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  60399. }
  60400. paths.push(path);
  60401. }
  60402. // lathe ribbon
  60403. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  60404. return lathe;
  60405. };
  60406. /**
  60407. * Creates a plane mesh
  60408. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  60409. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`)
  60410. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  60411. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60412. * * 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
  60413. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60414. * @param name defines the name of the mesh
  60415. * @param options defines the options used to create the mesh
  60416. * @param scene defines the hosting scene
  60417. * @returns the plane mesh
  60418. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  60419. */
  60420. MeshBuilder.CreatePlane = function (name, options, scene) {
  60421. var plane = new BABYLON.Mesh(name, scene);
  60422. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60423. plane._originalBuilderSideOrientation = options.sideOrientation;
  60424. var vertexData = BABYLON.VertexData.CreatePlane(options);
  60425. vertexData.applyToMesh(plane, options.updatable);
  60426. if (options.sourcePlane) {
  60427. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  60428. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  60429. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  60430. plane.rotate(vectorProduct, product);
  60431. }
  60432. return plane;
  60433. };
  60434. /**
  60435. * Creates a ground mesh
  60436. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  60437. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  60438. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60439. * @param name defines the name of the mesh
  60440. * @param options defines the options used to create the mesh
  60441. * @param scene defines the hosting scene
  60442. * @returns the ground mesh
  60443. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  60444. */
  60445. MeshBuilder.CreateGround = function (name, options, scene) {
  60446. var ground = new BABYLON.GroundMesh(name, scene);
  60447. ground._setReady(false);
  60448. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  60449. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  60450. ground._width = options.width || 1;
  60451. ground._height = options.height || 1;
  60452. ground._maxX = ground._width / 2;
  60453. ground._maxZ = ground._height / 2;
  60454. ground._minX = -ground._maxX;
  60455. ground._minZ = -ground._maxZ;
  60456. var vertexData = BABYLON.VertexData.CreateGround(options);
  60457. vertexData.applyToMesh(ground, options.updatable);
  60458. ground._setReady(true);
  60459. return ground;
  60460. };
  60461. /**
  60462. * Creates a tiled ground mesh
  60463. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  60464. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  60465. * * 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
  60466. * * 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
  60467. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60468. * @param name defines the name of the mesh
  60469. * @param options defines the options used to create the mesh
  60470. * @param scene defines the hosting scene
  60471. * @returns the tiled ground mesh
  60472. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  60473. */
  60474. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  60475. var tiledGround = new BABYLON.Mesh(name, scene);
  60476. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  60477. vertexData.applyToMesh(tiledGround, options.updatable);
  60478. return tiledGround;
  60479. };
  60480. /**
  60481. * Creates a ground mesh from a height map
  60482. * * The parameter `url` sets the URL of the height map image resource.
  60483. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  60484. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  60485. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  60486. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  60487. * * 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.
  60488. * * 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).
  60489. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60490. * @param name defines the name of the mesh
  60491. * @param url defines the url to the height map
  60492. * @param options defines the options used to create the mesh
  60493. * @param scene defines the hosting scene
  60494. * @returns the ground mesh
  60495. * @see http://doc.babylonjs.com/babylon101/height_map
  60496. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  60497. */
  60498. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  60499. var width = options.width || 10.0;
  60500. var height = options.height || 10.0;
  60501. var subdivisions = options.subdivisions || 1 | 0;
  60502. var minHeight = options.minHeight || 0.0;
  60503. var maxHeight = options.maxHeight || 1.0;
  60504. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  60505. var updatable = options.updatable;
  60506. var onReady = options.onReady;
  60507. var ground = new BABYLON.GroundMesh(name, scene);
  60508. ground._subdivisionsX = subdivisions;
  60509. ground._subdivisionsY = subdivisions;
  60510. ground._width = width;
  60511. ground._height = height;
  60512. ground._maxX = ground._width / 2.0;
  60513. ground._maxZ = ground._height / 2.0;
  60514. ground._minX = -ground._maxX;
  60515. ground._minZ = -ground._maxZ;
  60516. ground._setReady(false);
  60517. var onload = function (img) {
  60518. // Getting height map data
  60519. var canvas = document.createElement("canvas");
  60520. var context = canvas.getContext("2d");
  60521. if (!context) {
  60522. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  60523. }
  60524. if (scene.isDisposed) {
  60525. return;
  60526. }
  60527. var bufferWidth = img.width;
  60528. var bufferHeight = img.height;
  60529. canvas.width = bufferWidth;
  60530. canvas.height = bufferHeight;
  60531. context.drawImage(img, 0, 0);
  60532. // Create VertexData from map data
  60533. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  60534. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  60535. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  60536. width: width, height: height,
  60537. subdivisions: subdivisions,
  60538. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  60539. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  60540. });
  60541. vertexData.applyToMesh(ground, updatable);
  60542. //execute ready callback, if set
  60543. if (onReady) {
  60544. onReady(ground);
  60545. }
  60546. ground._setReady(true);
  60547. };
  60548. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  60549. return ground;
  60550. };
  60551. /**
  60552. * Creates a polygon mesh
  60553. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  60554. * * 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
  60555. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60556. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60557. * * 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)
  60558. * * Remember you can only change the shape positions, not their number when updating a polygon
  60559. * @param name defines the name of the mesh
  60560. * @param options defines the options used to create the mesh
  60561. * @param scene defines the hosting scene
  60562. * @returns the polygon mesh
  60563. */
  60564. MeshBuilder.CreatePolygon = function (name, options, scene) {
  60565. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60566. var shape = options.shape;
  60567. var holes = options.holes || [];
  60568. var depth = options.depth || 0;
  60569. var contours = [];
  60570. var hole = [];
  60571. for (var i = 0; i < shape.length; i++) {
  60572. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  60573. }
  60574. var epsilon = 0.00000001;
  60575. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  60576. contours.pop();
  60577. }
  60578. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  60579. for (var hNb = 0; hNb < holes.length; hNb++) {
  60580. hole = [];
  60581. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  60582. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  60583. }
  60584. polygonTriangulation.addHole(hole);
  60585. }
  60586. var polygon = polygonTriangulation.build(options.updatable, depth);
  60587. polygon._originalBuilderSideOrientation = options.sideOrientation;
  60588. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  60589. vertexData.applyToMesh(polygon, options.updatable);
  60590. return polygon;
  60591. };
  60592. ;
  60593. /**
  60594. * Creates an extruded polygon mesh, with depth in the Y direction.
  60595. * * 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)
  60596. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  60597. * @param name defines the name of the mesh
  60598. * @param options defines the options used to create the mesh
  60599. * @param scene defines the hosting scene
  60600. * @returns the polygon mesh
  60601. */
  60602. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  60603. return MeshBuilder.CreatePolygon(name, options, scene);
  60604. };
  60605. ;
  60606. /**
  60607. * Creates a tube mesh.
  60608. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  60609. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  60610. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  60611. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  60612. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  60613. * * 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)
  60614. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  60615. * * 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
  60616. * * 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
  60617. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60618. * * 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
  60619. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  60620. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60621. * @param name defines the name of the mesh
  60622. * @param options defines the options used to create the mesh
  60623. * @param scene defines the hosting scene
  60624. * @returns the tube mesh
  60625. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  60626. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  60627. */
  60628. MeshBuilder.CreateTube = function (name, options, scene) {
  60629. var path = options.path;
  60630. var instance = options.instance;
  60631. var radius = 1.0;
  60632. if (instance) {
  60633. radius = instance.radius;
  60634. }
  60635. if (options.radius !== undefined) {
  60636. radius = options.radius;
  60637. }
  60638. ;
  60639. var tessellation = options.tessellation || 64 | 0;
  60640. var radiusFunction = options.radiusFunction || null;
  60641. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  60642. var invertUV = options.invertUV || false;
  60643. var updatable = options.updatable;
  60644. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60645. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  60646. // tube geometry
  60647. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  60648. var tangents = path3D.getTangents();
  60649. var normals = path3D.getNormals();
  60650. var distances = path3D.getDistances();
  60651. var pi2 = Math.PI * 2;
  60652. var step = pi2 / tessellation * arc;
  60653. var returnRadius = function () { return radius; };
  60654. var radiusFunctionFinal = radiusFunction || returnRadius;
  60655. var circlePath;
  60656. var rad;
  60657. var normal;
  60658. var rotated;
  60659. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  60660. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  60661. for (var i = 0; i < path.length; i++) {
  60662. rad = radiusFunctionFinal(i, distances[i]); // current radius
  60663. circlePath = Array(); // current circle array
  60664. normal = normals[i]; // current normal
  60665. for (var t = 0; t < tessellation; t++) {
  60666. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  60667. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  60668. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  60669. rotated.scaleInPlace(rad).addInPlace(path[i]);
  60670. circlePath[t] = rotated;
  60671. }
  60672. circlePaths[index] = circlePath;
  60673. index++;
  60674. }
  60675. // cap
  60676. var capPath = function (nbPoints, pathIndex) {
  60677. var pointCap = Array();
  60678. for (var i = 0; i < nbPoints; i++) {
  60679. pointCap.push(path[pathIndex]);
  60680. }
  60681. return pointCap;
  60682. };
  60683. switch (cap) {
  60684. case BABYLON.Mesh.NO_CAP:
  60685. break;
  60686. case BABYLON.Mesh.CAP_START:
  60687. circlePaths[0] = capPath(tessellation, 0);
  60688. circlePaths[1] = circlePaths[2].slice(0);
  60689. break;
  60690. case BABYLON.Mesh.CAP_END:
  60691. circlePaths[index] = circlePaths[index - 1].slice(0);
  60692. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  60693. break;
  60694. case BABYLON.Mesh.CAP_ALL:
  60695. circlePaths[0] = capPath(tessellation, 0);
  60696. circlePaths[1] = circlePaths[2].slice(0);
  60697. circlePaths[index] = circlePaths[index - 1].slice(0);
  60698. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  60699. break;
  60700. default:
  60701. break;
  60702. }
  60703. return circlePaths;
  60704. };
  60705. var path3D;
  60706. var pathArray;
  60707. if (instance) { // tube update
  60708. var arc = options.arc || instance.arc;
  60709. path3D = (instance.path3D).update(path);
  60710. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  60711. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  60712. instance.path3D = path3D;
  60713. instance.pathArray = pathArray;
  60714. instance.arc = arc;
  60715. instance.radius = radius;
  60716. return instance;
  60717. }
  60718. // tube creation
  60719. path3D = new BABYLON.Path3D(path);
  60720. var newPathArray = new Array();
  60721. cap = (cap < 0 || cap > 3) ? 0 : cap;
  60722. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  60723. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  60724. tube.pathArray = pathArray;
  60725. tube.path3D = path3D;
  60726. tube.tessellation = tessellation;
  60727. tube.cap = cap;
  60728. tube.arc = options.arc;
  60729. tube.radius = radius;
  60730. return tube;
  60731. };
  60732. /**
  60733. * Creates a polyhedron mesh
  60734. * * 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
  60735. * * The parameter `size` (positive float, default 1) sets the polygon size
  60736. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  60737. * * 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`
  60738. * * 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
  60739. * * 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)`)
  60740. * * 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
  60741. * * 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
  60742. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60743. * * 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
  60744. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60745. * @param name defines the name of the mesh
  60746. * @param options defines the options used to create the mesh
  60747. * @param scene defines the hosting scene
  60748. * @returns the polyhedron mesh
  60749. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes
  60750. */
  60751. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  60752. var polyhedron = new BABYLON.Mesh(name, scene);
  60753. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60754. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  60755. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  60756. vertexData.applyToMesh(polyhedron, options.updatable);
  60757. return polyhedron;
  60758. };
  60759. /**
  60760. * Creates a decal mesh.
  60761. * 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
  60762. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  60763. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  60764. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  60765. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  60766. * @param name defines the name of the mesh
  60767. * @param sourceMesh defines the mesh where the decal must be applied
  60768. * @param options defines the options used to create the mesh
  60769. * @param scene defines the hosting scene
  60770. * @returns the decal mesh
  60771. * @see http://doc.babylonjs.com/how_to/decals
  60772. */
  60773. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  60774. var indices = sourceMesh.getIndices();
  60775. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60776. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  60777. var position = options.position || BABYLON.Vector3.Zero();
  60778. var normal = options.normal || BABYLON.Vector3.Up();
  60779. var size = options.size || BABYLON.Vector3.One();
  60780. var angle = options.angle || 0;
  60781. // Getting correct rotation
  60782. if (!normal) {
  60783. var target = new BABYLON.Vector3(0, 0, 1);
  60784. var camera = sourceMesh.getScene().activeCamera;
  60785. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  60786. normal = camera.globalPosition.subtract(cameraWorldTarget);
  60787. }
  60788. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  60789. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  60790. var pitch = Math.atan2(normal.y, len);
  60791. // Matrix
  60792. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  60793. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  60794. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  60795. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  60796. var vertexData = new BABYLON.VertexData();
  60797. vertexData.indices = [];
  60798. vertexData.positions = [];
  60799. vertexData.normals = [];
  60800. vertexData.uvs = [];
  60801. var currentVertexDataIndex = 0;
  60802. var extractDecalVector3 = function (indexId) {
  60803. var result = new BABYLON.PositionNormalVertex();
  60804. if (!indices || !positions || !normals) {
  60805. return result;
  60806. }
  60807. var vertexId = indices[indexId];
  60808. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  60809. // Send vector to decal local world
  60810. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  60811. // Get normal
  60812. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  60813. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  60814. return result;
  60815. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  60816. var clip = function (vertices, axis) {
  60817. if (vertices.length === 0) {
  60818. return vertices;
  60819. }
  60820. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  60821. var clipVertices = function (v0, v1) {
  60822. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  60823. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  60824. };
  60825. var result = new Array();
  60826. for (var index = 0; index < vertices.length; index += 3) {
  60827. var v1Out;
  60828. var v2Out;
  60829. var v3Out;
  60830. var total = 0;
  60831. var nV1 = null;
  60832. var nV2 = null;
  60833. var nV3 = null;
  60834. var nV4 = null;
  60835. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  60836. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  60837. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  60838. v1Out = d1 > 0;
  60839. v2Out = d2 > 0;
  60840. v3Out = d3 > 0;
  60841. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  60842. switch (total) {
  60843. case 0:
  60844. result.push(vertices[index]);
  60845. result.push(vertices[index + 1]);
  60846. result.push(vertices[index + 2]);
  60847. break;
  60848. case 1:
  60849. if (v1Out) {
  60850. nV1 = vertices[index + 1];
  60851. nV2 = vertices[index + 2];
  60852. nV3 = clipVertices(vertices[index], nV1);
  60853. nV4 = clipVertices(vertices[index], nV2);
  60854. }
  60855. if (v2Out) {
  60856. nV1 = vertices[index];
  60857. nV2 = vertices[index + 2];
  60858. nV3 = clipVertices(vertices[index + 1], nV1);
  60859. nV4 = clipVertices(vertices[index + 1], nV2);
  60860. result.push(nV3);
  60861. result.push(nV2.clone());
  60862. result.push(nV1.clone());
  60863. result.push(nV2.clone());
  60864. result.push(nV3.clone());
  60865. result.push(nV4);
  60866. break;
  60867. }
  60868. if (v3Out) {
  60869. nV1 = vertices[index];
  60870. nV2 = vertices[index + 1];
  60871. nV3 = clipVertices(vertices[index + 2], nV1);
  60872. nV4 = clipVertices(vertices[index + 2], nV2);
  60873. }
  60874. if (nV1 && nV2 && nV3 && nV4) {
  60875. result.push(nV1.clone());
  60876. result.push(nV2.clone());
  60877. result.push(nV3);
  60878. result.push(nV4);
  60879. result.push(nV3.clone());
  60880. result.push(nV2.clone());
  60881. }
  60882. break;
  60883. case 2:
  60884. if (!v1Out) {
  60885. nV1 = vertices[index].clone();
  60886. nV2 = clipVertices(nV1, vertices[index + 1]);
  60887. nV3 = clipVertices(nV1, vertices[index + 2]);
  60888. result.push(nV1);
  60889. result.push(nV2);
  60890. result.push(nV3);
  60891. }
  60892. if (!v2Out) {
  60893. nV1 = vertices[index + 1].clone();
  60894. nV2 = clipVertices(nV1, vertices[index + 2]);
  60895. nV3 = clipVertices(nV1, vertices[index]);
  60896. result.push(nV1);
  60897. result.push(nV2);
  60898. result.push(nV3);
  60899. }
  60900. if (!v3Out) {
  60901. nV1 = vertices[index + 2].clone();
  60902. nV2 = clipVertices(nV1, vertices[index]);
  60903. nV3 = clipVertices(nV1, vertices[index + 1]);
  60904. result.push(nV1);
  60905. result.push(nV2);
  60906. result.push(nV3);
  60907. }
  60908. break;
  60909. case 3:
  60910. break;
  60911. }
  60912. }
  60913. return result;
  60914. };
  60915. for (var index = 0; index < indices.length; index += 3) {
  60916. var faceVertices = new Array();
  60917. faceVertices.push(extractDecalVector3(index));
  60918. faceVertices.push(extractDecalVector3(index + 1));
  60919. faceVertices.push(extractDecalVector3(index + 2));
  60920. // Clip
  60921. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  60922. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  60923. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  60924. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  60925. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  60926. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  60927. if (faceVertices.length === 0) {
  60928. continue;
  60929. }
  60930. // Add UVs and get back to world
  60931. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  60932. var vertex = faceVertices[vIndex];
  60933. //TODO check for Int32Array | Uint32Array | Uint16Array
  60934. vertexData.indices.push(currentVertexDataIndex);
  60935. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  60936. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  60937. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  60938. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  60939. currentVertexDataIndex++;
  60940. }
  60941. }
  60942. // Return mesh
  60943. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  60944. vertexData.applyToMesh(decal);
  60945. decal.position = position.clone();
  60946. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  60947. return decal;
  60948. };
  60949. // Privates
  60950. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  60951. // extrusion geometry
  60952. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  60953. var tangents = path3D.getTangents();
  60954. var normals = path3D.getNormals();
  60955. var binormals = path3D.getBinormals();
  60956. var distances = path3D.getDistances();
  60957. var angle = 0;
  60958. var returnScale = function () { return scale !== null ? scale : 1; };
  60959. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  60960. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  60961. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  60962. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  60963. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  60964. for (var i = 0; i < curve.length; i++) {
  60965. var shapePath = new Array();
  60966. var angleStep = rotate(i, distances[i]);
  60967. var scaleRatio = scl(i, distances[i]);
  60968. for (var p = 0; p < shape.length; p++) {
  60969. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  60970. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  60971. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  60972. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  60973. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  60974. shapePath[p] = rotated;
  60975. }
  60976. shapePaths[index] = shapePath;
  60977. angle += angleStep;
  60978. index++;
  60979. }
  60980. // cap
  60981. var capPath = function (shapePath) {
  60982. var pointCap = Array();
  60983. var barycenter = BABYLON.Vector3.Zero();
  60984. var i;
  60985. for (i = 0; i < shapePath.length; i++) {
  60986. barycenter.addInPlace(shapePath[i]);
  60987. }
  60988. barycenter.scaleInPlace(1.0 / shapePath.length);
  60989. for (i = 0; i < shapePath.length; i++) {
  60990. pointCap.push(barycenter);
  60991. }
  60992. return pointCap;
  60993. };
  60994. switch (cap) {
  60995. case BABYLON.Mesh.NO_CAP:
  60996. break;
  60997. case BABYLON.Mesh.CAP_START:
  60998. shapePaths[0] = capPath(shapePaths[2]);
  60999. shapePaths[1] = shapePaths[2];
  61000. break;
  61001. case BABYLON.Mesh.CAP_END:
  61002. shapePaths[index] = shapePaths[index - 1];
  61003. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  61004. break;
  61005. case BABYLON.Mesh.CAP_ALL:
  61006. shapePaths[0] = capPath(shapePaths[2]);
  61007. shapePaths[1] = shapePaths[2];
  61008. shapePaths[index] = shapePaths[index - 1];
  61009. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  61010. break;
  61011. default:
  61012. break;
  61013. }
  61014. return shapePaths;
  61015. };
  61016. var path3D;
  61017. var pathArray;
  61018. if (instance) { // instance update
  61019. path3D = (instance.path3D).update(curve);
  61020. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  61021. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  61022. return instance;
  61023. }
  61024. // extruded shape creation
  61025. path3D = new BABYLON.Path3D(curve);
  61026. var newShapePaths = new Array();
  61027. cap = (cap < 0 || cap > 3) ? 0 : cap;
  61028. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  61029. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  61030. extrudedGeneric.pathArray = pathArray;
  61031. extrudedGeneric.path3D = path3D;
  61032. extrudedGeneric.cap = cap;
  61033. return extrudedGeneric;
  61034. };
  61035. return MeshBuilder;
  61036. }());
  61037. BABYLON.MeshBuilder = MeshBuilder;
  61038. })(BABYLON || (BABYLON = {}));
  61039. //# sourceMappingURL=babylon.meshBuilder.js.map
  61040. var BABYLON;
  61041. (function (BABYLON) {
  61042. /**
  61043. * Draco compression (https://google.github.io/draco/)
  61044. *
  61045. * This class wraps the Draco module.
  61046. *
  61047. * **Encoder**
  61048. *
  61049. * The encoder is not currently implemented.
  61050. *
  61051. * **Decoder**
  61052. *
  61053. * By default, the configuration points to a copy of the Draco decoder files for glTF from https://preview.babylonjs.com.
  61054. *
  61055. * To update the configuration, use the following code:
  61056. * ```javascript
  61057. * BABYLON.DracoCompression.Configuration = {
  61058. * decoder: {
  61059. * wasmUrl: "<url to the WebAssembly library>",
  61060. * wasmBinaryUrl: "<url to the WebAssembly binary>",
  61061. * fallbackUrl: "<url to the fallback JavaScript library>",
  61062. * }
  61063. * };
  61064. * ```
  61065. *
  61066. * 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.
  61067. * Decoding will automatically fallback to the JavaScript version if WebAssembly version is not configured or if WebAssembly is not supported by the browser.
  61068. * Use `BABYLON.DracoCompression.DecoderAvailable` to determine if the decoder is available for the current session.
  61069. *
  61070. * To decode Draco compressed data, create a DracoCompression object and call decodeMeshAsync:
  61071. * ```javascript
  61072. * var dracoCompression = new BABYLON.DracoCompression();
  61073. * var vertexData = await dracoCompression.decodeMeshAsync(data, {
  61074. * [BABYLON.VertexBuffer.PositionKind]: 0
  61075. * });
  61076. * ```
  61077. *
  61078. * @see https://www.babylonjs-playground.com/#N3EK4B#0
  61079. */
  61080. var DracoCompression = /** @class */ (function () {
  61081. /**
  61082. * Constructor
  61083. */
  61084. function DracoCompression() {
  61085. }
  61086. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  61087. /**
  61088. * Returns true if the decoder is available.
  61089. */
  61090. get: function () {
  61091. if (typeof DracoDecoderModule !== "undefined") {
  61092. return true;
  61093. }
  61094. var decoder = DracoCompression.Configuration.decoder;
  61095. if (decoder) {
  61096. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  61097. return true;
  61098. }
  61099. if (decoder.fallbackUrl) {
  61100. return true;
  61101. }
  61102. }
  61103. return false;
  61104. },
  61105. enumerable: true,
  61106. configurable: true
  61107. });
  61108. /**
  61109. * Stop all async operations and release resources.
  61110. */
  61111. DracoCompression.prototype.dispose = function () {
  61112. };
  61113. /**
  61114. * Decode Draco compressed mesh data to vertex data.
  61115. * @param data The ArrayBuffer or ArrayBufferView for the Draco compression data
  61116. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  61117. * @returns A promise that resolves with the decoded vertex data
  61118. */
  61119. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  61120. var dataView = data instanceof ArrayBuffer ? new Uint8Array(data) : data;
  61121. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  61122. var module = wrappedModule.module;
  61123. var vertexData = new BABYLON.VertexData();
  61124. var buffer = new module.DecoderBuffer();
  61125. buffer.Init(dataView, dataView.byteLength);
  61126. var decoder = new module.Decoder();
  61127. var geometry;
  61128. var status;
  61129. try {
  61130. var type = decoder.GetEncodedGeometryType(buffer);
  61131. switch (type) {
  61132. case module.TRIANGULAR_MESH:
  61133. geometry = new module.Mesh();
  61134. status = decoder.DecodeBufferToMesh(buffer, geometry);
  61135. break;
  61136. case module.POINT_CLOUD:
  61137. geometry = new module.PointCloud();
  61138. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  61139. break;
  61140. default:
  61141. throw new Error("Invalid geometry type " + type);
  61142. }
  61143. if (!status.ok() || !geometry.ptr) {
  61144. throw new Error(status.error_msg());
  61145. }
  61146. var numPoints = geometry.num_points();
  61147. if (type === module.TRIANGULAR_MESH) {
  61148. var numFaces = geometry.num_faces();
  61149. var faceIndices = new module.DracoInt32Array();
  61150. try {
  61151. var indices = new Uint32Array(numFaces * 3);
  61152. for (var i = 0; i < numFaces; i++) {
  61153. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  61154. var offset = i * 3;
  61155. indices[offset + 0] = faceIndices.GetValue(0);
  61156. indices[offset + 1] = faceIndices.GetValue(1);
  61157. indices[offset + 2] = faceIndices.GetValue(2);
  61158. }
  61159. vertexData.indices = indices;
  61160. }
  61161. finally {
  61162. module.destroy(faceIndices);
  61163. }
  61164. }
  61165. for (var kind in attributes) {
  61166. var uniqueId = attributes[kind];
  61167. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  61168. var dracoData = new module.DracoFloat32Array();
  61169. try {
  61170. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  61171. var babylonData = new Float32Array(numPoints * attribute.num_components());
  61172. for (var i = 0; i < babylonData.length; i++) {
  61173. babylonData[i] = dracoData.GetValue(i);
  61174. }
  61175. vertexData.set(babylonData, kind);
  61176. }
  61177. finally {
  61178. module.destroy(dracoData);
  61179. }
  61180. }
  61181. }
  61182. finally {
  61183. if (geometry) {
  61184. module.destroy(geometry);
  61185. }
  61186. module.destroy(decoder);
  61187. module.destroy(buffer);
  61188. }
  61189. return vertexData;
  61190. });
  61191. };
  61192. DracoCompression._GetDecoderModule = function () {
  61193. if (!DracoCompression._DecoderModulePromise) {
  61194. var promise = null;
  61195. var config_1 = {};
  61196. if (typeof DracoDecoderModule !== "undefined") {
  61197. promise = Promise.resolve();
  61198. }
  61199. else {
  61200. var decoder = DracoCompression.Configuration.decoder;
  61201. if (decoder) {
  61202. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  61203. promise = Promise.all([
  61204. DracoCompression._LoadScriptAsync(decoder.wasmUrl),
  61205. DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {
  61206. config_1.wasmBinary = data;
  61207. })
  61208. ]);
  61209. }
  61210. else if (decoder.fallbackUrl) {
  61211. promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);
  61212. }
  61213. }
  61214. }
  61215. if (!promise) {
  61216. throw new Error("Draco decoder module is not available");
  61217. }
  61218. DracoCompression._DecoderModulePromise = promise.then(function () {
  61219. return new Promise(function (resolve) {
  61220. config_1.onModuleLoaded = function (decoderModule) {
  61221. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  61222. resolve({ module: decoderModule });
  61223. };
  61224. DracoDecoderModule(config_1);
  61225. });
  61226. });
  61227. }
  61228. return DracoCompression._DecoderModulePromise;
  61229. };
  61230. DracoCompression._LoadScriptAsync = function (url) {
  61231. return new Promise(function (resolve, reject) {
  61232. BABYLON.Tools.LoadScript(url, function () {
  61233. resolve();
  61234. }, function (message) {
  61235. reject(new Error(message));
  61236. });
  61237. });
  61238. };
  61239. DracoCompression._LoadFileAsync = function (url) {
  61240. return new Promise(function (resolve, reject) {
  61241. BABYLON.Tools.LoadFile(url, function (data) {
  61242. resolve(data);
  61243. }, undefined, undefined, true, function (request, exception) {
  61244. reject(exception);
  61245. });
  61246. });
  61247. };
  61248. /**
  61249. * The configuration. Defaults to the following urls:
  61250. * - wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js"
  61251. * - wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm"
  61252. * - fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  61253. */
  61254. DracoCompression.Configuration = {
  61255. decoder: {
  61256. wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
  61257. wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
  61258. fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  61259. }
  61260. };
  61261. return DracoCompression;
  61262. }());
  61263. BABYLON.DracoCompression = DracoCompression;
  61264. })(BABYLON || (BABYLON = {}));
  61265. //# sourceMappingURL=babylon.dracoCompression.js.map
  61266. var BABYLON;
  61267. (function (BABYLON) {
  61268. var AudioEngine = /** @class */ (function () {
  61269. function AudioEngine() {
  61270. this._audioContext = null;
  61271. this._audioContextInitialized = false;
  61272. this.canUseWebAudio = false;
  61273. this.WarnedWebAudioUnsupported = false;
  61274. this.unlocked = false;
  61275. this.isMP3supported = false;
  61276. this.isOGGsupported = false;
  61277. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  61278. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  61279. this.canUseWebAudio = true;
  61280. }
  61281. var audioElem = document.createElement('audio');
  61282. try {
  61283. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  61284. this.isMP3supported = true;
  61285. }
  61286. }
  61287. catch (e) {
  61288. // protect error during capability check.
  61289. }
  61290. try {
  61291. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  61292. this.isOGGsupported = true;
  61293. }
  61294. }
  61295. catch (e) {
  61296. // protect error during capability check.
  61297. }
  61298. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  61299. this._unlockiOSaudio();
  61300. }
  61301. else {
  61302. this.unlocked = true;
  61303. }
  61304. }
  61305. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  61306. get: function () {
  61307. if (!this._audioContextInitialized) {
  61308. this._initializeAudioContext();
  61309. }
  61310. return this._audioContext;
  61311. },
  61312. enumerable: true,
  61313. configurable: true
  61314. });
  61315. AudioEngine.prototype._unlockiOSaudio = function () {
  61316. var _this = this;
  61317. var unlockaudio = function () {
  61318. if (!_this.audioContext) {
  61319. return;
  61320. }
  61321. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  61322. var source = _this.audioContext.createBufferSource();
  61323. source.buffer = buffer;
  61324. source.connect(_this.audioContext.destination);
  61325. source.start(0);
  61326. setTimeout(function () {
  61327. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  61328. _this.unlocked = true;
  61329. window.removeEventListener('touchend', unlockaudio, false);
  61330. if (_this.onAudioUnlocked) {
  61331. _this.onAudioUnlocked();
  61332. }
  61333. }
  61334. }, 0);
  61335. };
  61336. window.addEventListener('touchend', unlockaudio, false);
  61337. };
  61338. AudioEngine.prototype._initializeAudioContext = function () {
  61339. try {
  61340. if (this.canUseWebAudio) {
  61341. this._audioContext = new AudioContext();
  61342. // create a global volume gain node
  61343. this.masterGain = this._audioContext.createGain();
  61344. this.masterGain.gain.value = 1;
  61345. this.masterGain.connect(this._audioContext.destination);
  61346. this._audioContextInitialized = true;
  61347. }
  61348. }
  61349. catch (e) {
  61350. this.canUseWebAudio = false;
  61351. BABYLON.Tools.Error("Web Audio: " + e.message);
  61352. }
  61353. };
  61354. AudioEngine.prototype.dispose = function () {
  61355. if (this.canUseWebAudio && this._audioContextInitialized) {
  61356. if (this._connectedAnalyser && this._audioContext) {
  61357. this._connectedAnalyser.stopDebugCanvas();
  61358. this._connectedAnalyser.dispose();
  61359. this.masterGain.disconnect();
  61360. this.masterGain.connect(this._audioContext.destination);
  61361. this._connectedAnalyser = null;
  61362. }
  61363. this.masterGain.gain.value = 1;
  61364. }
  61365. this.WarnedWebAudioUnsupported = false;
  61366. };
  61367. AudioEngine.prototype.getGlobalVolume = function () {
  61368. if (this.canUseWebAudio && this._audioContextInitialized) {
  61369. return this.masterGain.gain.value;
  61370. }
  61371. else {
  61372. return -1;
  61373. }
  61374. };
  61375. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  61376. if (this.canUseWebAudio && this._audioContextInitialized) {
  61377. this.masterGain.gain.value = newVolume;
  61378. }
  61379. };
  61380. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  61381. if (this._connectedAnalyser) {
  61382. this._connectedAnalyser.stopDebugCanvas();
  61383. }
  61384. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  61385. this._connectedAnalyser = analyser;
  61386. this.masterGain.disconnect();
  61387. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  61388. }
  61389. };
  61390. return AudioEngine;
  61391. }());
  61392. BABYLON.AudioEngine = AudioEngine;
  61393. })(BABYLON || (BABYLON = {}));
  61394. //# sourceMappingURL=babylon.audioEngine.js.map
  61395. var BABYLON;
  61396. (function (BABYLON) {
  61397. var Sound = /** @class */ (function () {
  61398. /**
  61399. * Create a sound and attach it to a scene
  61400. * @param name Name of your sound
  61401. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  61402. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  61403. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  61404. */
  61405. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  61406. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  61407. var _this = this;
  61408. this.autoplay = false;
  61409. this.loop = false;
  61410. this.useCustomAttenuation = false;
  61411. this.spatialSound = false;
  61412. this.refDistance = 1;
  61413. this.rolloffFactor = 1;
  61414. this.maxDistance = 100;
  61415. this.distanceModel = "linear";
  61416. this._panningModel = "equalpower";
  61417. this._playbackRate = 1;
  61418. this._streaming = false;
  61419. this._startTime = 0;
  61420. this._startOffset = 0;
  61421. this._position = BABYLON.Vector3.Zero();
  61422. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  61423. this._volume = 1;
  61424. this._isReadyToPlay = false;
  61425. this.isPlaying = false;
  61426. this.isPaused = false;
  61427. this._isDirectional = false;
  61428. // Used if you'd like to create a directional sound.
  61429. // If not set, the sound will be omnidirectional
  61430. this._coneInnerAngle = 360;
  61431. this._coneOuterAngle = 360;
  61432. this._coneOuterGain = 0;
  61433. this._isOutputConnected = false;
  61434. this._urlType = "Unknown";
  61435. this.name = name;
  61436. this._scene = scene;
  61437. this._readyToPlayCallback = readyToPlayCallback;
  61438. // Default custom attenuation function is a linear attenuation
  61439. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  61440. if (currentDistance < maxDistance) {
  61441. return currentVolume * (1 - currentDistance / maxDistance);
  61442. }
  61443. else {
  61444. return 0;
  61445. }
  61446. };
  61447. if (options) {
  61448. this.autoplay = options.autoplay || false;
  61449. this.loop = options.loop || false;
  61450. // if volume === 0, we need another way to check this option
  61451. if (options.volume !== undefined) {
  61452. this._volume = options.volume;
  61453. }
  61454. this.spatialSound = options.spatialSound || false;
  61455. this.maxDistance = options.maxDistance || 100;
  61456. this.useCustomAttenuation = options.useCustomAttenuation || false;
  61457. this.rolloffFactor = options.rolloffFactor || 1;
  61458. this.refDistance = options.refDistance || 1;
  61459. this.distanceModel = options.distanceModel || "linear";
  61460. this._playbackRate = options.playbackRate || 1;
  61461. this._streaming = options.streaming || false;
  61462. }
  61463. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  61464. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  61465. this._soundGain.gain.value = this._volume;
  61466. this._inputAudioNode = this._soundGain;
  61467. this._ouputAudioNode = this._soundGain;
  61468. if (this.spatialSound) {
  61469. this._createSpatialParameters();
  61470. }
  61471. this._scene.mainSoundTrack.AddSound(this);
  61472. var validParameter = true;
  61473. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  61474. if (urlOrArrayBuffer) {
  61475. try {
  61476. if (typeof (urlOrArrayBuffer) === "string")
  61477. this._urlType = "String";
  61478. if (Array.isArray(urlOrArrayBuffer))
  61479. this._urlType = "Array";
  61480. if (urlOrArrayBuffer instanceof ArrayBuffer)
  61481. this._urlType = "ArrayBuffer";
  61482. var urls = [];
  61483. var codecSupportedFound = false;
  61484. switch (this._urlType) {
  61485. case "ArrayBuffer":
  61486. if (urlOrArrayBuffer.byteLength > 0) {
  61487. codecSupportedFound = true;
  61488. this._soundLoaded(urlOrArrayBuffer);
  61489. }
  61490. break;
  61491. case "String":
  61492. urls.push(urlOrArrayBuffer);
  61493. case "Array":
  61494. if (urls.length === 0)
  61495. urls = urlOrArrayBuffer;
  61496. // If we found a supported format, we load it immediately and stop the loop
  61497. for (var i = 0; i < urls.length; i++) {
  61498. var url = urls[i];
  61499. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  61500. codecSupportedFound = true;
  61501. }
  61502. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  61503. codecSupportedFound = true;
  61504. }
  61505. if (url.indexOf(".wav", url.length - 4) !== -1) {
  61506. codecSupportedFound = true;
  61507. }
  61508. if (url.indexOf("blob:") !== -1) {
  61509. codecSupportedFound = true;
  61510. }
  61511. if (codecSupportedFound) {
  61512. // Loading sound using XHR2
  61513. if (!this._streaming) {
  61514. this._scene._loadFile(url, function (data) {
  61515. _this._soundLoaded(data);
  61516. }, undefined, true, true, function (exception) {
  61517. if (exception) {
  61518. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  61519. }
  61520. BABYLON.Tools.Error("Sound creation aborted.");
  61521. _this._scene.mainSoundTrack.RemoveSound(_this);
  61522. });
  61523. }
  61524. // Streaming sound using HTML5 Audio tag
  61525. else {
  61526. this._htmlAudioElement = new Audio(url);
  61527. this._htmlAudioElement.controls = false;
  61528. this._htmlAudioElement.loop = this.loop;
  61529. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  61530. this._htmlAudioElement.preload = "auto";
  61531. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  61532. _this._isReadyToPlay = true;
  61533. if (_this.autoplay) {
  61534. _this.play();
  61535. }
  61536. if (_this._readyToPlayCallback) {
  61537. _this._readyToPlayCallback();
  61538. }
  61539. });
  61540. document.body.appendChild(this._htmlAudioElement);
  61541. }
  61542. break;
  61543. }
  61544. }
  61545. break;
  61546. default:
  61547. validParameter = false;
  61548. break;
  61549. }
  61550. if (!validParameter) {
  61551. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  61552. }
  61553. else {
  61554. if (!codecSupportedFound) {
  61555. this._isReadyToPlay = true;
  61556. // Simulating a ready to play event to avoid breaking code path
  61557. if (this._readyToPlayCallback) {
  61558. window.setTimeout(function () {
  61559. if (_this._readyToPlayCallback) {
  61560. _this._readyToPlayCallback();
  61561. }
  61562. }, 1000);
  61563. }
  61564. }
  61565. }
  61566. }
  61567. catch (ex) {
  61568. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  61569. this._scene.mainSoundTrack.RemoveSound(this);
  61570. }
  61571. }
  61572. }
  61573. else {
  61574. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  61575. this._scene.mainSoundTrack.AddSound(this);
  61576. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  61577. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  61578. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  61579. }
  61580. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  61581. if (this._readyToPlayCallback) {
  61582. window.setTimeout(function () {
  61583. if (_this._readyToPlayCallback) {
  61584. _this._readyToPlayCallback();
  61585. }
  61586. }, 1000);
  61587. }
  61588. }
  61589. }
  61590. Sound.prototype.dispose = function () {
  61591. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  61592. if (this.isPlaying) {
  61593. this.stop();
  61594. }
  61595. this._isReadyToPlay = false;
  61596. if (this.soundTrackId === -1) {
  61597. this._scene.mainSoundTrack.RemoveSound(this);
  61598. }
  61599. else {
  61600. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  61601. }
  61602. if (this._soundGain) {
  61603. this._soundGain.disconnect();
  61604. this._soundGain = null;
  61605. }
  61606. if (this._soundPanner) {
  61607. this._soundPanner.disconnect();
  61608. this._soundPanner = null;
  61609. }
  61610. if (this._soundSource) {
  61611. this._soundSource.disconnect();
  61612. this._soundSource = null;
  61613. }
  61614. this._audioBuffer = null;
  61615. if (this._htmlAudioElement) {
  61616. this._htmlAudioElement.pause();
  61617. this._htmlAudioElement.src = "";
  61618. document.body.removeChild(this._htmlAudioElement);
  61619. }
  61620. if (this._connectedMesh && this._registerFunc) {
  61621. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  61622. this._connectedMesh = null;
  61623. }
  61624. }
  61625. };
  61626. Sound.prototype.isReady = function () {
  61627. return this._isReadyToPlay;
  61628. };
  61629. Sound.prototype._soundLoaded = function (audioData) {
  61630. var _this = this;
  61631. if (!BABYLON.Engine.audioEngine.audioContext) {
  61632. return;
  61633. }
  61634. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  61635. _this._audioBuffer = buffer;
  61636. _this._isReadyToPlay = true;
  61637. if (_this.autoplay) {
  61638. _this.play();
  61639. }
  61640. if (_this._readyToPlayCallback) {
  61641. _this._readyToPlayCallback();
  61642. }
  61643. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  61644. };
  61645. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  61646. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  61647. this._audioBuffer = audioBuffer;
  61648. this._isReadyToPlay = true;
  61649. }
  61650. };
  61651. Sound.prototype.updateOptions = function (options) {
  61652. if (options) {
  61653. this.loop = options.loop || this.loop;
  61654. this.maxDistance = options.maxDistance || this.maxDistance;
  61655. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  61656. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  61657. this.refDistance = options.refDistance || this.refDistance;
  61658. this.distanceModel = options.distanceModel || this.distanceModel;
  61659. this._playbackRate = options.playbackRate || this._playbackRate;
  61660. this._updateSpatialParameters();
  61661. if (this.isPlaying) {
  61662. if (this._streaming) {
  61663. this._htmlAudioElement.playbackRate = this._playbackRate;
  61664. }
  61665. else {
  61666. if (this._soundSource) {
  61667. this._soundSource.playbackRate.value = this._playbackRate;
  61668. }
  61669. }
  61670. }
  61671. }
  61672. };
  61673. Sound.prototype._createSpatialParameters = function () {
  61674. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  61675. if (this._scene.headphone) {
  61676. this._panningModel = "HRTF";
  61677. }
  61678. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  61679. this._updateSpatialParameters();
  61680. this._soundPanner.connect(this._ouputAudioNode);
  61681. this._inputAudioNode = this._soundPanner;
  61682. }
  61683. };
  61684. Sound.prototype._updateSpatialParameters = function () {
  61685. if (this.spatialSound && this._soundPanner) {
  61686. if (this.useCustomAttenuation) {
  61687. // Tricks to disable in a way embedded Web Audio attenuation
  61688. this._soundPanner.distanceModel = "linear";
  61689. this._soundPanner.maxDistance = Number.MAX_VALUE;
  61690. this._soundPanner.refDistance = 1;
  61691. this._soundPanner.rolloffFactor = 1;
  61692. this._soundPanner.panningModel = this._panningModel;
  61693. }
  61694. else {
  61695. this._soundPanner.distanceModel = this.distanceModel;
  61696. this._soundPanner.maxDistance = this.maxDistance;
  61697. this._soundPanner.refDistance = this.refDistance;
  61698. this._soundPanner.rolloffFactor = this.rolloffFactor;
  61699. this._soundPanner.panningModel = this._panningModel;
  61700. }
  61701. }
  61702. };
  61703. Sound.prototype.switchPanningModelToHRTF = function () {
  61704. this._panningModel = "HRTF";
  61705. this._switchPanningModel();
  61706. };
  61707. Sound.prototype.switchPanningModelToEqualPower = function () {
  61708. this._panningModel = "equalpower";
  61709. this._switchPanningModel();
  61710. };
  61711. Sound.prototype._switchPanningModel = function () {
  61712. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  61713. this._soundPanner.panningModel = this._panningModel;
  61714. }
  61715. };
  61716. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  61717. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  61718. if (this._isOutputConnected) {
  61719. this._ouputAudioNode.disconnect();
  61720. }
  61721. this._ouputAudioNode.connect(soundTrackAudioNode);
  61722. this._isOutputConnected = true;
  61723. }
  61724. };
  61725. /**
  61726. * Transform this sound into a directional source
  61727. * @param coneInnerAngle Size of the inner cone in degree
  61728. * @param coneOuterAngle Size of the outer cone in degree
  61729. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  61730. */
  61731. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  61732. if (coneOuterAngle < coneInnerAngle) {
  61733. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  61734. return;
  61735. }
  61736. this._coneInnerAngle = coneInnerAngle;
  61737. this._coneOuterAngle = coneOuterAngle;
  61738. this._coneOuterGain = coneOuterGain;
  61739. this._isDirectional = true;
  61740. if (this.isPlaying && this.loop) {
  61741. this.stop();
  61742. this.play();
  61743. }
  61744. };
  61745. Sound.prototype.setPosition = function (newPosition) {
  61746. this._position = newPosition;
  61747. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  61748. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  61749. }
  61750. };
  61751. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  61752. this._localDirection = newLocalDirection;
  61753. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  61754. this._updateDirection();
  61755. }
  61756. };
  61757. Sound.prototype._updateDirection = function () {
  61758. if (!this._connectedMesh || !this._soundPanner) {
  61759. return;
  61760. }
  61761. var mat = this._connectedMesh.getWorldMatrix();
  61762. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  61763. direction.normalize();
  61764. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  61765. };
  61766. Sound.prototype.updateDistanceFromListener = function () {
  61767. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  61768. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  61769. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  61770. }
  61771. };
  61772. Sound.prototype.setAttenuationFunction = function (callback) {
  61773. this._customAttenuationFunction = callback;
  61774. };
  61775. /**
  61776. * Play the sound
  61777. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  61778. * @param offset (optional) Start the sound setting it at a specific time
  61779. */
  61780. Sound.prototype.play = function (time, offset) {
  61781. var _this = this;
  61782. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  61783. try {
  61784. if (this._startOffset < 0) {
  61785. time = -this._startOffset;
  61786. this._startOffset = 0;
  61787. }
  61788. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  61789. if (!this._soundSource || !this._streamingSource) {
  61790. if (this.spatialSound && this._soundPanner) {
  61791. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  61792. if (this._isDirectional) {
  61793. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  61794. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  61795. this._soundPanner.coneOuterGain = this._coneOuterGain;
  61796. if (this._connectedMesh) {
  61797. this._updateDirection();
  61798. }
  61799. else {
  61800. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  61801. }
  61802. }
  61803. }
  61804. }
  61805. if (this._streaming) {
  61806. if (!this._streamingSource) {
  61807. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  61808. this._htmlAudioElement.onended = function () { _this._onended(); };
  61809. this._htmlAudioElement.playbackRate = this._playbackRate;
  61810. }
  61811. this._streamingSource.disconnect();
  61812. this._streamingSource.connect(this._inputAudioNode);
  61813. this._htmlAudioElement.play();
  61814. }
  61815. else {
  61816. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  61817. this._soundSource.buffer = this._audioBuffer;
  61818. this._soundSource.connect(this._inputAudioNode);
  61819. this._soundSource.loop = this.loop;
  61820. this._soundSource.playbackRate.value = this._playbackRate;
  61821. this._soundSource.onended = function () { _this._onended(); };
  61822. if (this._soundSource.buffer) {
  61823. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  61824. }
  61825. }
  61826. this._startTime = startTime;
  61827. this.isPlaying = true;
  61828. this.isPaused = false;
  61829. }
  61830. catch (ex) {
  61831. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  61832. }
  61833. }
  61834. };
  61835. Sound.prototype._onended = function () {
  61836. this.isPlaying = false;
  61837. if (this.onended) {
  61838. this.onended();
  61839. }
  61840. };
  61841. /**
  61842. * Stop the sound
  61843. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  61844. */
  61845. Sound.prototype.stop = function (time) {
  61846. if (this.isPlaying) {
  61847. if (this._streaming) {
  61848. this._htmlAudioElement.pause();
  61849. // Test needed for Firefox or it will generate an Invalid State Error
  61850. if (this._htmlAudioElement.currentTime > 0) {
  61851. this._htmlAudioElement.currentTime = 0;
  61852. }
  61853. }
  61854. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  61855. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  61856. this._soundSource.stop(stopTime);
  61857. this._soundSource.onended = function () { };
  61858. if (!this.isPaused) {
  61859. this._startOffset = 0;
  61860. }
  61861. }
  61862. this.isPlaying = false;
  61863. }
  61864. };
  61865. Sound.prototype.pause = function () {
  61866. if (this.isPlaying) {
  61867. this.isPaused = true;
  61868. if (this._streaming) {
  61869. this._htmlAudioElement.pause();
  61870. }
  61871. else if (BABYLON.Engine.audioEngine.audioContext) {
  61872. this.stop(0);
  61873. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  61874. }
  61875. }
  61876. };
  61877. Sound.prototype.setVolume = function (newVolume, time) {
  61878. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  61879. if (time && BABYLON.Engine.audioEngine.audioContext) {
  61880. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  61881. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  61882. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  61883. }
  61884. else {
  61885. this._soundGain.gain.value = newVolume;
  61886. }
  61887. }
  61888. this._volume = newVolume;
  61889. };
  61890. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  61891. this._playbackRate = newPlaybackRate;
  61892. if (this.isPlaying) {
  61893. if (this._streaming) {
  61894. this._htmlAudioElement.playbackRate = this._playbackRate;
  61895. }
  61896. else if (this._soundSource) {
  61897. this._soundSource.playbackRate.value = this._playbackRate;
  61898. }
  61899. }
  61900. };
  61901. Sound.prototype.getVolume = function () {
  61902. return this._volume;
  61903. };
  61904. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  61905. var _this = this;
  61906. if (this._connectedMesh && this._registerFunc) {
  61907. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  61908. this._registerFunc = null;
  61909. }
  61910. this._connectedMesh = meshToConnectTo;
  61911. if (!this.spatialSound) {
  61912. this.spatialSound = true;
  61913. this._createSpatialParameters();
  61914. if (this.isPlaying && this.loop) {
  61915. this.stop();
  61916. this.play();
  61917. }
  61918. }
  61919. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  61920. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  61921. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  61922. };
  61923. Sound.prototype.detachFromMesh = function () {
  61924. if (this._connectedMesh && this._registerFunc) {
  61925. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  61926. this._registerFunc = null;
  61927. this._connectedMesh = null;
  61928. }
  61929. };
  61930. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  61931. if (!node.getBoundingInfo) {
  61932. return;
  61933. }
  61934. var mesh = node;
  61935. var boundingInfo = mesh.getBoundingInfo();
  61936. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  61937. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  61938. this._updateDirection();
  61939. }
  61940. };
  61941. Sound.prototype.clone = function () {
  61942. var _this = this;
  61943. if (!this._streaming) {
  61944. var setBufferAndRun = function () {
  61945. if (_this._isReadyToPlay) {
  61946. clonedSound._audioBuffer = _this.getAudioBuffer();
  61947. clonedSound._isReadyToPlay = true;
  61948. if (clonedSound.autoplay) {
  61949. clonedSound.play();
  61950. }
  61951. }
  61952. else {
  61953. window.setTimeout(setBufferAndRun, 300);
  61954. }
  61955. };
  61956. var currentOptions = {
  61957. autoplay: this.autoplay, loop: this.loop,
  61958. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  61959. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  61960. refDistance: this.refDistance, distanceModel: this.distanceModel
  61961. };
  61962. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  61963. if (this.useCustomAttenuation) {
  61964. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  61965. }
  61966. clonedSound.setPosition(this._position);
  61967. clonedSound.setPlaybackRate(this._playbackRate);
  61968. setBufferAndRun();
  61969. return clonedSound;
  61970. }
  61971. // Can't clone a streaming sound
  61972. else {
  61973. return null;
  61974. }
  61975. };
  61976. Sound.prototype.getAudioBuffer = function () {
  61977. return this._audioBuffer;
  61978. };
  61979. Sound.prototype.serialize = function () {
  61980. var serializationObject = {
  61981. name: this.name,
  61982. url: this.name,
  61983. autoplay: this.autoplay,
  61984. loop: this.loop,
  61985. volume: this._volume,
  61986. spatialSound: this.spatialSound,
  61987. maxDistance: this.maxDistance,
  61988. rolloffFactor: this.rolloffFactor,
  61989. refDistance: this.refDistance,
  61990. distanceModel: this.distanceModel,
  61991. playbackRate: this._playbackRate,
  61992. panningModel: this._panningModel,
  61993. soundTrackId: this.soundTrackId
  61994. };
  61995. if (this.spatialSound) {
  61996. if (this._connectedMesh)
  61997. serializationObject.connectedMeshId = this._connectedMesh.id;
  61998. serializationObject.position = this._position.asArray();
  61999. serializationObject.refDistance = this.refDistance;
  62000. serializationObject.distanceModel = this.distanceModel;
  62001. serializationObject.isDirectional = this._isDirectional;
  62002. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  62003. serializationObject.coneInnerAngle = this._coneInnerAngle;
  62004. serializationObject.coneOuterAngle = this._coneOuterAngle;
  62005. serializationObject.coneOuterGain = this._coneOuterGain;
  62006. }
  62007. return serializationObject;
  62008. };
  62009. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  62010. var soundName = parsedSound.name;
  62011. var soundUrl;
  62012. if (parsedSound.url) {
  62013. soundUrl = rootUrl + parsedSound.url;
  62014. }
  62015. else {
  62016. soundUrl = rootUrl + soundName;
  62017. }
  62018. var options = {
  62019. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  62020. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  62021. rolloffFactor: parsedSound.rolloffFactor,
  62022. refDistance: parsedSound.refDistance,
  62023. distanceModel: parsedSound.distanceModel,
  62024. playbackRate: parsedSound.playbackRate
  62025. };
  62026. var newSound;
  62027. if (!sourceSound) {
  62028. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  62029. scene._addPendingData(newSound);
  62030. }
  62031. else {
  62032. var setBufferAndRun = function () {
  62033. if (sourceSound._isReadyToPlay) {
  62034. newSound._audioBuffer = sourceSound.getAudioBuffer();
  62035. newSound._isReadyToPlay = true;
  62036. if (newSound.autoplay) {
  62037. newSound.play();
  62038. }
  62039. }
  62040. else {
  62041. window.setTimeout(setBufferAndRun, 300);
  62042. }
  62043. };
  62044. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  62045. setBufferAndRun();
  62046. }
  62047. if (parsedSound.position) {
  62048. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  62049. newSound.setPosition(soundPosition);
  62050. }
  62051. if (parsedSound.isDirectional) {
  62052. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  62053. if (parsedSound.localDirectionToMesh) {
  62054. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  62055. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  62056. }
  62057. }
  62058. if (parsedSound.connectedMeshId) {
  62059. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  62060. if (connectedMesh) {
  62061. newSound.attachToMesh(connectedMesh);
  62062. }
  62063. }
  62064. return newSound;
  62065. };
  62066. return Sound;
  62067. }());
  62068. BABYLON.Sound = Sound;
  62069. })(BABYLON || (BABYLON = {}));
  62070. //# sourceMappingURL=babylon.sound.js.map
  62071. var BABYLON;
  62072. (function (BABYLON) {
  62073. var SoundTrack = /** @class */ (function () {
  62074. function SoundTrack(scene, options) {
  62075. this.id = -1;
  62076. this._isMainTrack = false;
  62077. this._isInitialized = false;
  62078. this._scene = scene;
  62079. this.soundCollection = new Array();
  62080. this._options = options;
  62081. if (!this._isMainTrack) {
  62082. this._scene.soundTracks.push(this);
  62083. this.id = this._scene.soundTracks.length - 1;
  62084. }
  62085. }
  62086. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  62087. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62088. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  62089. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  62090. if (this._options) {
  62091. if (this._options.volume) {
  62092. this._outputAudioNode.gain.value = this._options.volume;
  62093. }
  62094. if (this._options.mainTrack) {
  62095. this._isMainTrack = this._options.mainTrack;
  62096. }
  62097. }
  62098. this._isInitialized = true;
  62099. }
  62100. };
  62101. SoundTrack.prototype.dispose = function () {
  62102. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  62103. if (this._connectedAnalyser) {
  62104. this._connectedAnalyser.stopDebugCanvas();
  62105. }
  62106. while (this.soundCollection.length) {
  62107. this.soundCollection[0].dispose();
  62108. }
  62109. if (this._outputAudioNode) {
  62110. this._outputAudioNode.disconnect();
  62111. }
  62112. this._outputAudioNode = null;
  62113. }
  62114. };
  62115. SoundTrack.prototype.AddSound = function (sound) {
  62116. if (!this._isInitialized) {
  62117. this._initializeSoundTrackAudioGraph();
  62118. }
  62119. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  62120. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  62121. }
  62122. if (sound.soundTrackId) {
  62123. if (sound.soundTrackId === -1) {
  62124. this._scene.mainSoundTrack.RemoveSound(sound);
  62125. }
  62126. else {
  62127. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  62128. }
  62129. }
  62130. this.soundCollection.push(sound);
  62131. sound.soundTrackId = this.id;
  62132. };
  62133. SoundTrack.prototype.RemoveSound = function (sound) {
  62134. var index = this.soundCollection.indexOf(sound);
  62135. if (index !== -1) {
  62136. this.soundCollection.splice(index, 1);
  62137. }
  62138. };
  62139. SoundTrack.prototype.setVolume = function (newVolume) {
  62140. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  62141. this._outputAudioNode.gain.value = newVolume;
  62142. }
  62143. };
  62144. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  62145. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62146. for (var i = 0; i < this.soundCollection.length; i++) {
  62147. this.soundCollection[i].switchPanningModelToHRTF();
  62148. }
  62149. }
  62150. };
  62151. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  62152. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62153. for (var i = 0; i < this.soundCollection.length; i++) {
  62154. this.soundCollection[i].switchPanningModelToEqualPower();
  62155. }
  62156. }
  62157. };
  62158. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  62159. if (this._connectedAnalyser) {
  62160. this._connectedAnalyser.stopDebugCanvas();
  62161. }
  62162. this._connectedAnalyser = analyser;
  62163. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  62164. this._outputAudioNode.disconnect();
  62165. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  62166. }
  62167. };
  62168. return SoundTrack;
  62169. }());
  62170. BABYLON.SoundTrack = SoundTrack;
  62171. })(BABYLON || (BABYLON = {}));
  62172. //# sourceMappingURL=babylon.soundtrack.js.map
  62173. var BABYLON;
  62174. (function (BABYLON) {
  62175. /**
  62176. * Class used to work with sound analyzer using fast fourier transform (FFT)
  62177. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  62178. */
  62179. var Analyser = /** @class */ (function () {
  62180. /**
  62181. * Creates a new analyser
  62182. * @param scene defines hosting scene
  62183. */
  62184. function Analyser(scene) {
  62185. /**
  62186. * Gets or sets the smoothing
  62187. * @ignorenaming
  62188. */
  62189. this.SMOOTHING = 0.75;
  62190. /**
  62191. * Gets or sets the FFT table size
  62192. * @ignorenaming
  62193. */
  62194. this.FFT_SIZE = 512;
  62195. /**
  62196. * Gets or sets the bar graph amplitude
  62197. * @ignorenaming
  62198. */
  62199. this.BARGRAPHAMPLITUDE = 256;
  62200. /**
  62201. * Gets or sets the position of the debug canvas
  62202. * @ignorenaming
  62203. */
  62204. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  62205. /**
  62206. * Gets or sets the debug canvas size
  62207. * @ignorenaming
  62208. */
  62209. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  62210. this._scene = scene;
  62211. this._audioEngine = BABYLON.Engine.audioEngine;
  62212. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  62213. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  62214. this._webAudioAnalyser.minDecibels = -140;
  62215. this._webAudioAnalyser.maxDecibels = 0;
  62216. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  62217. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  62218. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  62219. }
  62220. }
  62221. /**
  62222. * Get the number of data values you will have to play with for the visualization
  62223. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/frequencyBinCount
  62224. * @returns a number
  62225. */
  62226. Analyser.prototype.getFrequencyBinCount = function () {
  62227. if (this._audioEngine.canUseWebAudio) {
  62228. return this._webAudioAnalyser.frequencyBinCount;
  62229. }
  62230. else {
  62231. return 0;
  62232. }
  62233. };
  62234. /**
  62235. * Gets the current frequency data as a byte array
  62236. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  62237. * @returns a Uint8Array
  62238. */
  62239. Analyser.prototype.getByteFrequencyData = function () {
  62240. if (this._audioEngine.canUseWebAudio) {
  62241. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  62242. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  62243. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  62244. }
  62245. return this._byteFreqs;
  62246. };
  62247. /**
  62248. * Gets the current waveform as a byte array
  62249. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData
  62250. * @returns a Uint8Array
  62251. */
  62252. Analyser.prototype.getByteTimeDomainData = function () {
  62253. if (this._audioEngine.canUseWebAudio) {
  62254. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  62255. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  62256. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  62257. }
  62258. return this._byteTime;
  62259. };
  62260. /**
  62261. * Gets the current frequency data as a float array
  62262. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  62263. * @returns a Float32Array
  62264. */
  62265. Analyser.prototype.getFloatFrequencyData = function () {
  62266. if (this._audioEngine.canUseWebAudio) {
  62267. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  62268. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  62269. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  62270. }
  62271. return this._floatFreqs;
  62272. };
  62273. /**
  62274. * Renders the debug canvas
  62275. */
  62276. Analyser.prototype.drawDebugCanvas = function () {
  62277. var _this = this;
  62278. if (this._audioEngine.canUseWebAudio) {
  62279. if (!this._debugCanvas) {
  62280. this._debugCanvas = document.createElement("canvas");
  62281. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  62282. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  62283. this._debugCanvas.style.position = "absolute";
  62284. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  62285. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  62286. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  62287. document.body.appendChild(this._debugCanvas);
  62288. this._registerFunc = function () {
  62289. _this.drawDebugCanvas();
  62290. };
  62291. this._scene.registerBeforeRender(this._registerFunc);
  62292. }
  62293. if (this._registerFunc && this._debugCanvasContext) {
  62294. var workingArray = this.getByteFrequencyData();
  62295. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  62296. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  62297. // Draw the frequency domain chart.
  62298. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  62299. var value = workingArray[i];
  62300. var percent = value / this.BARGRAPHAMPLITUDE;
  62301. var height = this.DEBUGCANVASSIZE.height * percent;
  62302. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  62303. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  62304. var hue = i / this.getFrequencyBinCount() * 360;
  62305. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  62306. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  62307. }
  62308. }
  62309. }
  62310. };
  62311. /**
  62312. * Stops rendering the debug canvas and removes it
  62313. */
  62314. Analyser.prototype.stopDebugCanvas = function () {
  62315. if (this._debugCanvas) {
  62316. if (this._registerFunc) {
  62317. this._scene.unregisterBeforeRender(this._registerFunc);
  62318. this._registerFunc = null;
  62319. }
  62320. document.body.removeChild(this._debugCanvas);
  62321. this._debugCanvas = null;
  62322. this._debugCanvasContext = null;
  62323. }
  62324. };
  62325. /**
  62326. * Connects two audio nodes
  62327. * @param inputAudioNode defines first node to connect
  62328. * @param outputAudioNode defines second node to connect
  62329. */
  62330. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  62331. if (this._audioEngine.canUseWebAudio) {
  62332. inputAudioNode.connect(this._webAudioAnalyser);
  62333. this._webAudioAnalyser.connect(outputAudioNode);
  62334. }
  62335. };
  62336. /**
  62337. * Releases all associated resources
  62338. */
  62339. Analyser.prototype.dispose = function () {
  62340. if (this._audioEngine.canUseWebAudio) {
  62341. this._webAudioAnalyser.disconnect();
  62342. }
  62343. };
  62344. return Analyser;
  62345. }());
  62346. BABYLON.Analyser = Analyser;
  62347. })(BABYLON || (BABYLON = {}));
  62348. //# sourceMappingURL=babylon.analyser.js.map
  62349. var BABYLON;
  62350. (function (BABYLON) {
  62351. var CubeTexture = /** @class */ (function (_super) {
  62352. __extends(CubeTexture, _super);
  62353. /**
  62354. * Creates a cube texture to use with reflection for instance. It can be based upon dds or six images as well
  62355. * as prefiltered data.
  62356. * @param rootUrl defines the url of the texture or the root name of the six images
  62357. * @param scene defines the scene the texture is attached to
  62358. * @param extensions defines the suffixes add to the picture name in case six images are in use like _px.jpg...
  62359. * @param noMipmap defines if mipmaps should be created or not
  62360. * @param files defines the six files to load for the different faces
  62361. * @param onLoad defines a callback triggered at the end of the file load if no errors occured
  62362. * @param onError defines a callback triggered in case of error during load
  62363. * @param format defines the internal format to use for the texture once loaded
  62364. * @param prefiltered defines whether or not the texture is created from prefiltered data
  62365. * @param forcedExtension defines the extensions to use (force a special type of file to load) in case it is different from the file name
  62366. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  62367. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  62368. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  62369. * @return the cube texture
  62370. */
  62371. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension, createPolynomials, lodScale, lodOffset) {
  62372. if (extensions === void 0) { extensions = null; }
  62373. if (noMipmap === void 0) { noMipmap = false; }
  62374. if (files === void 0) { files = null; }
  62375. if (onLoad === void 0) { onLoad = null; }
  62376. if (onError === void 0) { onError = null; }
  62377. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  62378. if (prefiltered === void 0) { prefiltered = false; }
  62379. if (forcedExtension === void 0) { forcedExtension = null; }
  62380. if (createPolynomials === void 0) { createPolynomials = false; }
  62381. if (lodScale === void 0) { lodScale = 0.8; }
  62382. if (lodOffset === void 0) { lodOffset = 0; }
  62383. var _this = _super.call(this, scene) || this;
  62384. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  62385. /**
  62386. * Gets or sets the center of the bounding box associated with the cube texture
  62387. * It must define where the camera used to render the texture was set
  62388. */
  62389. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  62390. _this._rotationY = 0;
  62391. /** @hidden */
  62392. _this._prefiltered = false;
  62393. _this.name = rootUrl;
  62394. _this.url = rootUrl;
  62395. _this._noMipmap = noMipmap;
  62396. _this.hasAlpha = false;
  62397. _this._format = format;
  62398. _this.isCube = true;
  62399. _this._textureMatrix = BABYLON.Matrix.Identity();
  62400. _this._createPolynomials = createPolynomials;
  62401. if (!rootUrl && !files) {
  62402. return _this;
  62403. }
  62404. var lastDot = rootUrl.lastIndexOf(".");
  62405. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  62406. var isDDS = (extension === ".dds");
  62407. var isEnv = (extension === ".env");
  62408. if (isEnv) {
  62409. _this.gammaSpace = false;
  62410. _this._prefiltered = false;
  62411. }
  62412. else {
  62413. _this._prefiltered = prefiltered;
  62414. if (prefiltered) {
  62415. _this.gammaSpace = false;
  62416. }
  62417. }
  62418. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  62419. if (!files) {
  62420. if (!isEnv && !isDDS && !extensions) {
  62421. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  62422. }
  62423. files = [];
  62424. if (extensions) {
  62425. for (var index = 0; index < extensions.length; index++) {
  62426. files.push(rootUrl + extensions[index]);
  62427. }
  62428. }
  62429. }
  62430. _this._files = files;
  62431. if (!_this._texture) {
  62432. if (!scene.useDelayedTextureLoading) {
  62433. if (prefiltered) {
  62434. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, _this._createPolynomials);
  62435. }
  62436. else {
  62437. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension, false, lodScale, lodOffset);
  62438. }
  62439. }
  62440. else {
  62441. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  62442. }
  62443. }
  62444. else if (onLoad) {
  62445. if (_this._texture.isReady) {
  62446. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  62447. }
  62448. else {
  62449. _this._texture.onLoadedObservable.add(onLoad);
  62450. }
  62451. }
  62452. return _this;
  62453. }
  62454. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  62455. get: function () {
  62456. return this._boundingBoxSize;
  62457. },
  62458. /**
  62459. * Gets or sets the size of the bounding box associated with the cube texture
  62460. * When defined, the cubemap will switch to local mode
  62461. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  62462. * @example https://www.babylonjs-playground.com/#RNASML
  62463. */
  62464. set: function (value) {
  62465. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  62466. return;
  62467. }
  62468. this._boundingBoxSize = value;
  62469. var scene = this.getScene();
  62470. if (scene) {
  62471. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  62472. }
  62473. },
  62474. enumerable: true,
  62475. configurable: true
  62476. });
  62477. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  62478. /**
  62479. * Gets texture matrix rotation angle around Y axis radians.
  62480. */
  62481. get: function () {
  62482. return this._rotationY;
  62483. },
  62484. /**
  62485. * Sets texture matrix rotation angle around Y axis in radians.
  62486. */
  62487. set: function (value) {
  62488. this._rotationY = value;
  62489. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  62490. },
  62491. enumerable: true,
  62492. configurable: true
  62493. });
  62494. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  62495. var rootUrlKey = "";
  62496. files.forEach(function (url) { return rootUrlKey += url; });
  62497. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  62498. };
  62499. /**
  62500. * Creates and return a texture created from prefilterd data by tools like IBL Baker or Lys.
  62501. * @param url defines the url of the prefiltered texture
  62502. * @param scene defines the scene the texture is attached to
  62503. * @param forcedExtension defines the extension of the file if different from the url
  62504. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  62505. * @return the prefiltered texture
  62506. */
  62507. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension, createPolynomials) {
  62508. if (forcedExtension === void 0) { forcedExtension = null; }
  62509. if (createPolynomials === void 0) { createPolynomials = true; }
  62510. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension, createPolynomials);
  62511. };
  62512. // Methods
  62513. CubeTexture.prototype.delayLoad = function () {
  62514. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  62515. return;
  62516. }
  62517. var scene = this.getScene();
  62518. if (!scene) {
  62519. return;
  62520. }
  62521. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  62522. this._texture = this._getFromCache(this.url, this._noMipmap);
  62523. if (!this._texture) {
  62524. if (this._prefiltered) {
  62525. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format, undefined, this._createPolynomials);
  62526. }
  62527. else {
  62528. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  62529. }
  62530. }
  62531. };
  62532. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  62533. return this._textureMatrix;
  62534. };
  62535. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  62536. this._textureMatrix = value;
  62537. };
  62538. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  62539. var texture = BABYLON.SerializationHelper.Parse(function () {
  62540. var prefiltered = false;
  62541. if (parsedTexture.prefiltered) {
  62542. prefiltered = parsedTexture.prefiltered;
  62543. }
  62544. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions, false, null, null, null, undefined, prefiltered);
  62545. }, parsedTexture, scene);
  62546. // Local Cubemaps
  62547. if (parsedTexture.boundingBoxPosition) {
  62548. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  62549. }
  62550. if (parsedTexture.boundingBoxSize) {
  62551. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  62552. }
  62553. // Animations
  62554. if (parsedTexture.animations) {
  62555. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  62556. var parsedAnimation = parsedTexture.animations[animationIndex];
  62557. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  62558. }
  62559. }
  62560. return texture;
  62561. };
  62562. CubeTexture.prototype.clone = function () {
  62563. var _this = this;
  62564. return BABYLON.SerializationHelper.Clone(function () {
  62565. var scene = _this.getScene();
  62566. if (!scene) {
  62567. return _this;
  62568. }
  62569. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  62570. }, this);
  62571. };
  62572. __decorate([
  62573. BABYLON.serialize("rotationY")
  62574. ], CubeTexture.prototype, "_rotationY", void 0);
  62575. return CubeTexture;
  62576. }(BABYLON.BaseTexture));
  62577. BABYLON.CubeTexture = CubeTexture;
  62578. })(BABYLON || (BABYLON = {}));
  62579. //# sourceMappingURL=babylon.cubeTexture.js.map
  62580. var BABYLON;
  62581. (function (BABYLON) {
  62582. var RenderTargetTexture = /** @class */ (function (_super) {
  62583. __extends(RenderTargetTexture, _super);
  62584. /**
  62585. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  62586. * or used a shadow, depth texture...
  62587. * @param name The friendly name of the texture
  62588. * @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)
  62589. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  62590. * @param generateMipMaps True if mip maps need to be generated after render.
  62591. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  62592. * @param type The type of the buffer in the RTT (int, half float, float...)
  62593. * @param isCube True if a cube texture needs to be created
  62594. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  62595. * @param generateDepthBuffer True to generate a depth buffer
  62596. * @param generateStencilBuffer True to generate a stencil buffer
  62597. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  62598. */
  62599. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  62600. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  62601. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  62602. if (isCube === void 0) { isCube = false; }
  62603. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  62604. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  62605. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  62606. if (isMulti === void 0) { isMulti = false; }
  62607. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  62608. _this.isCube = isCube;
  62609. /**
  62610. * Use this list to define the list of mesh you want to render.
  62611. */
  62612. _this.renderList = new Array();
  62613. _this.renderParticles = true;
  62614. _this.renderSprites = false;
  62615. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  62616. _this.ignoreCameraViewport = false;
  62617. // Events
  62618. /**
  62619. * An event triggered when the texture is unbind.
  62620. */
  62621. _this.onBeforeBindObservable = new BABYLON.Observable();
  62622. /**
  62623. * An event triggered when the texture is unbind.
  62624. */
  62625. _this.onAfterUnbindObservable = new BABYLON.Observable();
  62626. /**
  62627. * An event triggered before rendering the texture
  62628. */
  62629. _this.onBeforeRenderObservable = new BABYLON.Observable();
  62630. /**
  62631. * An event triggered after rendering the texture
  62632. */
  62633. _this.onAfterRenderObservable = new BABYLON.Observable();
  62634. /**
  62635. * An event triggered after the texture clear
  62636. */
  62637. _this.onClearObservable = new BABYLON.Observable();
  62638. _this._currentRefreshId = -1;
  62639. _this._refreshRate = 1;
  62640. _this._samples = 1;
  62641. /**
  62642. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  62643. * It must define where the camera used to render the texture is set
  62644. */
  62645. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  62646. scene = _this.getScene();
  62647. if (!scene) {
  62648. return _this;
  62649. }
  62650. _this._engine = scene.getEngine();
  62651. _this.name = name;
  62652. _this.isRenderTarget = true;
  62653. _this._initialSizeParameter = size;
  62654. _this._processSizeParameter(size);
  62655. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  62656. });
  62657. _this._generateMipMaps = generateMipMaps ? true : false;
  62658. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  62659. // Rendering groups
  62660. _this._renderingManager = new BABYLON.RenderingManager(scene);
  62661. if (isMulti) {
  62662. return _this;
  62663. }
  62664. _this._renderTargetOptions = {
  62665. generateMipMaps: generateMipMaps,
  62666. type: type,
  62667. samplingMode: samplingMode,
  62668. generateDepthBuffer: generateDepthBuffer,
  62669. generateStencilBuffer: generateStencilBuffer
  62670. };
  62671. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  62672. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  62673. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  62674. }
  62675. if (isCube) {
  62676. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  62677. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  62678. _this._textureMatrix = BABYLON.Matrix.Identity();
  62679. }
  62680. else {
  62681. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  62682. }
  62683. return _this;
  62684. }
  62685. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  62686. get: function () {
  62687. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  62688. },
  62689. enumerable: true,
  62690. configurable: true
  62691. });
  62692. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  62693. get: function () {
  62694. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  62695. },
  62696. enumerable: true,
  62697. configurable: true
  62698. });
  62699. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  62700. get: function () {
  62701. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  62702. },
  62703. enumerable: true,
  62704. configurable: true
  62705. });
  62706. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  62707. set: function (callback) {
  62708. if (this._onAfterUnbindObserver) {
  62709. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  62710. }
  62711. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  62712. },
  62713. enumerable: true,
  62714. configurable: true
  62715. });
  62716. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  62717. set: function (callback) {
  62718. if (this._onBeforeRenderObserver) {
  62719. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  62720. }
  62721. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  62722. },
  62723. enumerable: true,
  62724. configurable: true
  62725. });
  62726. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  62727. set: function (callback) {
  62728. if (this._onAfterRenderObserver) {
  62729. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  62730. }
  62731. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  62732. },
  62733. enumerable: true,
  62734. configurable: true
  62735. });
  62736. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  62737. set: function (callback) {
  62738. if (this._onClearObserver) {
  62739. this.onClearObservable.remove(this._onClearObserver);
  62740. }
  62741. this._onClearObserver = this.onClearObservable.add(callback);
  62742. },
  62743. enumerable: true,
  62744. configurable: true
  62745. });
  62746. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  62747. get: function () {
  62748. return this._renderTargetOptions;
  62749. },
  62750. enumerable: true,
  62751. configurable: true
  62752. });
  62753. RenderTargetTexture.prototype._onRatioRescale = function () {
  62754. if (this._sizeRatio) {
  62755. this.resize(this._initialSizeParameter);
  62756. }
  62757. };
  62758. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  62759. get: function () {
  62760. return this._boundingBoxSize;
  62761. },
  62762. /**
  62763. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  62764. * When defined, the cubemap will switch to local mode
  62765. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  62766. * @example https://www.babylonjs-playground.com/#RNASML
  62767. */
  62768. set: function (value) {
  62769. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  62770. return;
  62771. }
  62772. this._boundingBoxSize = value;
  62773. var scene = this.getScene();
  62774. if (scene) {
  62775. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  62776. }
  62777. },
  62778. enumerable: true,
  62779. configurable: true
  62780. });
  62781. /**
  62782. * Creates a depth stencil texture.
  62783. * This is only available in WebGL 2 or with the depth texture extension available.
  62784. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  62785. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  62786. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  62787. */
  62788. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  62789. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  62790. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  62791. if (generateStencil === void 0) { generateStencil = false; }
  62792. if (!this.getScene()) {
  62793. return;
  62794. }
  62795. var engine = this.getScene().getEngine();
  62796. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  62797. bilinearFiltering: bilinearFiltering,
  62798. comparisonFunction: comparisonFunction,
  62799. generateStencil: generateStencil,
  62800. isCube: this.isCube
  62801. });
  62802. engine.setFrameBufferDepthStencilTexture(this);
  62803. };
  62804. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  62805. if (size.ratio) {
  62806. this._sizeRatio = size.ratio;
  62807. this._size = {
  62808. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  62809. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  62810. };
  62811. }
  62812. else {
  62813. this._size = size;
  62814. }
  62815. };
  62816. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  62817. get: function () {
  62818. return this._samples;
  62819. },
  62820. set: function (value) {
  62821. if (this._samples === value) {
  62822. return;
  62823. }
  62824. var scene = this.getScene();
  62825. if (!scene) {
  62826. return;
  62827. }
  62828. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  62829. },
  62830. enumerable: true,
  62831. configurable: true
  62832. });
  62833. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  62834. this._currentRefreshId = -1;
  62835. };
  62836. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  62837. get: function () {
  62838. return this._refreshRate;
  62839. },
  62840. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  62841. set: function (value) {
  62842. this._refreshRate = value;
  62843. this.resetRefreshCounter();
  62844. },
  62845. enumerable: true,
  62846. configurable: true
  62847. });
  62848. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  62849. if (!this._postProcessManager) {
  62850. var scene = this.getScene();
  62851. if (!scene) {
  62852. return;
  62853. }
  62854. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  62855. this._postProcesses = new Array();
  62856. }
  62857. this._postProcesses.push(postProcess);
  62858. this._postProcesses[0].autoClear = false;
  62859. };
  62860. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  62861. if (!this._postProcesses) {
  62862. return;
  62863. }
  62864. if (dispose) {
  62865. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  62866. var postProcess = _a[_i];
  62867. postProcess.dispose();
  62868. }
  62869. }
  62870. this._postProcesses = [];
  62871. };
  62872. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  62873. if (!this._postProcesses) {
  62874. return;
  62875. }
  62876. var index = this._postProcesses.indexOf(postProcess);
  62877. if (index === -1) {
  62878. return;
  62879. }
  62880. this._postProcesses.splice(index, 1);
  62881. if (this._postProcesses.length > 0) {
  62882. this._postProcesses[0].autoClear = false;
  62883. }
  62884. };
  62885. RenderTargetTexture.prototype._shouldRender = function () {
  62886. if (this._currentRefreshId === -1) { // At least render once
  62887. this._currentRefreshId = 1;
  62888. return true;
  62889. }
  62890. if (this.refreshRate === this._currentRefreshId) {
  62891. this._currentRefreshId = 1;
  62892. return true;
  62893. }
  62894. this._currentRefreshId++;
  62895. return false;
  62896. };
  62897. RenderTargetTexture.prototype.getRenderSize = function () {
  62898. if (this._size.width) {
  62899. return this._size.width;
  62900. }
  62901. return this._size;
  62902. };
  62903. RenderTargetTexture.prototype.getRenderWidth = function () {
  62904. if (this._size.width) {
  62905. return this._size.width;
  62906. }
  62907. return this._size;
  62908. };
  62909. RenderTargetTexture.prototype.getRenderHeight = function () {
  62910. if (this._size.width) {
  62911. return this._size.height;
  62912. }
  62913. return this._size;
  62914. };
  62915. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  62916. get: function () {
  62917. return true;
  62918. },
  62919. enumerable: true,
  62920. configurable: true
  62921. });
  62922. RenderTargetTexture.prototype.scale = function (ratio) {
  62923. var newSize = this.getRenderSize() * ratio;
  62924. this.resize(newSize);
  62925. };
  62926. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  62927. if (this.isCube) {
  62928. return this._textureMatrix;
  62929. }
  62930. return _super.prototype.getReflectionTextureMatrix.call(this);
  62931. };
  62932. RenderTargetTexture.prototype.resize = function (size) {
  62933. this.releaseInternalTexture();
  62934. var scene = this.getScene();
  62935. if (!scene) {
  62936. return;
  62937. }
  62938. this._processSizeParameter(size);
  62939. if (this.isCube) {
  62940. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  62941. }
  62942. else {
  62943. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  62944. }
  62945. };
  62946. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  62947. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  62948. if (dumpForDebug === void 0) { dumpForDebug = false; }
  62949. var scene = this.getScene();
  62950. if (!scene) {
  62951. return;
  62952. }
  62953. var engine = scene.getEngine();
  62954. if (this.useCameraPostProcesses !== undefined) {
  62955. useCameraPostProcess = this.useCameraPostProcesses;
  62956. }
  62957. if (this._waitingRenderList) {
  62958. this.renderList = [];
  62959. for (var index = 0; index < this._waitingRenderList.length; index++) {
  62960. var id = this._waitingRenderList[index];
  62961. var mesh_1 = scene.getMeshByID(id);
  62962. if (mesh_1) {
  62963. this.renderList.push(mesh_1);
  62964. }
  62965. }
  62966. delete this._waitingRenderList;
  62967. }
  62968. // Is predicate defined?
  62969. if (this.renderListPredicate) {
  62970. if (this.renderList) {
  62971. this.renderList.splice(0); // Clear previous renderList
  62972. }
  62973. else {
  62974. this.renderList = [];
  62975. }
  62976. var scene = this.getScene();
  62977. if (!scene) {
  62978. return;
  62979. }
  62980. var sceneMeshes = scene.meshes;
  62981. for (var index = 0; index < sceneMeshes.length; index++) {
  62982. var mesh = sceneMeshes[index];
  62983. if (this.renderListPredicate(mesh)) {
  62984. this.renderList.push(mesh);
  62985. }
  62986. }
  62987. }
  62988. this.onBeforeBindObservable.notifyObservers(this);
  62989. // Set custom projection.
  62990. // Needs to be before binding to prevent changing the aspect ratio.
  62991. var camera;
  62992. if (this.activeCamera) {
  62993. camera = this.activeCamera;
  62994. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  62995. if (this.activeCamera !== scene.activeCamera) {
  62996. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  62997. }
  62998. }
  62999. else {
  63000. camera = scene.activeCamera;
  63001. if (camera) {
  63002. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  63003. }
  63004. }
  63005. // Prepare renderingManager
  63006. this._renderingManager.reset();
  63007. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  63008. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  63009. var sceneRenderId = scene.getRenderId();
  63010. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  63011. var mesh = currentRenderList[meshIndex];
  63012. if (mesh) {
  63013. if (!mesh.isReady(this.refreshRate === 0)) {
  63014. this.resetRefreshCounter();
  63015. continue;
  63016. }
  63017. mesh._preActivateForIntermediateRendering(sceneRenderId);
  63018. var isMasked = void 0;
  63019. if (!this.renderList && camera) {
  63020. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  63021. }
  63022. else {
  63023. isMasked = false;
  63024. }
  63025. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  63026. mesh._activate(sceneRenderId);
  63027. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  63028. var subMesh = mesh.subMeshes[subIndex];
  63029. scene._activeIndices.addCount(subMesh.indexCount, false);
  63030. this._renderingManager.dispatch(subMesh, mesh);
  63031. }
  63032. }
  63033. }
  63034. }
  63035. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  63036. var particleSystem = scene.particleSystems[particleIndex];
  63037. var emitter = particleSystem.emitter;
  63038. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  63039. continue;
  63040. }
  63041. if (currentRenderList.indexOf(emitter) >= 0) {
  63042. this._renderingManager.dispatchParticles(particleSystem);
  63043. }
  63044. }
  63045. if (this.isCube) {
  63046. for (var face = 0; face < 6; face++) {
  63047. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  63048. scene.incrementRenderId();
  63049. scene.resetCachedMaterial();
  63050. }
  63051. }
  63052. else {
  63053. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  63054. }
  63055. this.onAfterUnbindObservable.notifyObservers(this);
  63056. if (scene.activeCamera) {
  63057. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  63058. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  63059. }
  63060. engine.setViewport(scene.activeCamera.viewport);
  63061. }
  63062. scene.resetCachedMaterial();
  63063. };
  63064. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  63065. var minimum = 128;
  63066. var x = renderDimension * scale;
  63067. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  63068. // Ensure we don't exceed the render dimension (while staying POT)
  63069. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  63070. };
  63071. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  63072. var _this = this;
  63073. if (!this._texture) {
  63074. return;
  63075. }
  63076. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  63077. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  63078. });
  63079. };
  63080. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  63081. var scene = this.getScene();
  63082. if (!scene) {
  63083. return;
  63084. }
  63085. var engine = scene.getEngine();
  63086. if (!this._texture) {
  63087. return;
  63088. }
  63089. // Bind
  63090. if (this._postProcessManager) {
  63091. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  63092. }
  63093. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  63094. if (this._texture) {
  63095. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  63096. }
  63097. }
  63098. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  63099. // Clear
  63100. if (this.onClearObservable.hasObservers()) {
  63101. this.onClearObservable.notifyObservers(engine);
  63102. }
  63103. else {
  63104. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  63105. }
  63106. if (!this._doNotChangeAspectRatio) {
  63107. scene.updateTransformMatrix(true);
  63108. }
  63109. // Render
  63110. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  63111. if (this._postProcessManager) {
  63112. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  63113. }
  63114. else if (useCameraPostProcess) {
  63115. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  63116. }
  63117. if (!this._doNotChangeAspectRatio) {
  63118. scene.updateTransformMatrix(true);
  63119. }
  63120. // Dump ?
  63121. if (dumpForDebug) {
  63122. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  63123. }
  63124. // Unbind
  63125. if (!this.isCube || faceIndex === 5) {
  63126. if (this.isCube) {
  63127. if (faceIndex === 5) {
  63128. engine.generateMipMapsForCubemap(this._texture);
  63129. }
  63130. }
  63131. this.unbindFrameBuffer(engine, faceIndex);
  63132. }
  63133. else {
  63134. this.onAfterRenderObservable.notifyObservers(faceIndex);
  63135. }
  63136. };
  63137. /**
  63138. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  63139. * This allowed control for front to back rendering or reversly depending of the special needs.
  63140. *
  63141. * @param renderingGroupId The rendering group id corresponding to its index
  63142. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  63143. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  63144. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  63145. */
  63146. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  63147. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  63148. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  63149. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  63150. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  63151. };
  63152. /**
  63153. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  63154. *
  63155. * @param renderingGroupId The rendering group id corresponding to its index
  63156. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  63157. */
  63158. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  63159. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  63160. };
  63161. RenderTargetTexture.prototype.clone = function () {
  63162. var textureSize = this.getSize();
  63163. 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);
  63164. // Base texture
  63165. newTexture.hasAlpha = this.hasAlpha;
  63166. newTexture.level = this.level;
  63167. // RenderTarget Texture
  63168. newTexture.coordinatesMode = this.coordinatesMode;
  63169. if (this.renderList) {
  63170. newTexture.renderList = this.renderList.slice(0);
  63171. }
  63172. return newTexture;
  63173. };
  63174. RenderTargetTexture.prototype.serialize = function () {
  63175. if (!this.name) {
  63176. return null;
  63177. }
  63178. var serializationObject = _super.prototype.serialize.call(this);
  63179. serializationObject.renderTargetSize = this.getRenderSize();
  63180. serializationObject.renderList = [];
  63181. if (this.renderList) {
  63182. for (var index = 0; index < this.renderList.length; index++) {
  63183. serializationObject.renderList.push(this.renderList[index].id);
  63184. }
  63185. }
  63186. return serializationObject;
  63187. };
  63188. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  63189. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  63190. var objBuffer = this.getInternalTexture();
  63191. var scene = this.getScene();
  63192. if (objBuffer && scene) {
  63193. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  63194. }
  63195. };
  63196. RenderTargetTexture.prototype.dispose = function () {
  63197. if (this._postProcessManager) {
  63198. this._postProcessManager.dispose();
  63199. this._postProcessManager = null;
  63200. }
  63201. this.clearPostProcesses(true);
  63202. if (this._resizeObserver) {
  63203. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  63204. this._resizeObserver = null;
  63205. }
  63206. this.renderList = null;
  63207. // Remove from custom render targets
  63208. var scene = this.getScene();
  63209. if (!scene) {
  63210. return;
  63211. }
  63212. var index = scene.customRenderTargets.indexOf(this);
  63213. if (index >= 0) {
  63214. scene.customRenderTargets.splice(index, 1);
  63215. }
  63216. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  63217. var camera = _a[_i];
  63218. index = camera.customRenderTargets.indexOf(this);
  63219. if (index >= 0) {
  63220. camera.customRenderTargets.splice(index, 1);
  63221. }
  63222. }
  63223. _super.prototype.dispose.call(this);
  63224. };
  63225. RenderTargetTexture.prototype._rebuild = function () {
  63226. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  63227. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  63228. }
  63229. if (this._postProcessManager) {
  63230. this._postProcessManager._rebuild();
  63231. }
  63232. };
  63233. /**
  63234. * Clear the info related to rendering groups preventing retention point in material dispose.
  63235. */
  63236. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  63237. if (this._renderingManager) {
  63238. this._renderingManager.freeRenderingGroups();
  63239. }
  63240. };
  63241. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  63242. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  63243. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  63244. return RenderTargetTexture;
  63245. }(BABYLON.Texture));
  63246. BABYLON.RenderTargetTexture = RenderTargetTexture;
  63247. })(BABYLON || (BABYLON = {}));
  63248. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  63249. var BABYLON;
  63250. (function (BABYLON) {
  63251. ;
  63252. var MultiRenderTarget = /** @class */ (function (_super) {
  63253. __extends(MultiRenderTarget, _super);
  63254. function MultiRenderTarget(name, size, count, scene, options) {
  63255. var _this = this;
  63256. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  63257. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  63258. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  63259. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  63260. _this._engine = scene.getEngine();
  63261. if (!_this.isSupported) {
  63262. _this.dispose();
  63263. return;
  63264. }
  63265. var types = [];
  63266. var samplingModes = [];
  63267. for (var i = 0; i < count; i++) {
  63268. if (options && options.types && options.types[i] !== undefined) {
  63269. types.push(options.types[i]);
  63270. }
  63271. else {
  63272. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  63273. }
  63274. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  63275. samplingModes.push(options.samplingModes[i]);
  63276. }
  63277. else {
  63278. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  63279. }
  63280. }
  63281. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  63282. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  63283. _this._size = size;
  63284. _this._multiRenderTargetOptions = {
  63285. samplingModes: samplingModes,
  63286. generateMipMaps: generateMipMaps,
  63287. generateDepthBuffer: generateDepthBuffer,
  63288. generateStencilBuffer: generateStencilBuffer,
  63289. generateDepthTexture: generateDepthTexture,
  63290. types: types,
  63291. textureCount: count
  63292. };
  63293. _this._createInternalTextures();
  63294. _this._createTextures();
  63295. return _this;
  63296. }
  63297. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  63298. get: function () {
  63299. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  63300. },
  63301. enumerable: true,
  63302. configurable: true
  63303. });
  63304. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  63305. get: function () {
  63306. return this._textures;
  63307. },
  63308. enumerable: true,
  63309. configurable: true
  63310. });
  63311. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  63312. get: function () {
  63313. return this._textures[this._textures.length - 1];
  63314. },
  63315. enumerable: true,
  63316. configurable: true
  63317. });
  63318. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  63319. set: function (wrap) {
  63320. if (this._textures) {
  63321. for (var i = 0; i < this._textures.length; i++) {
  63322. this._textures[i].wrapU = wrap;
  63323. }
  63324. }
  63325. },
  63326. enumerable: true,
  63327. configurable: true
  63328. });
  63329. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  63330. set: function (wrap) {
  63331. if (this._textures) {
  63332. for (var i = 0; i < this._textures.length; i++) {
  63333. this._textures[i].wrapV = wrap;
  63334. }
  63335. }
  63336. },
  63337. enumerable: true,
  63338. configurable: true
  63339. });
  63340. MultiRenderTarget.prototype._rebuild = function () {
  63341. this.releaseInternalTextures();
  63342. this._createInternalTextures();
  63343. for (var i = 0; i < this._internalTextures.length; i++) {
  63344. var texture = this._textures[i];
  63345. texture._texture = this._internalTextures[i];
  63346. }
  63347. // Keeps references to frame buffer and stencil/depth buffer
  63348. this._texture = this._internalTextures[0];
  63349. };
  63350. MultiRenderTarget.prototype._createInternalTextures = function () {
  63351. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  63352. };
  63353. MultiRenderTarget.prototype._createTextures = function () {
  63354. this._textures = [];
  63355. for (var i = 0; i < this._internalTextures.length; i++) {
  63356. var texture = new BABYLON.Texture(null, this.getScene());
  63357. texture._texture = this._internalTextures[i];
  63358. this._textures.push(texture);
  63359. }
  63360. // Keeps references to frame buffer and stencil/depth buffer
  63361. this._texture = this._internalTextures[0];
  63362. };
  63363. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  63364. get: function () {
  63365. return this._samples;
  63366. },
  63367. set: function (value) {
  63368. if (this._samples === value) {
  63369. return;
  63370. }
  63371. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  63372. },
  63373. enumerable: true,
  63374. configurable: true
  63375. });
  63376. MultiRenderTarget.prototype.resize = function (size) {
  63377. this.releaseInternalTextures();
  63378. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  63379. this._createInternalTextures();
  63380. };
  63381. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  63382. var _this = this;
  63383. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  63384. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  63385. });
  63386. };
  63387. MultiRenderTarget.prototype.dispose = function () {
  63388. this.releaseInternalTextures();
  63389. _super.prototype.dispose.call(this);
  63390. };
  63391. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  63392. if (!this._internalTextures) {
  63393. return;
  63394. }
  63395. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  63396. if (this._internalTextures[i] !== undefined) {
  63397. this._internalTextures[i].dispose();
  63398. this._internalTextures.splice(i, 1);
  63399. }
  63400. }
  63401. };
  63402. return MultiRenderTarget;
  63403. }(BABYLON.RenderTargetTexture));
  63404. BABYLON.MultiRenderTarget = MultiRenderTarget;
  63405. })(BABYLON || (BABYLON = {}));
  63406. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  63407. var BABYLON;
  63408. (function (BABYLON) {
  63409. var MirrorTexture = /** @class */ (function (_super) {
  63410. __extends(MirrorTexture, _super);
  63411. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  63412. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63413. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  63414. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  63415. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  63416. _this.scene = scene;
  63417. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  63418. _this._transformMatrix = BABYLON.Matrix.Zero();
  63419. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  63420. _this._adaptiveBlurKernel = 0;
  63421. _this._blurKernelX = 0;
  63422. _this._blurKernelY = 0;
  63423. _this._blurRatio = 1.0;
  63424. _this.ignoreCameraViewport = true;
  63425. _this._updateGammaSpace();
  63426. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  63427. _this._updateGammaSpace;
  63428. });
  63429. _this.onBeforeRenderObservable.add(function () {
  63430. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  63431. _this._savedViewMatrix = scene.getViewMatrix();
  63432. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  63433. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  63434. scene.clipPlane = _this.mirrorPlane;
  63435. scene.getEngine().cullBackFaces = false;
  63436. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  63437. });
  63438. _this.onAfterRenderObservable.add(function () {
  63439. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  63440. scene.getEngine().cullBackFaces = true;
  63441. scene._mirroredCameraPosition = null;
  63442. delete scene.clipPlane;
  63443. });
  63444. return _this;
  63445. }
  63446. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  63447. get: function () {
  63448. return this._blurRatio;
  63449. },
  63450. set: function (value) {
  63451. if (this._blurRatio === value) {
  63452. return;
  63453. }
  63454. this._blurRatio = value;
  63455. this._preparePostProcesses();
  63456. },
  63457. enumerable: true,
  63458. configurable: true
  63459. });
  63460. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  63461. set: function (value) {
  63462. this._adaptiveBlurKernel = value;
  63463. this._autoComputeBlurKernel();
  63464. },
  63465. enumerable: true,
  63466. configurable: true
  63467. });
  63468. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  63469. set: function (value) {
  63470. this.blurKernelX = value;
  63471. this.blurKernelY = value;
  63472. },
  63473. enumerable: true,
  63474. configurable: true
  63475. });
  63476. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  63477. get: function () {
  63478. return this._blurKernelX;
  63479. },
  63480. set: function (value) {
  63481. if (this._blurKernelX === value) {
  63482. return;
  63483. }
  63484. this._blurKernelX = value;
  63485. this._preparePostProcesses();
  63486. },
  63487. enumerable: true,
  63488. configurable: true
  63489. });
  63490. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  63491. get: function () {
  63492. return this._blurKernelY;
  63493. },
  63494. set: function (value) {
  63495. if (this._blurKernelY === value) {
  63496. return;
  63497. }
  63498. this._blurKernelY = value;
  63499. this._preparePostProcesses();
  63500. },
  63501. enumerable: true,
  63502. configurable: true
  63503. });
  63504. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  63505. var engine = this.getScene().getEngine();
  63506. var dw = this.getRenderWidth() / engine.getRenderWidth();
  63507. var dh = this.getRenderHeight() / engine.getRenderHeight();
  63508. this.blurKernelX = this._adaptiveBlurKernel * dw;
  63509. this.blurKernelY = this._adaptiveBlurKernel * dh;
  63510. };
  63511. MirrorTexture.prototype._onRatioRescale = function () {
  63512. if (this._sizeRatio) {
  63513. this.resize(this._initialSizeParameter);
  63514. if (!this._adaptiveBlurKernel) {
  63515. this._preparePostProcesses();
  63516. }
  63517. }
  63518. if (this._adaptiveBlurKernel) {
  63519. this._autoComputeBlurKernel();
  63520. }
  63521. };
  63522. MirrorTexture.prototype._updateGammaSpace = function () {
  63523. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  63524. };
  63525. MirrorTexture.prototype._preparePostProcesses = function () {
  63526. this.clearPostProcesses(true);
  63527. if (this._blurKernelX && this._blurKernelY) {
  63528. var engine = this.getScene().getEngine();
  63529. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  63530. 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);
  63531. this._blurX.autoClear = false;
  63532. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  63533. this._blurX.inputTexture = this._texture;
  63534. }
  63535. else {
  63536. this._blurX.alwaysForcePOT = true;
  63537. }
  63538. 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);
  63539. this._blurY.autoClear = false;
  63540. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  63541. this.addPostProcess(this._blurX);
  63542. this.addPostProcess(this._blurY);
  63543. }
  63544. else {
  63545. if (this._blurY) {
  63546. this.removePostProcess(this._blurY);
  63547. this._blurY.dispose();
  63548. this._blurY = null;
  63549. }
  63550. if (this._blurX) {
  63551. this.removePostProcess(this._blurX);
  63552. this._blurX.dispose();
  63553. this._blurX = null;
  63554. }
  63555. }
  63556. };
  63557. MirrorTexture.prototype.clone = function () {
  63558. var scene = this.getScene();
  63559. if (!scene) {
  63560. return this;
  63561. }
  63562. var textureSize = this.getSize();
  63563. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  63564. // Base texture
  63565. newTexture.hasAlpha = this.hasAlpha;
  63566. newTexture.level = this.level;
  63567. // Mirror Texture
  63568. newTexture.mirrorPlane = this.mirrorPlane.clone();
  63569. if (this.renderList) {
  63570. newTexture.renderList = this.renderList.slice(0);
  63571. }
  63572. return newTexture;
  63573. };
  63574. MirrorTexture.prototype.serialize = function () {
  63575. if (!this.name) {
  63576. return null;
  63577. }
  63578. var serializationObject = _super.prototype.serialize.call(this);
  63579. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  63580. return serializationObject;
  63581. };
  63582. MirrorTexture.prototype.dispose = function () {
  63583. _super.prototype.dispose.call(this);
  63584. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  63585. };
  63586. return MirrorTexture;
  63587. }(BABYLON.RenderTargetTexture));
  63588. BABYLON.MirrorTexture = MirrorTexture;
  63589. })(BABYLON || (BABYLON = {}));
  63590. //# sourceMappingURL=babylon.mirrorTexture.js.map
  63591. var BABYLON;
  63592. (function (BABYLON) {
  63593. /**
  63594. * Creates a refraction texture used by refraction channel of the standard material.
  63595. * @param name the texture name
  63596. * @param size size of the underlying texture
  63597. * @param scene root scene
  63598. */
  63599. var RefractionTexture = /** @class */ (function (_super) {
  63600. __extends(RefractionTexture, _super);
  63601. function RefractionTexture(name, size, scene, generateMipMaps) {
  63602. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  63603. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  63604. _this.depth = 2.0;
  63605. _this.onBeforeRenderObservable.add(function () {
  63606. scene.clipPlane = _this.refractionPlane;
  63607. });
  63608. _this.onAfterRenderObservable.add(function () {
  63609. delete scene.clipPlane;
  63610. });
  63611. return _this;
  63612. }
  63613. RefractionTexture.prototype.clone = function () {
  63614. var scene = this.getScene();
  63615. if (!scene) {
  63616. return this;
  63617. }
  63618. var textureSize = this.getSize();
  63619. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  63620. // Base texture
  63621. newTexture.hasAlpha = this.hasAlpha;
  63622. newTexture.level = this.level;
  63623. // Refraction Texture
  63624. newTexture.refractionPlane = this.refractionPlane.clone();
  63625. if (this.renderList) {
  63626. newTexture.renderList = this.renderList.slice(0);
  63627. }
  63628. newTexture.depth = this.depth;
  63629. return newTexture;
  63630. };
  63631. RefractionTexture.prototype.serialize = function () {
  63632. if (!this.name) {
  63633. return null;
  63634. }
  63635. var serializationObject = _super.prototype.serialize.call(this);
  63636. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  63637. serializationObject.depth = this.depth;
  63638. return serializationObject;
  63639. };
  63640. return RefractionTexture;
  63641. }(BABYLON.RenderTargetTexture));
  63642. BABYLON.RefractionTexture = RefractionTexture;
  63643. })(BABYLON || (BABYLON = {}));
  63644. //# sourceMappingURL=babylon.refractionTexture.js.map
  63645. var BABYLON;
  63646. (function (BABYLON) {
  63647. /**
  63648. * A class extending {BABYLON.Texture} allowing drawing on a texture
  63649. * @see http://doc.babylonjs.com/how_to/dynamictexture
  63650. */
  63651. var DynamicTexture = /** @class */ (function (_super) {
  63652. __extends(DynamicTexture, _super);
  63653. /**
  63654. * Creates a {BABYLON.DynamicTexture}
  63655. * @param name defines the name of the texture
  63656. * @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
  63657. * @param scene defines the scene where you want the texture
  63658. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  63659. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  63660. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  63661. */
  63662. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  63663. if (scene === void 0) { scene = null; }
  63664. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63665. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  63666. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  63667. _this.name = name;
  63668. _this._engine = _this.getScene().getEngine();
  63669. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63670. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63671. _this._generateMipMaps = generateMipMaps;
  63672. if (options.getContext) {
  63673. _this._canvas = options;
  63674. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  63675. }
  63676. else {
  63677. _this._canvas = document.createElement("canvas");
  63678. if (options.width || options.width === 0) {
  63679. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  63680. }
  63681. else {
  63682. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  63683. }
  63684. }
  63685. var textureSize = _this.getSize();
  63686. _this._canvas.width = textureSize.width;
  63687. _this._canvas.height = textureSize.height;
  63688. _this._context = _this._canvas.getContext("2d");
  63689. return _this;
  63690. }
  63691. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  63692. /**
  63693. * Gets the current state of canRescale
  63694. */
  63695. get: function () {
  63696. return true;
  63697. },
  63698. enumerable: true,
  63699. configurable: true
  63700. });
  63701. DynamicTexture.prototype._recreate = function (textureSize) {
  63702. this._canvas.width = textureSize.width;
  63703. this._canvas.height = textureSize.height;
  63704. this.releaseInternalTexture();
  63705. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  63706. };
  63707. /**
  63708. * Scales the texture
  63709. * @param ratio the scale factor to apply to both width and height
  63710. */
  63711. DynamicTexture.prototype.scale = function (ratio) {
  63712. var textureSize = this.getSize();
  63713. textureSize.width *= ratio;
  63714. textureSize.height *= ratio;
  63715. this._recreate(textureSize);
  63716. };
  63717. /**
  63718. * Resizes the texture
  63719. * @param width the new width
  63720. * @param height the new height
  63721. */
  63722. DynamicTexture.prototype.scaleTo = function (width, height) {
  63723. var textureSize = this.getSize();
  63724. textureSize.width = width;
  63725. textureSize.height = height;
  63726. this._recreate(textureSize);
  63727. };
  63728. /**
  63729. * Gets the context of the canvas used by the texture
  63730. * @returns the canvas context of the dynamic texture
  63731. */
  63732. DynamicTexture.prototype.getContext = function () {
  63733. return this._context;
  63734. };
  63735. /**
  63736. * Clears the texture
  63737. */
  63738. DynamicTexture.prototype.clear = function () {
  63739. var size = this.getSize();
  63740. this._context.fillRect(0, 0, size.width, size.height);
  63741. };
  63742. /**
  63743. * Updates the texture
  63744. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  63745. * @param premulAlpha defines if alpha is stored as premultiplied (default is false)
  63746. */
  63747. DynamicTexture.prototype.update = function (invertY, premulAlpha) {
  63748. if (premulAlpha === void 0) { premulAlpha = false; }
  63749. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, premulAlpha, this._format || undefined);
  63750. };
  63751. /**
  63752. * Draws text onto the texture
  63753. * @param text defines the text to be drawn
  63754. * @param x defines the placement of the text from the left
  63755. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  63756. * @param font defines the font to be used with font-style, font-size, font-name
  63757. * @param color defines the color used for the text
  63758. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  63759. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  63760. * @param update defines whether texture is immediately update (default is true)
  63761. */
  63762. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  63763. if (update === void 0) { update = true; }
  63764. var size = this.getSize();
  63765. if (clearColor) {
  63766. this._context.fillStyle = clearColor;
  63767. this._context.fillRect(0, 0, size.width, size.height);
  63768. }
  63769. this._context.font = font;
  63770. if (x === null || x === undefined) {
  63771. var textSize = this._context.measureText(text);
  63772. x = (size.width - textSize.width) / 2;
  63773. }
  63774. if (y === null || y === undefined) {
  63775. var fontSize = parseInt((font.replace(/\D/g, '')));
  63776. y = (size.height / 2) + (fontSize / 3.65);
  63777. }
  63778. this._context.fillStyle = color;
  63779. this._context.fillText(text, x, y);
  63780. if (update) {
  63781. this.update(invertY);
  63782. }
  63783. };
  63784. /**
  63785. * Clones the texture
  63786. * @returns the clone of the texture.
  63787. */
  63788. DynamicTexture.prototype.clone = function () {
  63789. var scene = this.getScene();
  63790. if (!scene) {
  63791. return this;
  63792. }
  63793. var textureSize = this.getSize();
  63794. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  63795. // Base texture
  63796. newTexture.hasAlpha = this.hasAlpha;
  63797. newTexture.level = this.level;
  63798. // Dynamic Texture
  63799. newTexture.wrapU = this.wrapU;
  63800. newTexture.wrapV = this.wrapV;
  63801. return newTexture;
  63802. };
  63803. /** @hidden */
  63804. DynamicTexture.prototype._rebuild = function () {
  63805. this.update();
  63806. };
  63807. return DynamicTexture;
  63808. }(BABYLON.Texture));
  63809. BABYLON.DynamicTexture = DynamicTexture;
  63810. })(BABYLON || (BABYLON = {}));
  63811. //# sourceMappingURL=babylon.dynamicTexture.js.map
  63812. var BABYLON;
  63813. (function (BABYLON) {
  63814. var VideoTexture = /** @class */ (function (_super) {
  63815. __extends(VideoTexture, _super);
  63816. /**
  63817. * Creates a video texture.
  63818. * Sample : https://doc.babylonjs.com/how_to/video_texture
  63819. * @param {string | null} name optional name, will detect from video source, if not defined
  63820. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  63821. * @param {BABYLON.Scene} scene is obviously the current scene.
  63822. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  63823. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  63824. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  63825. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  63826. */
  63827. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  63828. if (generateMipMaps === void 0) { generateMipMaps = false; }
  63829. if (invertY === void 0) { invertY = false; }
  63830. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63831. if (settings === void 0) { settings = {
  63832. autoPlay: true,
  63833. loop: true,
  63834. autoUpdateTexture: true,
  63835. }; }
  63836. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  63837. _this._stillImageCaptured = false;
  63838. _this._createInternalTexture = function () {
  63839. if (_this._texture != null) {
  63840. return;
  63841. }
  63842. if (!_this._engine.needPOTTextures ||
  63843. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  63844. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  63845. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  63846. }
  63847. else {
  63848. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63849. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63850. _this._generateMipMaps = false;
  63851. }
  63852. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  63853. if (!_this.video.autoplay) {
  63854. var oldHandler_1 = _this.video.onplaying;
  63855. _this.video.onplaying = function () {
  63856. _this.video.onplaying = oldHandler_1;
  63857. _this._texture.isReady = true;
  63858. _this._updateInternalTexture();
  63859. _this.video.pause();
  63860. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  63861. _this.onLoadObservable.notifyObservers(_this);
  63862. }
  63863. };
  63864. _this.video.play();
  63865. }
  63866. else {
  63867. _this._texture.isReady = true;
  63868. _this._updateInternalTexture();
  63869. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  63870. _this.onLoadObservable.notifyObservers(_this);
  63871. }
  63872. }
  63873. };
  63874. _this.reset = function () {
  63875. if (_this._texture == null) {
  63876. return;
  63877. }
  63878. _this._texture.dispose();
  63879. _this._texture = null;
  63880. };
  63881. _this._updateInternalTexture = function (e) {
  63882. if (_this._texture == null || !_this._texture.isReady) {
  63883. return;
  63884. }
  63885. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  63886. return;
  63887. }
  63888. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  63889. };
  63890. _this._engine = _this.getScene().getEngine();
  63891. _this._generateMipMaps = generateMipMaps;
  63892. _this._samplingMode = samplingMode;
  63893. _this.autoUpdateTexture = settings.autoUpdateTexture;
  63894. _this.name = name || _this._getName(src);
  63895. _this.video = _this._getVideo(src);
  63896. if (settings.autoPlay !== undefined) {
  63897. _this.video.autoplay = settings.autoPlay;
  63898. }
  63899. if (settings.loop !== undefined) {
  63900. _this.video.loop = settings.loop;
  63901. }
  63902. _this.video.addEventListener("canplay", _this._createInternalTexture);
  63903. _this.video.addEventListener("paused", _this._updateInternalTexture);
  63904. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  63905. _this.video.addEventListener("emptied", _this.reset);
  63906. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  63907. _this._createInternalTexture();
  63908. }
  63909. return _this;
  63910. }
  63911. VideoTexture.prototype._getName = function (src) {
  63912. if (src instanceof HTMLVideoElement) {
  63913. return src.currentSrc;
  63914. }
  63915. if (typeof src === "object") {
  63916. return src.toString();
  63917. }
  63918. return src;
  63919. };
  63920. ;
  63921. VideoTexture.prototype._getVideo = function (src) {
  63922. if (src instanceof HTMLVideoElement) {
  63923. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  63924. return src;
  63925. }
  63926. var video = document.createElement("video");
  63927. if (typeof src === "string") {
  63928. BABYLON.Tools.SetCorsBehavior(src, video);
  63929. video.src = src;
  63930. }
  63931. else {
  63932. BABYLON.Tools.SetCorsBehavior(src[0], video);
  63933. src.forEach(function (url) {
  63934. var source = document.createElement("source");
  63935. source.src = url;
  63936. video.appendChild(source);
  63937. });
  63938. }
  63939. return video;
  63940. };
  63941. ;
  63942. /**
  63943. * Internal method to initiate `update`.
  63944. */
  63945. VideoTexture.prototype._rebuild = function () {
  63946. this.update();
  63947. };
  63948. /**
  63949. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  63950. */
  63951. VideoTexture.prototype.update = function () {
  63952. if (!this.autoUpdateTexture) {
  63953. // Expecting user to call `updateTexture` manually
  63954. return;
  63955. }
  63956. this.updateTexture(true);
  63957. };
  63958. /**
  63959. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  63960. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  63961. */
  63962. VideoTexture.prototype.updateTexture = function (isVisible) {
  63963. if (!isVisible) {
  63964. return;
  63965. }
  63966. if (this.video.paused && this._stillImageCaptured) {
  63967. return;
  63968. }
  63969. this._stillImageCaptured = true;
  63970. this._updateInternalTexture();
  63971. };
  63972. /**
  63973. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  63974. * @param url New url.
  63975. */
  63976. VideoTexture.prototype.updateURL = function (url) {
  63977. this.video.src = url;
  63978. };
  63979. VideoTexture.prototype.dispose = function () {
  63980. _super.prototype.dispose.call(this);
  63981. this.video.removeEventListener("canplay", this._createInternalTexture);
  63982. this.video.removeEventListener("paused", this._updateInternalTexture);
  63983. this.video.removeEventListener("seeked", this._updateInternalTexture);
  63984. this.video.removeEventListener("emptied", this.reset);
  63985. this.video.pause();
  63986. };
  63987. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  63988. var video = document.createElement("video");
  63989. var constraintsDeviceId;
  63990. if (constraints && constraints.deviceId) {
  63991. constraintsDeviceId = {
  63992. exact: constraints.deviceId,
  63993. };
  63994. }
  63995. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  63996. if (navigator.mediaDevices) {
  63997. navigator.mediaDevices.getUserMedia({ video: constraints })
  63998. .then(function (stream) {
  63999. if (video.mozSrcObject !== undefined) {
  64000. // hack for Firefox < 19
  64001. video.mozSrcObject = stream;
  64002. }
  64003. else {
  64004. video.srcObject = stream;
  64005. }
  64006. var onPlaying = function () {
  64007. if (onReady) {
  64008. onReady(new VideoTexture("video", video, scene, true, true));
  64009. }
  64010. video.removeEventListener("playing", onPlaying);
  64011. };
  64012. video.addEventListener("playing", onPlaying);
  64013. video.play();
  64014. })
  64015. .catch(function (err) {
  64016. BABYLON.Tools.Error(err.name);
  64017. });
  64018. }
  64019. else {
  64020. navigator.getUserMedia =
  64021. navigator.getUserMedia ||
  64022. navigator.webkitGetUserMedia ||
  64023. navigator.mozGetUserMedia ||
  64024. navigator.msGetUserMedia;
  64025. if (navigator.getUserMedia) {
  64026. navigator.getUserMedia({
  64027. video: {
  64028. deviceId: constraintsDeviceId,
  64029. width: {
  64030. min: (constraints && constraints.minWidth) || 256,
  64031. max: (constraints && constraints.maxWidth) || 640,
  64032. },
  64033. height: {
  64034. min: (constraints && constraints.minHeight) || 256,
  64035. max: (constraints && constraints.maxHeight) || 480,
  64036. },
  64037. },
  64038. }, function (stream) {
  64039. if (video.mozSrcObject !== undefined) {
  64040. // hack for Firefox < 19
  64041. video.mozSrcObject = stream;
  64042. }
  64043. else {
  64044. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  64045. }
  64046. video.play();
  64047. if (onReady) {
  64048. onReady(new VideoTexture("video", video, scene, true, true));
  64049. }
  64050. }, function (e) {
  64051. BABYLON.Tools.Error(e.name);
  64052. });
  64053. }
  64054. }
  64055. };
  64056. return VideoTexture;
  64057. }(BABYLON.Texture));
  64058. BABYLON.VideoTexture = VideoTexture;
  64059. })(BABYLON || (BABYLON = {}));
  64060. //# sourceMappingURL=babylon.videoTexture.js.map
  64061. var BABYLON;
  64062. (function (BABYLON) {
  64063. var RawTexture = /** @class */ (function (_super) {
  64064. __extends(RawTexture, _super);
  64065. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  64066. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64067. if (invertY === void 0) { invertY = false; }
  64068. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64069. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64070. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  64071. _this.format = format;
  64072. _this._engine = scene.getEngine();
  64073. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  64074. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64075. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64076. return _this;
  64077. }
  64078. RawTexture.prototype.update = function (data) {
  64079. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  64080. };
  64081. // Statics
  64082. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  64083. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64084. if (invertY === void 0) { invertY = false; }
  64085. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64086. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  64087. };
  64088. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  64089. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64090. if (invertY === void 0) { invertY = false; }
  64091. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64092. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  64093. };
  64094. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  64095. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64096. if (invertY === void 0) { invertY = false; }
  64097. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64098. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  64099. };
  64100. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  64101. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64102. if (invertY === void 0) { invertY = false; }
  64103. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64104. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64105. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  64106. };
  64107. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  64108. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64109. if (invertY === void 0) { invertY = false; }
  64110. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64111. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64112. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  64113. };
  64114. return RawTexture;
  64115. }(BABYLON.Texture));
  64116. BABYLON.RawTexture = RawTexture;
  64117. })(BABYLON || (BABYLON = {}));
  64118. //# sourceMappingURL=babylon.rawTexture.js.map
  64119. var BABYLON;
  64120. (function (BABYLON) {
  64121. /**
  64122. * Class used to store 3D textures containing user data
  64123. */
  64124. var RawTexture3D = /** @class */ (function (_super) {
  64125. __extends(RawTexture3D, _super);
  64126. /**
  64127. * Create a new RawTexture3D
  64128. * @param data defines the data of the texture
  64129. * @param width defines the width of the texture
  64130. * @param height defines the height of the texture
  64131. * @param depth defines the depth of the texture
  64132. * @param format defines the texture format to use
  64133. * @param scene defines the hosting scene
  64134. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  64135. * @param invertY defines if texture must be stored with Y axis inverted
  64136. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  64137. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  64138. */
  64139. function RawTexture3D(data, width, height, depth,
  64140. /** Gets or sets the texture format to use */
  64141. format, scene, generateMipMaps, invertY, samplingMode, textureType) {
  64142. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64143. if (invertY === void 0) { invertY = false; }
  64144. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64145. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64146. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  64147. _this.format = format;
  64148. _this._engine = scene.getEngine();
  64149. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, undefined, textureType);
  64150. _this.is3D = true;
  64151. return _this;
  64152. }
  64153. /**
  64154. * Update the texture with new data
  64155. * @param data defines the data to store in the texture
  64156. */
  64157. RawTexture3D.prototype.update = function (data) {
  64158. if (!this._texture) {
  64159. return;
  64160. }
  64161. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  64162. };
  64163. return RawTexture3D;
  64164. }(BABYLON.Texture));
  64165. BABYLON.RawTexture3D = RawTexture3D;
  64166. })(BABYLON || (BABYLON = {}));
  64167. //# sourceMappingURL=babylon.rawTexture3D.js.map
  64168. var BABYLON;
  64169. (function (BABYLON) {
  64170. /**
  64171. * PostProcessManager is used to manage one or more post processes or post process pipelines
  64172. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  64173. */
  64174. var PostProcessManager = /** @class */ (function () {
  64175. /**
  64176. * Creates a new instance PostProcess
  64177. * @param scene The scene that the post process is associated with.
  64178. */
  64179. function PostProcessManager(scene) {
  64180. this._vertexBuffers = {};
  64181. this._scene = scene;
  64182. }
  64183. PostProcessManager.prototype._prepareBuffers = function () {
  64184. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  64185. return;
  64186. }
  64187. // VBO
  64188. var vertices = [];
  64189. vertices.push(1, 1);
  64190. vertices.push(-1, 1);
  64191. vertices.push(-1, -1);
  64192. vertices.push(1, -1);
  64193. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  64194. this._buildIndexBuffer();
  64195. };
  64196. PostProcessManager.prototype._buildIndexBuffer = function () {
  64197. // Indices
  64198. var indices = [];
  64199. indices.push(0);
  64200. indices.push(1);
  64201. indices.push(2);
  64202. indices.push(0);
  64203. indices.push(2);
  64204. indices.push(3);
  64205. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  64206. };
  64207. /**
  64208. * Rebuilds the vertex buffers of the manager.
  64209. */
  64210. PostProcessManager.prototype._rebuild = function () {
  64211. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  64212. if (!vb) {
  64213. return;
  64214. }
  64215. vb._rebuild();
  64216. this._buildIndexBuffer();
  64217. };
  64218. // Methods
  64219. /**
  64220. * Prepares a frame to be run through a post process.
  64221. * @param sourceTexture The input texture to the post procesess. (default: null)
  64222. * @param postProcesses An array of post processes to be run. (default: null)
  64223. * @returns True if the post processes were able to be run.
  64224. */
  64225. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  64226. if (sourceTexture === void 0) { sourceTexture = null; }
  64227. if (postProcesses === void 0) { postProcesses = null; }
  64228. var camera = this._scene.activeCamera;
  64229. if (!camera) {
  64230. return false;
  64231. }
  64232. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  64233. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  64234. return false;
  64235. }
  64236. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  64237. return true;
  64238. };
  64239. /**
  64240. * Manually render a set of post processes to a texture.
  64241. * @param postProcesses An array of post processes to be run.
  64242. * @param targetTexture The target texture to render to.
  64243. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  64244. * @param faceIndex defines the face to render to if a cubemap is defined as the target
  64245. * @param lodLevel defines which lod of the texture to render to
  64246. */
  64247. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport, faceIndex, lodLevel) {
  64248. if (targetTexture === void 0) { targetTexture = null; }
  64249. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  64250. if (faceIndex === void 0) { faceIndex = 0; }
  64251. if (lodLevel === void 0) { lodLevel = 0; }
  64252. var engine = this._scene.getEngine();
  64253. for (var index = 0; index < postProcesses.length; index++) {
  64254. if (index < postProcesses.length - 1) {
  64255. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  64256. }
  64257. else {
  64258. if (targetTexture) {
  64259. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport, undefined, lodLevel);
  64260. }
  64261. else {
  64262. engine.restoreDefaultFramebuffer();
  64263. }
  64264. }
  64265. var pp = postProcesses[index];
  64266. var effect = pp.apply();
  64267. if (effect) {
  64268. pp.onBeforeRenderObservable.notifyObservers(effect);
  64269. // VBOs
  64270. this._prepareBuffers();
  64271. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  64272. // Draw order
  64273. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  64274. pp.onAfterRenderObservable.notifyObservers(effect);
  64275. }
  64276. }
  64277. // Restore depth buffer
  64278. engine.setDepthBuffer(true);
  64279. engine.setDepthWrite(true);
  64280. };
  64281. /**
  64282. * Finalize the result of the output of the postprocesses.
  64283. * @param doNotPresent If true the result will not be displayed to the screen.
  64284. * @param targetTexture The target texture to render to.
  64285. * @param faceIndex The index of the face to bind the target texture to.
  64286. * @param postProcesses The array of post processes to render.
  64287. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  64288. */
  64289. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  64290. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  64291. var camera = this._scene.activeCamera;
  64292. if (!camera) {
  64293. return;
  64294. }
  64295. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  64296. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  64297. return;
  64298. }
  64299. var engine = this._scene.getEngine();
  64300. for (var index = 0, len = postProcesses.length; index < len; index++) {
  64301. var pp = postProcesses[index];
  64302. if (index < len - 1) {
  64303. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  64304. }
  64305. else {
  64306. if (targetTexture) {
  64307. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  64308. pp._outputTexture = targetTexture;
  64309. }
  64310. else {
  64311. engine.restoreDefaultFramebuffer();
  64312. pp._outputTexture = null;
  64313. }
  64314. }
  64315. if (doNotPresent) {
  64316. break;
  64317. }
  64318. var effect = pp.apply();
  64319. if (effect) {
  64320. pp.onBeforeRenderObservable.notifyObservers(effect);
  64321. // VBOs
  64322. this._prepareBuffers();
  64323. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  64324. // Draw order
  64325. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  64326. pp.onAfterRenderObservable.notifyObservers(effect);
  64327. }
  64328. }
  64329. // Restore states
  64330. engine.setDepthBuffer(true);
  64331. engine.setDepthWrite(true);
  64332. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  64333. };
  64334. /**
  64335. * Disposes of the post process manager.
  64336. */
  64337. PostProcessManager.prototype.dispose = function () {
  64338. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  64339. if (buffer) {
  64340. buffer.dispose();
  64341. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  64342. }
  64343. if (this._indexBuffer) {
  64344. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  64345. this._indexBuffer = null;
  64346. }
  64347. };
  64348. return PostProcessManager;
  64349. }());
  64350. BABYLON.PostProcessManager = PostProcessManager;
  64351. })(BABYLON || (BABYLON = {}));
  64352. //# sourceMappingURL=babylon.postProcessManager.js.map
  64353. var BABYLON;
  64354. (function (BABYLON) {
  64355. /**
  64356. * PostProcess can be used to apply a shader to a texture after it has been rendered
  64357. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  64358. */
  64359. var PostProcess = /** @class */ (function () {
  64360. /**
  64361. * Creates a new instance PostProcess
  64362. * @param name The name of the PostProcess.
  64363. * @param fragmentUrl The url of the fragment shader to be used.
  64364. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  64365. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  64366. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  64367. * @param camera The camera to apply the render pass to.
  64368. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  64369. * @param engine The engine which the post process will be applied. (default: current engine)
  64370. * @param reusable If the post process can be reused on the same frame. (default: false)
  64371. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  64372. * @param textureType Type of textures used when performing the post process. (default: 0)
  64373. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  64374. * @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
  64375. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  64376. */
  64377. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  64378. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  64379. if (defines === void 0) { defines = null; }
  64380. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64381. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  64382. if (blockCompilation === void 0) { blockCompilation = false; }
  64383. this.name = name;
  64384. /**
  64385. * Width of the texture to apply the post process on
  64386. */
  64387. this.width = -1;
  64388. /**
  64389. * Height of the texture to apply the post process on
  64390. */
  64391. this.height = -1;
  64392. /**
  64393. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  64394. */
  64395. this._outputTexture = null;
  64396. /**
  64397. * If the buffer needs to be cleared before applying the post process. (default: true)
  64398. * Should be set to false if shader will overwrite all previous pixels.
  64399. */
  64400. this.autoClear = true;
  64401. /**
  64402. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  64403. */
  64404. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  64405. /**
  64406. * Animations to be used for the post processing
  64407. */
  64408. this.animations = new Array();
  64409. /**
  64410. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  64411. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  64412. */
  64413. this.enablePixelPerfectMode = false;
  64414. /**
  64415. * Force the postprocess to be applied without taking in account viewport
  64416. */
  64417. this.forceFullscreenViewport = true;
  64418. /**
  64419. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  64420. *
  64421. * | Value | Type | Description |
  64422. * | ----- | ----------------------------------- | ----------- |
  64423. * | 1 | SCALEMODE_FLOOR | [engine.scalemode_floor](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_floor) |
  64424. * | 2 | SCALEMODE_NEAREST | [engine.scalemode_nearest](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_nearest) |
  64425. * | 3 | SCALEMODE_CEILING | [engine.scalemode_ceiling](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_ceiling) |
  64426. *
  64427. */
  64428. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  64429. /**
  64430. * Force textures to be a power of two (default: false)
  64431. */
  64432. this.alwaysForcePOT = false;
  64433. /**
  64434. * Number of sample textures (default: 1)
  64435. */
  64436. this.samples = 1;
  64437. /**
  64438. * Modify the scale of the post process to be the same as the viewport (default: false)
  64439. */
  64440. this.adaptScaleToCurrentViewport = false;
  64441. this._reusable = false;
  64442. /**
  64443. * Smart array of input and output textures for the post process.
  64444. */
  64445. this._textures = new BABYLON.SmartArray(2);
  64446. /**
  64447. * The index in _textures that corresponds to the output texture.
  64448. */
  64449. this._currentRenderTextureInd = 0;
  64450. this._scaleRatio = new BABYLON.Vector2(1, 1);
  64451. this._texelSize = BABYLON.Vector2.Zero();
  64452. // Events
  64453. /**
  64454. * An event triggered when the postprocess is activated.
  64455. */
  64456. this.onActivateObservable = new BABYLON.Observable();
  64457. /**
  64458. * An event triggered when the postprocess changes its size.
  64459. */
  64460. this.onSizeChangedObservable = new BABYLON.Observable();
  64461. /**
  64462. * An event triggered when the postprocess applies its effect.
  64463. */
  64464. this.onApplyObservable = new BABYLON.Observable();
  64465. /**
  64466. * An event triggered before rendering the postprocess
  64467. */
  64468. this.onBeforeRenderObservable = new BABYLON.Observable();
  64469. /**
  64470. * An event triggered after rendering the postprocess
  64471. */
  64472. this.onAfterRenderObservable = new BABYLON.Observable();
  64473. if (camera != null) {
  64474. this._camera = camera;
  64475. this._scene = camera.getScene();
  64476. camera.attachPostProcess(this);
  64477. this._engine = this._scene.getEngine();
  64478. this._scene.postProcesses.push(this);
  64479. }
  64480. else if (engine) {
  64481. this._engine = engine;
  64482. this._engine.postProcesses.push(this);
  64483. }
  64484. this._options = options;
  64485. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  64486. this._reusable = reusable || false;
  64487. this._textureType = textureType;
  64488. this._samplers = samplers || [];
  64489. this._samplers.push("textureSampler");
  64490. this._fragmentUrl = fragmentUrl;
  64491. this._vertexUrl = vertexUrl;
  64492. this._parameters = parameters || [];
  64493. this._parameters.push("scale");
  64494. this._indexParameters = indexParameters;
  64495. if (!blockCompilation) {
  64496. this.updateEffect(defines);
  64497. }
  64498. }
  64499. Object.defineProperty(PostProcess.prototype, "onActivate", {
  64500. /**
  64501. * A function that is added to the onActivateObservable
  64502. */
  64503. set: function (callback) {
  64504. if (this._onActivateObserver) {
  64505. this.onActivateObservable.remove(this._onActivateObserver);
  64506. }
  64507. if (callback) {
  64508. this._onActivateObserver = this.onActivateObservable.add(callback);
  64509. }
  64510. },
  64511. enumerable: true,
  64512. configurable: true
  64513. });
  64514. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  64515. /**
  64516. * A function that is added to the onSizeChangedObservable
  64517. */
  64518. set: function (callback) {
  64519. if (this._onSizeChangedObserver) {
  64520. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  64521. }
  64522. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  64523. },
  64524. enumerable: true,
  64525. configurable: true
  64526. });
  64527. Object.defineProperty(PostProcess.prototype, "onApply", {
  64528. /**
  64529. * A function that is added to the onApplyObservable
  64530. */
  64531. set: function (callback) {
  64532. if (this._onApplyObserver) {
  64533. this.onApplyObservable.remove(this._onApplyObserver);
  64534. }
  64535. this._onApplyObserver = this.onApplyObservable.add(callback);
  64536. },
  64537. enumerable: true,
  64538. configurable: true
  64539. });
  64540. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  64541. /**
  64542. * A function that is added to the onBeforeRenderObservable
  64543. */
  64544. set: function (callback) {
  64545. if (this._onBeforeRenderObserver) {
  64546. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  64547. }
  64548. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  64549. },
  64550. enumerable: true,
  64551. configurable: true
  64552. });
  64553. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  64554. /**
  64555. * A function that is added to the onAfterRenderObservable
  64556. */
  64557. set: function (callback) {
  64558. if (this._onAfterRenderObserver) {
  64559. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  64560. }
  64561. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  64562. },
  64563. enumerable: true,
  64564. configurable: true
  64565. });
  64566. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  64567. /**
  64568. * 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
  64569. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  64570. */
  64571. get: function () {
  64572. return this._textures.data[this._currentRenderTextureInd];
  64573. },
  64574. set: function (value) {
  64575. this._forcedOutputTexture = value;
  64576. },
  64577. enumerable: true,
  64578. configurable: true
  64579. });
  64580. /**
  64581. * Gets the camera which post process is applied to.
  64582. * @returns The camera the post process is applied to.
  64583. */
  64584. PostProcess.prototype.getCamera = function () {
  64585. return this._camera;
  64586. };
  64587. Object.defineProperty(PostProcess.prototype, "texelSize", {
  64588. /**
  64589. * Gets the texel size of the postprocess.
  64590. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  64591. */
  64592. get: function () {
  64593. if (this._shareOutputWithPostProcess) {
  64594. return this._shareOutputWithPostProcess.texelSize;
  64595. }
  64596. if (this._forcedOutputTexture) {
  64597. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  64598. }
  64599. return this._texelSize;
  64600. },
  64601. enumerable: true,
  64602. configurable: true
  64603. });
  64604. /**
  64605. * Gets the engine which this post process belongs to.
  64606. * @returns The engine the post process was enabled with.
  64607. */
  64608. PostProcess.prototype.getEngine = function () {
  64609. return this._engine;
  64610. };
  64611. /**
  64612. * The effect that is created when initializing the post process.
  64613. * @returns The created effect corrisponding the the postprocess.
  64614. */
  64615. PostProcess.prototype.getEffect = function () {
  64616. return this._effect;
  64617. };
  64618. /**
  64619. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  64620. * @param postProcess The post process to share the output with.
  64621. * @returns This post process.
  64622. */
  64623. PostProcess.prototype.shareOutputWith = function (postProcess) {
  64624. this._disposeTextures();
  64625. this._shareOutputWithPostProcess = postProcess;
  64626. return this;
  64627. };
  64628. /**
  64629. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  64630. * This should be called if the post process that shares output with this post process is disabled/disposed.
  64631. */
  64632. PostProcess.prototype.useOwnOutput = function () {
  64633. if (this._textures.length == 0) {
  64634. this._textures = new BABYLON.SmartArray(2);
  64635. }
  64636. this._shareOutputWithPostProcess = null;
  64637. };
  64638. /**
  64639. * Updates the effect with the current post process compile time values and recompiles the shader.
  64640. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  64641. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  64642. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  64643. * @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
  64644. * @param onCompiled Called when the shader has been compiled.
  64645. * @param onError Called if there is an error when compiling a shader.
  64646. */
  64647. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  64648. if (defines === void 0) { defines = null; }
  64649. if (uniforms === void 0) { uniforms = null; }
  64650. if (samplers === void 0) { samplers = null; }
  64651. 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);
  64652. };
  64653. /**
  64654. * The post process is reusable if it can be used multiple times within one frame.
  64655. * @returns If the post process is reusable
  64656. */
  64657. PostProcess.prototype.isReusable = function () {
  64658. return this._reusable;
  64659. };
  64660. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  64661. PostProcess.prototype.markTextureDirty = function () {
  64662. this.width = -1;
  64663. };
  64664. /**
  64665. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  64666. * 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.
  64667. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  64668. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  64669. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  64670. * @returns The target texture that was bound to be written to.
  64671. */
  64672. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  64673. var _this = this;
  64674. if (sourceTexture === void 0) { sourceTexture = null; }
  64675. camera = camera || this._camera;
  64676. var scene = camera.getScene();
  64677. var engine = scene.getEngine();
  64678. var maxSize = engine.getCaps().maxTextureSize;
  64679. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  64680. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  64681. // 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
  64682. var webVRCamera = camera.parent;
  64683. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  64684. requiredWidth /= 2;
  64685. }
  64686. var desiredWidth = (this._options.width || requiredWidth);
  64687. var desiredHeight = this._options.height || requiredHeight;
  64688. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  64689. if (this.adaptScaleToCurrentViewport) {
  64690. var currentViewport = engine.currentViewport;
  64691. if (currentViewport) {
  64692. desiredWidth *= currentViewport.width;
  64693. desiredHeight *= currentViewport.height;
  64694. }
  64695. }
  64696. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  64697. if (!this._options.width) {
  64698. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  64699. }
  64700. if (!this._options.height) {
  64701. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  64702. }
  64703. }
  64704. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  64705. if (this._textures.length > 0) {
  64706. for (var i = 0; i < this._textures.length; i++) {
  64707. this._engine._releaseTexture(this._textures.data[i]);
  64708. }
  64709. this._textures.reset();
  64710. }
  64711. this.width = desiredWidth;
  64712. this.height = desiredHeight;
  64713. var textureSize = { width: this.width, height: this.height };
  64714. var textureOptions = {
  64715. generateMipMaps: false,
  64716. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  64717. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  64718. samplingMode: this.renderTargetSamplingMode,
  64719. type: this._textureType
  64720. };
  64721. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  64722. if (this._reusable) {
  64723. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  64724. }
  64725. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  64726. this.onSizeChangedObservable.notifyObservers(this);
  64727. }
  64728. this._textures.forEach(function (texture) {
  64729. if (texture.samples !== _this.samples) {
  64730. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  64731. }
  64732. });
  64733. }
  64734. var target;
  64735. if (this._shareOutputWithPostProcess) {
  64736. target = this._shareOutputWithPostProcess.inputTexture;
  64737. }
  64738. else if (this._forcedOutputTexture) {
  64739. target = this._forcedOutputTexture;
  64740. this.width = this._forcedOutputTexture.width;
  64741. this.height = this._forcedOutputTexture.height;
  64742. }
  64743. else {
  64744. target = this.inputTexture;
  64745. }
  64746. // Bind the input of this post process to be used as the output of the previous post process.
  64747. if (this.enablePixelPerfectMode) {
  64748. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  64749. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, this.forceFullscreenViewport);
  64750. }
  64751. else {
  64752. this._scaleRatio.copyFromFloats(1, 1);
  64753. this._engine.bindFramebuffer(target, 0, undefined, undefined, this.forceFullscreenViewport);
  64754. }
  64755. this.onActivateObservable.notifyObservers(camera);
  64756. // Clear
  64757. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  64758. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  64759. }
  64760. if (this._reusable) {
  64761. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  64762. }
  64763. return target;
  64764. };
  64765. Object.defineProperty(PostProcess.prototype, "isSupported", {
  64766. /**
  64767. * If the post process is supported.
  64768. */
  64769. get: function () {
  64770. return this._effect.isSupported;
  64771. },
  64772. enumerable: true,
  64773. configurable: true
  64774. });
  64775. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  64776. /**
  64777. * The aspect ratio of the output texture.
  64778. */
  64779. get: function () {
  64780. if (this._shareOutputWithPostProcess) {
  64781. return this._shareOutputWithPostProcess.aspectRatio;
  64782. }
  64783. if (this._forcedOutputTexture) {
  64784. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  64785. }
  64786. return this.width / this.height;
  64787. },
  64788. enumerable: true,
  64789. configurable: true
  64790. });
  64791. /**
  64792. * Get a value indicating if the post-process is ready to be used
  64793. * @returns true if the post-process is ready (shader is compiled)
  64794. */
  64795. PostProcess.prototype.isReady = function () {
  64796. return this._effect && this._effect.isReady();
  64797. };
  64798. /**
  64799. * Binds all textures and uniforms to the shader, this will be run on every pass.
  64800. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  64801. */
  64802. PostProcess.prototype.apply = function () {
  64803. // Check
  64804. if (!this._effect || !this._effect.isReady())
  64805. return null;
  64806. // States
  64807. this._engine.enableEffect(this._effect);
  64808. this._engine.setState(false);
  64809. this._engine.setDepthBuffer(false);
  64810. this._engine.setDepthWrite(false);
  64811. // Alpha
  64812. this._engine.setAlphaMode(this.alphaMode);
  64813. if (this.alphaConstants) {
  64814. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  64815. }
  64816. // Bind the output texture of the preivous post process as the input to this post process.
  64817. var source;
  64818. if (this._shareOutputWithPostProcess) {
  64819. source = this._shareOutputWithPostProcess.inputTexture;
  64820. }
  64821. else if (this._forcedOutputTexture) {
  64822. source = this._forcedOutputTexture;
  64823. }
  64824. else {
  64825. source = this.inputTexture;
  64826. }
  64827. this._effect._bindTexture("textureSampler", source);
  64828. // Parameters
  64829. this._effect.setVector2("scale", this._scaleRatio);
  64830. this.onApplyObservable.notifyObservers(this._effect);
  64831. return this._effect;
  64832. };
  64833. PostProcess.prototype._disposeTextures = function () {
  64834. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  64835. return;
  64836. }
  64837. if (this._textures.length > 0) {
  64838. for (var i = 0; i < this._textures.length; i++) {
  64839. this._engine._releaseTexture(this._textures.data[i]);
  64840. }
  64841. }
  64842. this._textures.dispose();
  64843. };
  64844. /**
  64845. * Disposes the post process.
  64846. * @param camera The camera to dispose the post process on.
  64847. */
  64848. PostProcess.prototype.dispose = function (camera) {
  64849. camera = camera || this._camera;
  64850. this._disposeTextures();
  64851. if (this._scene) {
  64852. var index_1 = this._scene.postProcesses.indexOf(this);
  64853. if (index_1 !== -1) {
  64854. this._scene.postProcesses.splice(index_1, 1);
  64855. }
  64856. }
  64857. else {
  64858. var index_2 = this._engine.postProcesses.indexOf(this);
  64859. if (index_2 !== -1) {
  64860. this._engine.postProcesses.splice(index_2, 1);
  64861. }
  64862. }
  64863. if (!camera) {
  64864. return;
  64865. }
  64866. camera.detachPostProcess(this);
  64867. var index = camera._postProcesses.indexOf(this);
  64868. if (index === 0 && camera._postProcesses.length > 0) {
  64869. var firstPostProcess = this._camera._getFirstPostProcess();
  64870. if (firstPostProcess) {
  64871. firstPostProcess.markTextureDirty();
  64872. }
  64873. }
  64874. this.onActivateObservable.clear();
  64875. this.onAfterRenderObservable.clear();
  64876. this.onApplyObservable.clear();
  64877. this.onBeforeRenderObservable.clear();
  64878. this.onSizeChangedObservable.clear();
  64879. };
  64880. return PostProcess;
  64881. }());
  64882. BABYLON.PostProcess = PostProcess;
  64883. })(BABYLON || (BABYLON = {}));
  64884. //# sourceMappingURL=babylon.postProcess.js.map
  64885. var BABYLON;
  64886. (function (BABYLON) {
  64887. var PassPostProcess = /** @class */ (function (_super) {
  64888. __extends(PassPostProcess, _super);
  64889. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  64890. if (camera === void 0) { camera = null; }
  64891. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64892. if (blockCompilation === void 0) { blockCompilation = false; }
  64893. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  64894. }
  64895. return PassPostProcess;
  64896. }(BABYLON.PostProcess));
  64897. BABYLON.PassPostProcess = PassPostProcess;
  64898. })(BABYLON || (BABYLON = {}));
  64899. //# sourceMappingURL=babylon.passPostProcess.js.map
  64900. var __assign = (this && this.__assign) || Object.assign || function(t) {
  64901. for (var s, i = 1, n = arguments.length; i < n; i++) {
  64902. s = arguments[i];
  64903. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  64904. t[p] = s[p];
  64905. }
  64906. return t;
  64907. };
  64908. var BABYLON;
  64909. (function (BABYLON) {
  64910. /**
  64911. * Default implementation IShadowGenerator.
  64912. * This is the main object responsible of generating shadows in the framework.
  64913. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  64914. */
  64915. var ShadowGenerator = /** @class */ (function () {
  64916. /**
  64917. * Creates a ShadowGenerator object.
  64918. * A ShadowGenerator is the required tool to use the shadows.
  64919. * Each light casting shadows needs to use its own ShadowGenerator.
  64920. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  64921. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  64922. * @param light The light object generating the shadows.
  64923. * @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.
  64924. */
  64925. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  64926. this._bias = 0.00005;
  64927. this._normalBias = 0;
  64928. this._blurBoxOffset = 1;
  64929. this._blurScale = 2;
  64930. this._blurKernel = 1;
  64931. this._useKernelBlur = false;
  64932. this._filter = ShadowGenerator.FILTER_NONE;
  64933. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  64934. this._contactHardeningLightSizeUVRatio = 0.1;
  64935. this._darkness = 0;
  64936. this._transparencyShadow = false;
  64937. /**
  64938. * Controls the extent to which the shadows fade out at the edge of the frustum
  64939. * Used only by directionals and spots
  64940. */
  64941. this.frustumEdgeFalloff = 0;
  64942. /**
  64943. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  64944. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  64945. * It might on the other hand introduce peter panning.
  64946. */
  64947. this.forceBackFacesOnly = false;
  64948. this._lightDirection = BABYLON.Vector3.Zero();
  64949. this._viewMatrix = BABYLON.Matrix.Zero();
  64950. this._projectionMatrix = BABYLON.Matrix.Zero();
  64951. this._transformMatrix = BABYLON.Matrix.Zero();
  64952. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  64953. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  64954. this._currentFaceIndex = 0;
  64955. this._currentFaceIndexCache = 0;
  64956. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  64957. this._mapSize = mapSize;
  64958. this._light = light;
  64959. this._scene = light.getScene();
  64960. light._shadowGenerator = this;
  64961. // Texture type fallback from float to int if not supported.
  64962. var caps = this._scene.getEngine().getCaps();
  64963. if (!useFullFloatFirst) {
  64964. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  64965. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  64966. }
  64967. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  64968. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  64969. }
  64970. else {
  64971. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  64972. }
  64973. }
  64974. else {
  64975. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  64976. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  64977. }
  64978. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  64979. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  64980. }
  64981. else {
  64982. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  64983. }
  64984. }
  64985. this._initializeGenerator();
  64986. this._applyFilterValues();
  64987. }
  64988. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  64989. /**
  64990. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  64991. */
  64992. get: function () {
  64993. return this._bias;
  64994. },
  64995. /**
  64996. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  64997. */
  64998. set: function (bias) {
  64999. this._bias = bias;
  65000. },
  65001. enumerable: true,
  65002. configurable: true
  65003. });
  65004. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  65005. /**
  65006. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  65007. */
  65008. get: function () {
  65009. return this._normalBias;
  65010. },
  65011. /**
  65012. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  65013. */
  65014. set: function (normalBias) {
  65015. this._normalBias = normalBias;
  65016. },
  65017. enumerable: true,
  65018. configurable: true
  65019. });
  65020. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  65021. /**
  65022. * Gets the blur box offset: offset applied during the blur pass.
  65023. * Only usefull if useKernelBlur = false
  65024. */
  65025. get: function () {
  65026. return this._blurBoxOffset;
  65027. },
  65028. /**
  65029. * Sets the blur box offset: offset applied during the blur pass.
  65030. * Only usefull if useKernelBlur = false
  65031. */
  65032. set: function (value) {
  65033. if (this._blurBoxOffset === value) {
  65034. return;
  65035. }
  65036. this._blurBoxOffset = value;
  65037. this._disposeBlurPostProcesses();
  65038. },
  65039. enumerable: true,
  65040. configurable: true
  65041. });
  65042. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  65043. /**
  65044. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  65045. * 2 means half of the size.
  65046. */
  65047. get: function () {
  65048. return this._blurScale;
  65049. },
  65050. /**
  65051. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  65052. * 2 means half of the size.
  65053. */
  65054. set: function (value) {
  65055. if (this._blurScale === value) {
  65056. return;
  65057. }
  65058. this._blurScale = value;
  65059. this._disposeBlurPostProcesses();
  65060. },
  65061. enumerable: true,
  65062. configurable: true
  65063. });
  65064. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  65065. /**
  65066. * Gets the blur kernel: kernel size of the blur pass.
  65067. * Only usefull if useKernelBlur = true
  65068. */
  65069. get: function () {
  65070. return this._blurKernel;
  65071. },
  65072. /**
  65073. * Sets the blur kernel: kernel size of the blur pass.
  65074. * Only usefull if useKernelBlur = true
  65075. */
  65076. set: function (value) {
  65077. if (this._blurKernel === value) {
  65078. return;
  65079. }
  65080. this._blurKernel = value;
  65081. this._disposeBlurPostProcesses();
  65082. },
  65083. enumerable: true,
  65084. configurable: true
  65085. });
  65086. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  65087. /**
  65088. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  65089. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  65090. */
  65091. get: function () {
  65092. return this._useKernelBlur;
  65093. },
  65094. /**
  65095. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  65096. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  65097. */
  65098. set: function (value) {
  65099. if (this._useKernelBlur === value) {
  65100. return;
  65101. }
  65102. this._useKernelBlur = value;
  65103. this._disposeBlurPostProcesses();
  65104. },
  65105. enumerable: true,
  65106. configurable: true
  65107. });
  65108. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  65109. /**
  65110. * Gets the depth scale used in ESM mode.
  65111. */
  65112. get: function () {
  65113. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  65114. },
  65115. /**
  65116. * Sets the depth scale used in ESM mode.
  65117. * This can override the scale stored on the light.
  65118. */
  65119. set: function (value) {
  65120. this._depthScale = value;
  65121. },
  65122. enumerable: true,
  65123. configurable: true
  65124. });
  65125. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  65126. /**
  65127. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  65128. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  65129. */
  65130. get: function () {
  65131. return this._filter;
  65132. },
  65133. /**
  65134. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  65135. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  65136. */
  65137. set: function (value) {
  65138. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  65139. if (this._light.needCube()) {
  65140. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  65141. this.useExponentialShadowMap = true;
  65142. return;
  65143. }
  65144. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  65145. this.useCloseExponentialShadowMap = true;
  65146. return;
  65147. }
  65148. // PCF on cubemap would also be expensive
  65149. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  65150. this.usePoissonSampling = true;
  65151. return;
  65152. }
  65153. }
  65154. // Weblg1 fallback for PCF.
  65155. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  65156. if (this._scene.getEngine().webGLVersion === 1) {
  65157. this.usePoissonSampling = true;
  65158. return;
  65159. }
  65160. }
  65161. if (this._filter === value) {
  65162. return;
  65163. }
  65164. this._filter = value;
  65165. this._disposeBlurPostProcesses();
  65166. this._applyFilterValues();
  65167. this._light._markMeshesAsLightDirty();
  65168. },
  65169. enumerable: true,
  65170. configurable: true
  65171. });
  65172. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  65173. /**
  65174. * Gets if the current filter is set to Poisson Sampling.
  65175. */
  65176. get: function () {
  65177. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  65178. },
  65179. /**
  65180. * Sets the current filter to Poisson Sampling.
  65181. */
  65182. set: function (value) {
  65183. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  65184. return;
  65185. }
  65186. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  65187. },
  65188. enumerable: true,
  65189. configurable: true
  65190. });
  65191. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  65192. /**
  65193. * Gets if the current filter is set to VSM.
  65194. * DEPRECATED. Should use useExponentialShadowMap instead.
  65195. */
  65196. get: function () {
  65197. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  65198. return this.useExponentialShadowMap;
  65199. },
  65200. /**
  65201. * Sets the current filter is to VSM.
  65202. * DEPRECATED. Should use useExponentialShadowMap instead.
  65203. */
  65204. set: function (value) {
  65205. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  65206. this.useExponentialShadowMap = value;
  65207. },
  65208. enumerable: true,
  65209. configurable: true
  65210. });
  65211. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  65212. /**
  65213. * Gets if the current filter is set to blurred VSM.
  65214. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  65215. */
  65216. get: function () {
  65217. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  65218. return this.useBlurExponentialShadowMap;
  65219. },
  65220. /**
  65221. * Sets the current filter is to blurred VSM.
  65222. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  65223. */
  65224. set: function (value) {
  65225. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  65226. this.useBlurExponentialShadowMap = value;
  65227. },
  65228. enumerable: true,
  65229. configurable: true
  65230. });
  65231. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  65232. /**
  65233. * Gets if the current filter is set to ESM.
  65234. */
  65235. get: function () {
  65236. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  65237. },
  65238. /**
  65239. * Sets the current filter is to ESM.
  65240. */
  65241. set: function (value) {
  65242. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  65243. return;
  65244. }
  65245. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65246. },
  65247. enumerable: true,
  65248. configurable: true
  65249. });
  65250. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  65251. /**
  65252. * Gets if the current filter is set to filtered ESM.
  65253. */
  65254. get: function () {
  65255. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  65256. },
  65257. /**
  65258. * Gets if the current filter is set to filtered ESM.
  65259. */
  65260. set: function (value) {
  65261. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  65262. return;
  65263. }
  65264. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65265. },
  65266. enumerable: true,
  65267. configurable: true
  65268. });
  65269. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  65270. /**
  65271. * Gets if the current filter is set to "close ESM" (using the inverse of the
  65272. * exponential to prevent steep falloff artifacts).
  65273. */
  65274. get: function () {
  65275. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  65276. },
  65277. /**
  65278. * Sets the current filter to "close ESM" (using the inverse of the
  65279. * exponential to prevent steep falloff artifacts).
  65280. */
  65281. set: function (value) {
  65282. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  65283. return;
  65284. }
  65285. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65286. },
  65287. enumerable: true,
  65288. configurable: true
  65289. });
  65290. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  65291. /**
  65292. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  65293. * exponential to prevent steep falloff artifacts).
  65294. */
  65295. get: function () {
  65296. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  65297. },
  65298. /**
  65299. * Sets the current filter to filtered "close ESM" (using the inverse of the
  65300. * exponential to prevent steep falloff artifacts).
  65301. */
  65302. set: function (value) {
  65303. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  65304. return;
  65305. }
  65306. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65307. },
  65308. enumerable: true,
  65309. configurable: true
  65310. });
  65311. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  65312. /**
  65313. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  65314. */
  65315. get: function () {
  65316. return this.filter === ShadowGenerator.FILTER_PCF;
  65317. },
  65318. /**
  65319. * Sets the current filter to "PCF" (percentage closer filtering).
  65320. */
  65321. set: function (value) {
  65322. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  65323. return;
  65324. }
  65325. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  65326. },
  65327. enumerable: true,
  65328. configurable: true
  65329. });
  65330. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  65331. /**
  65332. * Gets the PCF or PCSS Quality.
  65333. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  65334. */
  65335. get: function () {
  65336. return this._filteringQuality;
  65337. },
  65338. /**
  65339. * Sets the PCF or PCSS Quality.
  65340. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  65341. */
  65342. set: function (filteringQuality) {
  65343. this._filteringQuality = filteringQuality;
  65344. },
  65345. enumerable: true,
  65346. configurable: true
  65347. });
  65348. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  65349. /**
  65350. * Gets if the current filter is set to "PCSS" (contact hardening).
  65351. */
  65352. get: function () {
  65353. return this.filter === ShadowGenerator.FILTER_PCSS;
  65354. },
  65355. /**
  65356. * Sets the current filter to "PCSS" (contact hardening).
  65357. */
  65358. set: function (value) {
  65359. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  65360. return;
  65361. }
  65362. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  65363. },
  65364. enumerable: true,
  65365. configurable: true
  65366. });
  65367. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  65368. /**
  65369. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  65370. * Using a ratio helps keeping shape stability independently of the map size.
  65371. *
  65372. * It does not account for the light projection as it was having too much
  65373. * instability during the light setup or during light position changes.
  65374. *
  65375. * Only valid if useContactHardeningShadow is true.
  65376. */
  65377. get: function () {
  65378. return this._contactHardeningLightSizeUVRatio;
  65379. },
  65380. /**
  65381. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  65382. * Using a ratio helps keeping shape stability independently of the map size.
  65383. *
  65384. * It does not account for the light projection as it was having too much
  65385. * instability during the light setup or during light position changes.
  65386. *
  65387. * Only valid if useContactHardeningShadow is true.
  65388. */
  65389. set: function (contactHardeningLightSizeUVRatio) {
  65390. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  65391. },
  65392. enumerable: true,
  65393. configurable: true
  65394. });
  65395. /**
  65396. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  65397. * 0 means strongest and 1 would means no shadow.
  65398. * @returns the darkness.
  65399. */
  65400. ShadowGenerator.prototype.getDarkness = function () {
  65401. return this._darkness;
  65402. };
  65403. /**
  65404. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  65405. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  65406. * @returns the shadow generator allowing fluent coding.
  65407. */
  65408. ShadowGenerator.prototype.setDarkness = function (darkness) {
  65409. if (darkness >= 1.0)
  65410. this._darkness = 1.0;
  65411. else if (darkness <= 0.0)
  65412. this._darkness = 0.0;
  65413. else
  65414. this._darkness = darkness;
  65415. return this;
  65416. };
  65417. /**
  65418. * Sets the ability to have transparent shadow (boolean).
  65419. * @param transparent True if transparent else False
  65420. * @returns the shadow generator allowing fluent coding
  65421. */
  65422. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  65423. this._transparencyShadow = transparent;
  65424. return this;
  65425. };
  65426. /**
  65427. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  65428. * @returns The render target texture if present otherwise, null
  65429. */
  65430. ShadowGenerator.prototype.getShadowMap = function () {
  65431. return this._shadowMap;
  65432. };
  65433. /**
  65434. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  65435. * @returns The render target texture if the shadow map is present otherwise, null
  65436. */
  65437. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  65438. if (this._shadowMap2) {
  65439. return this._shadowMap2;
  65440. }
  65441. return this._shadowMap;
  65442. };
  65443. /**
  65444. * Helper function to add a mesh and its descendants to the list of shadow casters.
  65445. * @param mesh Mesh to add
  65446. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  65447. * @returns the Shadow Generator itself
  65448. */
  65449. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  65450. if (includeDescendants === void 0) { includeDescendants = true; }
  65451. if (!this._shadowMap) {
  65452. return this;
  65453. }
  65454. if (!this._shadowMap.renderList) {
  65455. this._shadowMap.renderList = [];
  65456. }
  65457. this._shadowMap.renderList.push(mesh);
  65458. if (includeDescendants) {
  65459. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  65460. }
  65461. return this;
  65462. var _a;
  65463. };
  65464. /**
  65465. * Helper function to remove a mesh and its descendants from the list of shadow casters
  65466. * @param mesh Mesh to remove
  65467. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  65468. * @returns the Shadow Generator itself
  65469. */
  65470. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  65471. if (includeDescendants === void 0) { includeDescendants = true; }
  65472. if (!this._shadowMap || !this._shadowMap.renderList) {
  65473. return this;
  65474. }
  65475. var index = this._shadowMap.renderList.indexOf(mesh);
  65476. if (index !== -1) {
  65477. this._shadowMap.renderList.splice(index, 1);
  65478. }
  65479. if (includeDescendants) {
  65480. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  65481. var child = _a[_i];
  65482. this.removeShadowCaster(child);
  65483. }
  65484. }
  65485. return this;
  65486. };
  65487. /**
  65488. * Returns the associated light object.
  65489. * @returns the light generating the shadow
  65490. */
  65491. ShadowGenerator.prototype.getLight = function () {
  65492. return this._light;
  65493. };
  65494. ShadowGenerator.prototype._initializeGenerator = function () {
  65495. this._light._markMeshesAsLightDirty();
  65496. this._initializeShadowMap();
  65497. };
  65498. ShadowGenerator.prototype._initializeShadowMap = function () {
  65499. var _this = this;
  65500. // Render target
  65501. var engine = this._scene.getEngine();
  65502. if (engine.webGLVersion > 1) {
  65503. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  65504. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  65505. }
  65506. else {
  65507. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  65508. }
  65509. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65510. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65511. this._shadowMap.anisotropicFilteringLevel = 1;
  65512. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  65513. this._shadowMap.renderParticles = false;
  65514. this._shadowMap.ignoreCameraViewport = true;
  65515. // Record Face Index before render.
  65516. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  65517. _this._currentFaceIndex = faceIndex;
  65518. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  65519. engine.setColorWrite(false);
  65520. }
  65521. });
  65522. // Custom render function.
  65523. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  65524. // Blur if required afer render.
  65525. this._shadowMap.onAfterUnbindObservable.add(function () {
  65526. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  65527. engine.setColorWrite(true);
  65528. }
  65529. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  65530. return;
  65531. }
  65532. var shadowMap = _this.getShadowMapForRendering();
  65533. if (shadowMap) {
  65534. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  65535. }
  65536. });
  65537. // Clear according to the chosen filter.
  65538. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  65539. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  65540. this._shadowMap.onClearObservable.add(function (engine) {
  65541. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  65542. engine.clear(clearOne, false, true, false);
  65543. }
  65544. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  65545. engine.clear(clearZero, true, true, false);
  65546. }
  65547. else {
  65548. engine.clear(clearOne, true, true, false);
  65549. }
  65550. });
  65551. };
  65552. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  65553. var _this = this;
  65554. var engine = this._scene.getEngine();
  65555. var targetSize = this._mapSize / this.blurScale;
  65556. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  65557. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  65558. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65559. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65560. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  65561. }
  65562. if (this.useKernelBlur) {
  65563. 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);
  65564. this._kernelBlurXPostprocess.width = targetSize;
  65565. this._kernelBlurXPostprocess.height = targetSize;
  65566. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  65567. effect.setTexture("textureSampler", _this._shadowMap);
  65568. });
  65569. 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);
  65570. this._kernelBlurXPostprocess.autoClear = false;
  65571. this._kernelBlurYPostprocess.autoClear = false;
  65572. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  65573. this._kernelBlurXPostprocess.packedFloat = true;
  65574. this._kernelBlurYPostprocess.packedFloat = true;
  65575. }
  65576. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  65577. }
  65578. else {
  65579. 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);
  65580. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  65581. effect.setFloat2("screenSize", targetSize, targetSize);
  65582. effect.setTexture("textureSampler", _this._shadowMap);
  65583. });
  65584. this._boxBlurPostprocess.autoClear = false;
  65585. this._blurPostProcesses = [this._boxBlurPostprocess];
  65586. }
  65587. };
  65588. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  65589. var index;
  65590. var engine = this._scene.getEngine();
  65591. if (depthOnlySubMeshes.length) {
  65592. engine.setColorWrite(false);
  65593. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  65594. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  65595. }
  65596. engine.setColorWrite(true);
  65597. }
  65598. for (index = 0; index < opaqueSubMeshes.length; index++) {
  65599. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  65600. }
  65601. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  65602. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  65603. }
  65604. if (this._transparencyShadow) {
  65605. for (index = 0; index < transparentSubMeshes.length; index++) {
  65606. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  65607. }
  65608. }
  65609. };
  65610. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  65611. var _this = this;
  65612. var mesh = subMesh.getRenderingMesh();
  65613. var scene = this._scene;
  65614. var engine = scene.getEngine();
  65615. var material = subMesh.getMaterial();
  65616. if (!material) {
  65617. return;
  65618. }
  65619. // Culling
  65620. engine.setState(material.backFaceCulling);
  65621. // Managing instances
  65622. var batch = mesh._getInstancesRenderList(subMesh._id);
  65623. if (batch.mustReturn) {
  65624. return;
  65625. }
  65626. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  65627. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  65628. engine.enableEffect(this._effect);
  65629. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  65630. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  65631. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  65632. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  65633. this._effect.setVector3("lightData", this._cachedDirection);
  65634. }
  65635. else {
  65636. this._effect.setVector3("lightData", this._cachedPosition);
  65637. }
  65638. if (scene.activeCamera) {
  65639. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  65640. }
  65641. // Alpha test
  65642. if (material && material.needAlphaTesting()) {
  65643. var alphaTexture = material.getAlphaTestTexture();
  65644. if (alphaTexture) {
  65645. this._effect.setTexture("diffuseSampler", alphaTexture);
  65646. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  65647. }
  65648. }
  65649. // Bones
  65650. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  65651. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  65652. }
  65653. // Morph targets
  65654. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  65655. if (this.forceBackFacesOnly) {
  65656. engine.setState(true, 0, false, true);
  65657. }
  65658. // Draw
  65659. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  65660. if (this.forceBackFacesOnly) {
  65661. engine.setState(true, 0, false, false);
  65662. }
  65663. }
  65664. else {
  65665. // Need to reset refresh rate of the shadowMap
  65666. if (this._shadowMap) {
  65667. this._shadowMap.resetRefreshCounter();
  65668. }
  65669. }
  65670. };
  65671. ShadowGenerator.prototype._applyFilterValues = function () {
  65672. if (!this._shadowMap) {
  65673. return;
  65674. }
  65675. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  65676. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  65677. }
  65678. else {
  65679. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  65680. }
  65681. };
  65682. /**
  65683. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  65684. * @param onCompiled Callback triggered at the and of the effects compilation
  65685. * @param options Sets of optional options forcing the compilation with different modes
  65686. */
  65687. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  65688. var _this = this;
  65689. var localOptions = __assign({ useInstances: false }, options);
  65690. var shadowMap = this.getShadowMap();
  65691. if (!shadowMap) {
  65692. if (onCompiled) {
  65693. onCompiled(this);
  65694. }
  65695. return;
  65696. }
  65697. var renderList = shadowMap.renderList;
  65698. if (!renderList) {
  65699. if (onCompiled) {
  65700. onCompiled(this);
  65701. }
  65702. return;
  65703. }
  65704. var subMeshes = new Array();
  65705. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  65706. var mesh = renderList_1[_i];
  65707. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  65708. }
  65709. if (subMeshes.length === 0) {
  65710. if (onCompiled) {
  65711. onCompiled(this);
  65712. }
  65713. return;
  65714. }
  65715. var currentIndex = 0;
  65716. var checkReady = function () {
  65717. if (!_this._scene || !_this._scene.getEngine()) {
  65718. return;
  65719. }
  65720. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  65721. currentIndex++;
  65722. if (currentIndex >= subMeshes.length) {
  65723. if (onCompiled) {
  65724. onCompiled(_this);
  65725. }
  65726. return;
  65727. }
  65728. }
  65729. setTimeout(checkReady, 16);
  65730. };
  65731. checkReady();
  65732. };
  65733. /**
  65734. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  65735. * @param options Sets of optional options forcing the compilation with different modes
  65736. * @returns A promise that resolves when the compilation completes
  65737. */
  65738. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  65739. var _this = this;
  65740. return new Promise(function (resolve) {
  65741. _this.forceCompilation(function () {
  65742. resolve();
  65743. }, options);
  65744. });
  65745. };
  65746. /**
  65747. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  65748. * @param subMesh The submesh we want to render in the shadow map
  65749. * @param useInstances Defines wether will draw in the map using instances
  65750. * @returns true if ready otherwise, false
  65751. */
  65752. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  65753. var defines = [];
  65754. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  65755. defines.push("#define FLOAT");
  65756. }
  65757. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  65758. defines.push("#define ESM");
  65759. }
  65760. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  65761. defines.push("#define DEPTHTEXTURE");
  65762. }
  65763. var attribs = [BABYLON.VertexBuffer.PositionKind];
  65764. var mesh = subMesh.getMesh();
  65765. var material = subMesh.getMaterial();
  65766. // Normal bias.
  65767. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  65768. attribs.push(BABYLON.VertexBuffer.NormalKind);
  65769. defines.push("#define NORMAL");
  65770. if (mesh.nonUniformScaling) {
  65771. defines.push("#define NONUNIFORMSCALING");
  65772. }
  65773. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  65774. defines.push("#define DIRECTIONINLIGHTDATA");
  65775. }
  65776. }
  65777. // Alpha test
  65778. if (material && material.needAlphaTesting()) {
  65779. var alphaTexture = material.getAlphaTestTexture();
  65780. if (alphaTexture) {
  65781. defines.push("#define ALPHATEST");
  65782. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  65783. attribs.push(BABYLON.VertexBuffer.UVKind);
  65784. defines.push("#define UV1");
  65785. }
  65786. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  65787. if (alphaTexture.coordinatesIndex === 1) {
  65788. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  65789. defines.push("#define UV2");
  65790. }
  65791. }
  65792. }
  65793. }
  65794. // Bones
  65795. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  65796. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  65797. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  65798. if (mesh.numBoneInfluencers > 4) {
  65799. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  65800. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  65801. }
  65802. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  65803. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  65804. }
  65805. else {
  65806. defines.push("#define NUM_BONE_INFLUENCERS 0");
  65807. }
  65808. // Morph targets
  65809. var manager = mesh.morphTargetManager;
  65810. var morphInfluencers = 0;
  65811. if (manager) {
  65812. if (manager.numInfluencers > 0) {
  65813. defines.push("#define MORPHTARGETS");
  65814. morphInfluencers = manager.numInfluencers;
  65815. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  65816. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  65817. }
  65818. }
  65819. // Instances
  65820. if (useInstances) {
  65821. defines.push("#define INSTANCES");
  65822. attribs.push("world0");
  65823. attribs.push("world1");
  65824. attribs.push("world2");
  65825. attribs.push("world3");
  65826. }
  65827. // Get correct effect
  65828. var join = defines.join("\n");
  65829. if (this._cachedDefines !== join) {
  65830. this._cachedDefines = join;
  65831. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  65832. }
  65833. if (!this._effect.isReady()) {
  65834. return false;
  65835. }
  65836. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  65837. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  65838. this._initializeBlurRTTAndPostProcesses();
  65839. }
  65840. }
  65841. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  65842. return false;
  65843. }
  65844. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  65845. return false;
  65846. }
  65847. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  65848. return false;
  65849. }
  65850. return true;
  65851. };
  65852. /**
  65853. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  65854. * @param defines Defines of the material we want to update
  65855. * @param lightIndex Index of the light in the enabled light list of the material
  65856. */
  65857. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  65858. var scene = this._scene;
  65859. var light = this._light;
  65860. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  65861. return;
  65862. }
  65863. defines["SHADOW" + lightIndex] = true;
  65864. if (this.useContactHardeningShadow) {
  65865. defines["SHADOWPCSS" + lightIndex] = true;
  65866. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  65867. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  65868. }
  65869. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  65870. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  65871. }
  65872. // else default to high.
  65873. }
  65874. if (this.usePercentageCloserFiltering) {
  65875. defines["SHADOWPCF" + lightIndex] = true;
  65876. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  65877. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  65878. }
  65879. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  65880. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  65881. }
  65882. // else default to high.
  65883. }
  65884. else if (this.usePoissonSampling) {
  65885. defines["SHADOWPOISSON" + lightIndex] = true;
  65886. }
  65887. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  65888. defines["SHADOWESM" + lightIndex] = true;
  65889. }
  65890. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  65891. defines["SHADOWCLOSEESM" + lightIndex] = true;
  65892. }
  65893. if (light.needCube()) {
  65894. defines["SHADOWCUBE" + lightIndex] = true;
  65895. }
  65896. };
  65897. /**
  65898. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  65899. * defined in the generator but impacting the effect).
  65900. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  65901. * @param effect The effect we are binfing the information for
  65902. */
  65903. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  65904. var light = this._light;
  65905. var scene = this._scene;
  65906. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  65907. return;
  65908. }
  65909. var camera = scene.activeCamera;
  65910. if (!camera) {
  65911. return;
  65912. }
  65913. var shadowMap = this.getShadowMap();
  65914. if (!shadowMap) {
  65915. return;
  65916. }
  65917. if (!light.needCube()) {
  65918. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  65919. }
  65920. // Only PCF uses depth stencil texture.
  65921. if (this._filter === ShadowGenerator.FILTER_PCF) {
  65922. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  65923. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  65924. }
  65925. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  65926. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  65927. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  65928. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  65929. }
  65930. else {
  65931. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  65932. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  65933. }
  65934. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  65935. };
  65936. /**
  65937. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  65938. * (eq to shadow prjection matrix * light transform matrix)
  65939. * @returns The transform matrix used to create the shadow map
  65940. */
  65941. ShadowGenerator.prototype.getTransformMatrix = function () {
  65942. var scene = this._scene;
  65943. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  65944. return this._transformMatrix;
  65945. }
  65946. this._currentRenderID = scene.getRenderId();
  65947. this._currentFaceIndexCache = this._currentFaceIndex;
  65948. var lightPosition = this._light.position;
  65949. if (this._light.computeTransformedInformation()) {
  65950. lightPosition = this._light.transformedPosition;
  65951. }
  65952. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  65953. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  65954. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  65955. }
  65956. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  65957. this._cachedPosition.copyFrom(lightPosition);
  65958. this._cachedDirection.copyFrom(this._lightDirection);
  65959. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  65960. var shadowMap = this.getShadowMap();
  65961. if (shadowMap) {
  65962. var renderList = shadowMap.renderList;
  65963. if (renderList) {
  65964. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  65965. }
  65966. }
  65967. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  65968. }
  65969. return this._transformMatrix;
  65970. };
  65971. /**
  65972. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  65973. * Cube and 2D textures for instance.
  65974. */
  65975. ShadowGenerator.prototype.recreateShadowMap = function () {
  65976. var shadowMap = this._shadowMap;
  65977. if (!shadowMap) {
  65978. return;
  65979. }
  65980. // Track render list.
  65981. var renderList = shadowMap.renderList;
  65982. // Clean up existing data.
  65983. this._disposeRTTandPostProcesses();
  65984. // Reinitializes.
  65985. this._initializeGenerator();
  65986. // Reaffect the filter to ensure a correct fallback if necessary.
  65987. this.filter = this.filter;
  65988. // Reaffect the filter.
  65989. this._applyFilterValues();
  65990. // Reaffect Render List.
  65991. this._shadowMap.renderList = renderList;
  65992. };
  65993. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  65994. if (this._shadowMap2) {
  65995. this._shadowMap2.dispose();
  65996. this._shadowMap2 = null;
  65997. }
  65998. if (this._boxBlurPostprocess) {
  65999. this._boxBlurPostprocess.dispose();
  66000. this._boxBlurPostprocess = null;
  66001. }
  66002. if (this._kernelBlurXPostprocess) {
  66003. this._kernelBlurXPostprocess.dispose();
  66004. this._kernelBlurXPostprocess = null;
  66005. }
  66006. if (this._kernelBlurYPostprocess) {
  66007. this._kernelBlurYPostprocess.dispose();
  66008. this._kernelBlurYPostprocess = null;
  66009. }
  66010. this._blurPostProcesses = [];
  66011. };
  66012. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  66013. if (this._shadowMap) {
  66014. this._shadowMap.dispose();
  66015. this._shadowMap = null;
  66016. }
  66017. this._disposeBlurPostProcesses();
  66018. };
  66019. /**
  66020. * Disposes the ShadowGenerator.
  66021. * Returns nothing.
  66022. */
  66023. ShadowGenerator.prototype.dispose = function () {
  66024. this._disposeRTTandPostProcesses();
  66025. if (this._light) {
  66026. this._light._shadowGenerator = null;
  66027. this._light._markMeshesAsLightDirty();
  66028. }
  66029. };
  66030. /**
  66031. * Serializes the shadow generator setup to a json object.
  66032. * @returns The serialized JSON object
  66033. */
  66034. ShadowGenerator.prototype.serialize = function () {
  66035. var serializationObject = {};
  66036. var shadowMap = this.getShadowMap();
  66037. if (!shadowMap) {
  66038. return serializationObject;
  66039. }
  66040. serializationObject.lightId = this._light.id;
  66041. serializationObject.mapSize = shadowMap.getRenderSize();
  66042. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  66043. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  66044. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  66045. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  66046. serializationObject.usePoissonSampling = this.usePoissonSampling;
  66047. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  66048. serializationObject.depthScale = this.depthScale;
  66049. serializationObject.darkness = this.getDarkness();
  66050. serializationObject.blurBoxOffset = this.blurBoxOffset;
  66051. serializationObject.blurKernel = this.blurKernel;
  66052. serializationObject.blurScale = this.blurScale;
  66053. serializationObject.useKernelBlur = this.useKernelBlur;
  66054. serializationObject.transparencyShadow = this._transparencyShadow;
  66055. serializationObject.frustumEdgeFalloff = this.frustumEdgeFalloff;
  66056. serializationObject.bias = this.bias;
  66057. serializationObject.normalBias = this.normalBias;
  66058. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  66059. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  66060. serializationObject.filteringQuality = this.filteringQuality;
  66061. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  66062. serializationObject.renderList = [];
  66063. if (shadowMap.renderList) {
  66064. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  66065. var mesh = shadowMap.renderList[meshIndex];
  66066. serializationObject.renderList.push(mesh.id);
  66067. }
  66068. }
  66069. return serializationObject;
  66070. };
  66071. /**
  66072. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  66073. * @param parsedShadowGenerator The JSON object to parse
  66074. * @param scene The scene to create the shadow map for
  66075. * @returns The parsed shadow generator
  66076. */
  66077. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  66078. //casting to point light, as light is missing the position attr and typescript complains.
  66079. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  66080. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  66081. var shadowMap = shadowGenerator.getShadowMap();
  66082. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  66083. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  66084. meshes.forEach(function (mesh) {
  66085. if (!shadowMap) {
  66086. return;
  66087. }
  66088. if (!shadowMap.renderList) {
  66089. shadowMap.renderList = [];
  66090. }
  66091. shadowMap.renderList.push(mesh);
  66092. });
  66093. }
  66094. if (parsedShadowGenerator.usePoissonSampling) {
  66095. shadowGenerator.usePoissonSampling = true;
  66096. }
  66097. else if (parsedShadowGenerator.useExponentialShadowMap) {
  66098. shadowGenerator.useExponentialShadowMap = true;
  66099. }
  66100. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  66101. shadowGenerator.useBlurExponentialShadowMap = true;
  66102. }
  66103. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  66104. shadowGenerator.useCloseExponentialShadowMap = true;
  66105. }
  66106. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  66107. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  66108. }
  66109. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  66110. shadowGenerator.usePercentageCloserFiltering = true;
  66111. }
  66112. else if (parsedShadowGenerator.useContactHardeningShadow) {
  66113. shadowGenerator.useContactHardeningShadow = true;
  66114. }
  66115. if (parsedShadowGenerator.filteringQuality) {
  66116. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  66117. }
  66118. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  66119. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  66120. }
  66121. // Backward compat
  66122. else if (parsedShadowGenerator.useVarianceShadowMap) {
  66123. shadowGenerator.useExponentialShadowMap = true;
  66124. }
  66125. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  66126. shadowGenerator.useBlurExponentialShadowMap = true;
  66127. }
  66128. if (parsedShadowGenerator.depthScale) {
  66129. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  66130. }
  66131. if (parsedShadowGenerator.blurScale) {
  66132. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  66133. }
  66134. if (parsedShadowGenerator.blurBoxOffset) {
  66135. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  66136. }
  66137. if (parsedShadowGenerator.useKernelBlur) {
  66138. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  66139. }
  66140. if (parsedShadowGenerator.blurKernel) {
  66141. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  66142. }
  66143. if (parsedShadowGenerator.bias !== undefined) {
  66144. shadowGenerator.bias = parsedShadowGenerator.bias;
  66145. }
  66146. if (parsedShadowGenerator.normalBias !== undefined) {
  66147. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  66148. }
  66149. if (parsedShadowGenerator.frustumEdgeFalloff !== undefined) {
  66150. shadowGenerator.frustumEdgeFalloff = parsedShadowGenerator.frustumEdgeFalloff;
  66151. }
  66152. if (parsedShadowGenerator.darkness) {
  66153. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  66154. }
  66155. if (parsedShadowGenerator.transparencyShadow) {
  66156. shadowGenerator.setTransparencyShadow(true);
  66157. }
  66158. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  66159. return shadowGenerator;
  66160. };
  66161. /**
  66162. * Shadow generator mode None: no filtering applied.
  66163. */
  66164. ShadowGenerator.FILTER_NONE = 0;
  66165. /**
  66166. * Shadow generator mode ESM: Exponential Shadow Mapping.
  66167. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66168. */
  66169. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  66170. /**
  66171. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  66172. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  66173. */
  66174. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  66175. /**
  66176. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  66177. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66178. */
  66179. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  66180. /**
  66181. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  66182. * edge artifacts on steep falloff.
  66183. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66184. */
  66185. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  66186. /**
  66187. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  66188. * edge artifacts on steep falloff.
  66189. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66190. */
  66191. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  66192. /**
  66193. * Shadow generator mode PCF: Percentage Closer Filtering
  66194. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  66195. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  66196. */
  66197. ShadowGenerator.FILTER_PCF = 6;
  66198. /**
  66199. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  66200. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  66201. * Contact Hardening
  66202. */
  66203. ShadowGenerator.FILTER_PCSS = 7;
  66204. /**
  66205. * Reserved for PCF and PCSS
  66206. * Highest Quality.
  66207. *
  66208. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  66209. *
  66210. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  66211. */
  66212. ShadowGenerator.QUALITY_HIGH = 0;
  66213. /**
  66214. * Reserved for PCF and PCSS
  66215. * Good tradeoff for quality/perf cross devices
  66216. *
  66217. * Execute PCF on a 3*3 kernel.
  66218. *
  66219. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  66220. */
  66221. ShadowGenerator.QUALITY_MEDIUM = 1;
  66222. /**
  66223. * Reserved for PCF and PCSS
  66224. * The lowest quality but the fastest.
  66225. *
  66226. * Execute PCF on a 1*1 kernel.
  66227. *
  66228. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  66229. */
  66230. ShadowGenerator.QUALITY_LOW = 2;
  66231. return ShadowGenerator;
  66232. }());
  66233. BABYLON.ShadowGenerator = ShadowGenerator;
  66234. })(BABYLON || (BABYLON = {}));
  66235. //# sourceMappingURL=babylon.shadowGenerator.js.map
  66236. var BABYLON;
  66237. (function (BABYLON) {
  66238. var DefaultLoadingScreen = /** @class */ (function () {
  66239. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  66240. if (_loadingText === void 0) { _loadingText = ""; }
  66241. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  66242. var _this = this;
  66243. this._renderingCanvas = _renderingCanvas;
  66244. this._loadingText = _loadingText;
  66245. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  66246. // Resize
  66247. this._resizeLoadingUI = function () {
  66248. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  66249. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  66250. if (!_this._loadingDiv) {
  66251. return;
  66252. }
  66253. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  66254. _this._loadingDiv.style.left = canvasRect.left + "px";
  66255. _this._loadingDiv.style.top = canvasRect.top + "px";
  66256. _this._loadingDiv.style.width = canvasRect.width + "px";
  66257. _this._loadingDiv.style.height = canvasRect.height + "px";
  66258. };
  66259. }
  66260. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  66261. if (this._loadingDiv) {
  66262. // Do not add a loading screen if there is already one
  66263. return;
  66264. }
  66265. this._loadingDiv = document.createElement("div");
  66266. this._loadingDiv.id = "babylonjsLoadingDiv";
  66267. this._loadingDiv.style.opacity = "0";
  66268. this._loadingDiv.style.transition = "opacity 1.5s ease";
  66269. this._loadingDiv.style.pointerEvents = "none";
  66270. // Loading text
  66271. this._loadingTextDiv = document.createElement("div");
  66272. this._loadingTextDiv.style.position = "absolute";
  66273. this._loadingTextDiv.style.left = "0";
  66274. this._loadingTextDiv.style.top = "50%";
  66275. this._loadingTextDiv.style.marginTop = "80px";
  66276. this._loadingTextDiv.style.width = "100%";
  66277. this._loadingTextDiv.style.height = "20px";
  66278. this._loadingTextDiv.style.fontFamily = "Arial";
  66279. this._loadingTextDiv.style.fontSize = "14px";
  66280. this._loadingTextDiv.style.color = "white";
  66281. this._loadingTextDiv.style.textAlign = "center";
  66282. this._loadingTextDiv.innerHTML = "Loading";
  66283. this._loadingDiv.appendChild(this._loadingTextDiv);
  66284. //set the predefined text
  66285. this._loadingTextDiv.innerHTML = this._loadingText;
  66286. // Generating keyframes
  66287. var style = document.createElement('style');
  66288. style.type = 'text/css';
  66289. 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 }";
  66290. style.innerHTML = keyFrames;
  66291. document.getElementsByTagName('head')[0].appendChild(style);
  66292. // Loading img
  66293. var imgBack = new Image();
  66294. imgBack.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAHgAAAB4CAYAAAA5ZDbSAAAAAXNSR0IArs4c6QAAAARnQ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Hd5J2CnesLuyGaze3KZ2hTemoNcpO+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";
  66295. imgBack.style.position = "absolute";
  66296. imgBack.style.left = "50%";
  66297. imgBack.style.top = "50%";
  66298. imgBack.style.marginLeft = "-60px";
  66299. imgBack.style.marginTop = "-60px";
  66300. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  66301. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  66302. imgBack.style.transformOrigin = "50% 50%";
  66303. imgBack.style.webkitTransformOrigin = "50% 50%";
  66304. this._loadingDiv.appendChild(imgBack);
  66305. this._resizeLoadingUI();
  66306. window.addEventListener("resize", this._resizeLoadingUI);
  66307. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  66308. document.body.appendChild(this._loadingDiv);
  66309. this._loadingDiv.style.opacity = "1";
  66310. };
  66311. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  66312. var _this = this;
  66313. if (!this._loadingDiv) {
  66314. return;
  66315. }
  66316. var onTransitionEnd = function () {
  66317. if (!_this._loadingDiv) {
  66318. return;
  66319. }
  66320. document.body.removeChild(_this._loadingDiv);
  66321. window.removeEventListener("resize", _this._resizeLoadingUI);
  66322. _this._loadingDiv = null;
  66323. };
  66324. this._loadingDiv.style.opacity = "0";
  66325. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  66326. };
  66327. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  66328. set: function (text) {
  66329. this._loadingText = text;
  66330. if (this._loadingTextDiv) {
  66331. this._loadingTextDiv.innerHTML = this._loadingText;
  66332. }
  66333. },
  66334. enumerable: true,
  66335. configurable: true
  66336. });
  66337. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  66338. get: function () {
  66339. return this._loadingDivBackgroundColor;
  66340. },
  66341. set: function (color) {
  66342. this._loadingDivBackgroundColor = color;
  66343. if (!this._loadingDiv) {
  66344. return;
  66345. }
  66346. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  66347. },
  66348. enumerable: true,
  66349. configurable: true
  66350. });
  66351. return DefaultLoadingScreen;
  66352. }());
  66353. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  66354. })(BABYLON || (BABYLON = {}));
  66355. //# sourceMappingURL=babylon.loadingScreen.js.map
  66356. var BABYLON;
  66357. (function (BABYLON) {
  66358. var SceneLoaderProgressEvent = /** @class */ (function () {
  66359. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  66360. this.lengthComputable = lengthComputable;
  66361. this.loaded = loaded;
  66362. this.total = total;
  66363. }
  66364. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  66365. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  66366. };
  66367. return SceneLoaderProgressEvent;
  66368. }());
  66369. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  66370. var SceneLoader = /** @class */ (function () {
  66371. function SceneLoader() {
  66372. }
  66373. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  66374. get: function () {
  66375. return 0;
  66376. },
  66377. enumerable: true,
  66378. configurable: true
  66379. });
  66380. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  66381. get: function () {
  66382. return 1;
  66383. },
  66384. enumerable: true,
  66385. configurable: true
  66386. });
  66387. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  66388. get: function () {
  66389. return 2;
  66390. },
  66391. enumerable: true,
  66392. configurable: true
  66393. });
  66394. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  66395. get: function () {
  66396. return 3;
  66397. },
  66398. enumerable: true,
  66399. configurable: true
  66400. });
  66401. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  66402. get: function () {
  66403. return SceneLoader._ForceFullSceneLoadingForIncremental;
  66404. },
  66405. set: function (value) {
  66406. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  66407. },
  66408. enumerable: true,
  66409. configurable: true
  66410. });
  66411. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  66412. get: function () {
  66413. return SceneLoader._ShowLoadingScreen;
  66414. },
  66415. set: function (value) {
  66416. SceneLoader._ShowLoadingScreen = value;
  66417. },
  66418. enumerable: true,
  66419. configurable: true
  66420. });
  66421. Object.defineProperty(SceneLoader, "loggingLevel", {
  66422. get: function () {
  66423. return SceneLoader._loggingLevel;
  66424. },
  66425. set: function (value) {
  66426. SceneLoader._loggingLevel = value;
  66427. },
  66428. enumerable: true,
  66429. configurable: true
  66430. });
  66431. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  66432. get: function () {
  66433. return SceneLoader._CleanBoneMatrixWeights;
  66434. },
  66435. set: function (value) {
  66436. SceneLoader._CleanBoneMatrixWeights = value;
  66437. },
  66438. enumerable: true,
  66439. configurable: true
  66440. });
  66441. SceneLoader._getDefaultPlugin = function () {
  66442. return SceneLoader._registeredPlugins[".babylon"];
  66443. };
  66444. SceneLoader._getPluginForExtension = function (extension) {
  66445. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  66446. if (registeredPlugin) {
  66447. return registeredPlugin;
  66448. }
  66449. 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");
  66450. return SceneLoader._getDefaultPlugin();
  66451. };
  66452. SceneLoader._getPluginForDirectLoad = function (data) {
  66453. for (var extension in SceneLoader._registeredPlugins) {
  66454. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  66455. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  66456. return SceneLoader._registeredPlugins[extension];
  66457. }
  66458. }
  66459. return SceneLoader._getDefaultPlugin();
  66460. };
  66461. SceneLoader._getPluginForFilename = function (sceneFilename) {
  66462. if (sceneFilename.name) {
  66463. sceneFilename = sceneFilename.name;
  66464. }
  66465. var queryStringPosition = sceneFilename.indexOf("?");
  66466. if (queryStringPosition !== -1) {
  66467. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  66468. }
  66469. var dotPosition = sceneFilename.lastIndexOf(".");
  66470. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  66471. return SceneLoader._getPluginForExtension(extension);
  66472. };
  66473. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  66474. SceneLoader._getDirectLoad = function (sceneFilename) {
  66475. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  66476. return sceneFilename.substr(5);
  66477. }
  66478. return null;
  66479. };
  66480. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  66481. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  66482. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  66483. var plugin;
  66484. if (registeredPlugin.plugin.createPlugin) {
  66485. plugin = registeredPlugin.plugin.createPlugin();
  66486. }
  66487. else {
  66488. plugin = registeredPlugin.plugin;
  66489. }
  66490. var useArrayBuffer = registeredPlugin.isBinary;
  66491. var database;
  66492. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  66493. var dataCallback = function (data, responseURL) {
  66494. if (scene.isDisposed) {
  66495. onError("Scene has been disposed");
  66496. return;
  66497. }
  66498. scene.database = database;
  66499. onSuccess(plugin, data, responseURL);
  66500. };
  66501. var request = null;
  66502. var pluginDisposed = false;
  66503. var onDisposeObservable = plugin.onDisposeObservable;
  66504. if (onDisposeObservable) {
  66505. onDisposeObservable.add(function () {
  66506. pluginDisposed = true;
  66507. if (request) {
  66508. request.abort();
  66509. request = null;
  66510. }
  66511. onDispose();
  66512. });
  66513. }
  66514. var manifestChecked = function () {
  66515. if (pluginDisposed) {
  66516. return;
  66517. }
  66518. var url = rootUrl + sceneFilename;
  66519. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  66520. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  66521. } : undefined, database, useArrayBuffer, function (request, exception) {
  66522. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  66523. });
  66524. };
  66525. if (directLoad) {
  66526. dataCallback(directLoad);
  66527. return plugin;
  66528. }
  66529. if (rootUrl.indexOf("file:") === -1) {
  66530. var engine = scene.getEngine();
  66531. var canUseOfflineSupport = engine.enableOfflineSupport;
  66532. if (canUseOfflineSupport) {
  66533. // Also check for exceptions
  66534. var exceptionFound = false;
  66535. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  66536. var regex = _a[_i];
  66537. if (regex.test(rootUrl + sceneFilename)) {
  66538. exceptionFound = true;
  66539. break;
  66540. }
  66541. }
  66542. canUseOfflineSupport = !exceptionFound;
  66543. }
  66544. if (canUseOfflineSupport) {
  66545. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  66546. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked, engine.disableManifestCheck);
  66547. }
  66548. else {
  66549. manifestChecked();
  66550. }
  66551. }
  66552. // Loading file from disk via input file or drag'n'drop
  66553. else {
  66554. var fileOrString = sceneFilename;
  66555. if (fileOrString.name) { // File
  66556. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  66557. }
  66558. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  66559. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  66560. }
  66561. else {
  66562. onError("Unable to find file named " + sceneFilename);
  66563. }
  66564. }
  66565. return plugin;
  66566. };
  66567. // Public functions
  66568. SceneLoader.GetPluginForExtension = function (extension) {
  66569. return SceneLoader._getPluginForExtension(extension).plugin;
  66570. };
  66571. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  66572. return !!SceneLoader._registeredPlugins[extension];
  66573. };
  66574. SceneLoader.RegisterPlugin = function (plugin) {
  66575. if (typeof plugin.extensions === "string") {
  66576. var extension = plugin.extensions;
  66577. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  66578. plugin: plugin,
  66579. isBinary: false
  66580. };
  66581. }
  66582. else {
  66583. var extensions = plugin.extensions;
  66584. Object.keys(extensions).forEach(function (extension) {
  66585. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  66586. plugin: plugin,
  66587. isBinary: extensions[extension].isBinary
  66588. };
  66589. });
  66590. }
  66591. };
  66592. /**
  66593. * Import meshes into a scene
  66594. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  66595. * @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)
  66596. * @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)
  66597. * @param scene the instance of BABYLON.Scene to append to
  66598. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  66599. * @param onProgress a callback with a progress event for each file being loaded
  66600. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  66601. * @param pluginExtension the extension used to determine the plugin
  66602. * @returns The loaded plugin
  66603. */
  66604. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  66605. if (sceneFilename === void 0) { sceneFilename = ""; }
  66606. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  66607. if (onSuccess === void 0) { onSuccess = null; }
  66608. if (onProgress === void 0) { onProgress = null; }
  66609. if (onError === void 0) { onError = null; }
  66610. if (pluginExtension === void 0) { pluginExtension = null; }
  66611. if (!scene) {
  66612. BABYLON.Tools.Error("No scene available to import mesh to");
  66613. return null;
  66614. }
  66615. if (!sceneFilename) {
  66616. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  66617. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  66618. }
  66619. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  66620. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  66621. return null;
  66622. }
  66623. var loadingToken = {};
  66624. scene._addPendingData(loadingToken);
  66625. var disposeHandler = function () {
  66626. scene._removePendingData(loadingToken);
  66627. };
  66628. var errorHandler = function (message, exception) {
  66629. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  66630. if (onError) {
  66631. onError(scene, errorMessage, exception);
  66632. }
  66633. else {
  66634. BABYLON.Tools.Error(errorMessage);
  66635. // should the exception be thrown?
  66636. }
  66637. disposeHandler();
  66638. };
  66639. var progressHandler = onProgress ? function (event) {
  66640. try {
  66641. onProgress(event);
  66642. }
  66643. catch (e) {
  66644. errorHandler("Error in onProgress callback", e);
  66645. }
  66646. } : undefined;
  66647. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  66648. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  66649. if (onSuccess) {
  66650. try {
  66651. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  66652. }
  66653. catch (e) {
  66654. errorHandler("Error in onSuccess callback", e);
  66655. }
  66656. }
  66657. scene._removePendingData(loadingToken);
  66658. };
  66659. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  66660. if (plugin.rewriteRootURL) {
  66661. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  66662. }
  66663. if (sceneFilename === "") {
  66664. if (sceneFilename === "") {
  66665. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  66666. }
  66667. }
  66668. if (plugin.importMesh) {
  66669. var syncedPlugin = plugin;
  66670. var meshes = new Array();
  66671. var particleSystems = new Array();
  66672. var skeletons = new Array();
  66673. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  66674. return;
  66675. }
  66676. scene.loadingPluginName = plugin.name;
  66677. successHandler(meshes, particleSystems, skeletons, []);
  66678. }
  66679. else {
  66680. var asyncedPlugin = plugin;
  66681. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  66682. scene.loadingPluginName = plugin.name;
  66683. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  66684. }).catch(function (error) {
  66685. errorHandler(error.message, error);
  66686. });
  66687. }
  66688. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  66689. };
  66690. /**
  66691. * Import meshes into a scene
  66692. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  66693. * @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)
  66694. * @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)
  66695. * @param scene the instance of BABYLON.Scene to append to
  66696. * @param onProgress a callback with a progress event for each file being loaded
  66697. * @param pluginExtension the extension used to determine the plugin
  66698. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  66699. */
  66700. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  66701. if (sceneFilename === void 0) { sceneFilename = ""; }
  66702. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  66703. if (onProgress === void 0) { onProgress = null; }
  66704. if (pluginExtension === void 0) { pluginExtension = null; }
  66705. return new Promise(function (resolve, reject) {
  66706. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  66707. resolve({
  66708. meshes: meshes,
  66709. particleSystems: particleSystems,
  66710. skeletons: skeletons,
  66711. animationGroups: animationGroups
  66712. });
  66713. }, onProgress, function (scene, message, exception) {
  66714. reject(exception || new Error(message));
  66715. }, pluginExtension);
  66716. });
  66717. };
  66718. /**
  66719. * Load a scene
  66720. * @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)
  66721. * @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)
  66722. * @param engine is the instance of BABYLON.Engine to use to create the scene
  66723. * @param onSuccess a callback with the scene when import succeeds
  66724. * @param onProgress a callback with a progress event for each file being loaded
  66725. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  66726. * @param pluginExtension the extension used to determine the plugin
  66727. * @returns The loaded plugin
  66728. */
  66729. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  66730. if (onSuccess === void 0) { onSuccess = null; }
  66731. if (onProgress === void 0) { onProgress = null; }
  66732. if (onError === void 0) { onError = null; }
  66733. if (pluginExtension === void 0) { pluginExtension = null; }
  66734. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  66735. };
  66736. /**
  66737. * Load a scene
  66738. * @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)
  66739. * @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)
  66740. * @param engine is the instance of BABYLON.Engine to use to create the scene
  66741. * @param onProgress a callback with a progress event for each file being loaded
  66742. * @param pluginExtension the extension used to determine the plugin
  66743. * @returns The loaded scene
  66744. */
  66745. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  66746. if (onProgress === void 0) { onProgress = null; }
  66747. if (pluginExtension === void 0) { pluginExtension = null; }
  66748. return new Promise(function (resolve, reject) {
  66749. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  66750. resolve(scene);
  66751. }, onProgress, function (scene, message, exception) {
  66752. reject(exception || new Error(message));
  66753. }, pluginExtension);
  66754. });
  66755. };
  66756. /**
  66757. * Append a scene
  66758. * @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)
  66759. * @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)
  66760. * @param scene is the instance of BABYLON.Scene to append to
  66761. * @param onSuccess a callback with the scene when import succeeds
  66762. * @param onProgress a callback with a progress event for each file being loaded
  66763. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  66764. * @param pluginExtension the extension used to determine the plugin
  66765. * @returns The loaded plugin
  66766. */
  66767. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  66768. if (sceneFilename === void 0) { sceneFilename = ""; }
  66769. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  66770. if (onSuccess === void 0) { onSuccess = null; }
  66771. if (onProgress === void 0) { onProgress = null; }
  66772. if (onError === void 0) { onError = null; }
  66773. if (pluginExtension === void 0) { pluginExtension = null; }
  66774. if (!scene) {
  66775. BABYLON.Tools.Error("No scene available to append to");
  66776. return null;
  66777. }
  66778. if (!sceneFilename) {
  66779. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  66780. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  66781. }
  66782. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  66783. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  66784. return null;
  66785. }
  66786. if (SceneLoader.ShowLoadingScreen) {
  66787. scene.getEngine().displayLoadingUI();
  66788. }
  66789. var loadingToken = {};
  66790. scene._addPendingData(loadingToken);
  66791. var disposeHandler = function () {
  66792. scene._removePendingData(loadingToken);
  66793. scene.getEngine().hideLoadingUI();
  66794. };
  66795. var errorHandler = function (message, exception) {
  66796. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  66797. if (onError) {
  66798. onError(scene, errorMessage, exception);
  66799. }
  66800. else {
  66801. BABYLON.Tools.Error(errorMessage);
  66802. // should the exception be thrown?
  66803. }
  66804. disposeHandler();
  66805. };
  66806. var progressHandler = onProgress ? function (event) {
  66807. try {
  66808. onProgress(event);
  66809. }
  66810. catch (e) {
  66811. errorHandler("Error in onProgress callback", e);
  66812. }
  66813. } : undefined;
  66814. var successHandler = function () {
  66815. if (onSuccess) {
  66816. try {
  66817. onSuccess(scene);
  66818. }
  66819. catch (e) {
  66820. errorHandler("Error in onSuccess callback", e);
  66821. }
  66822. }
  66823. scene._removePendingData(loadingToken);
  66824. };
  66825. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  66826. if (sceneFilename === "") {
  66827. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  66828. }
  66829. if (plugin.load) {
  66830. var syncedPlugin = plugin;
  66831. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  66832. return;
  66833. }
  66834. scene.loadingPluginName = plugin.name;
  66835. successHandler();
  66836. }
  66837. else {
  66838. var asyncedPlugin = plugin;
  66839. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  66840. scene.loadingPluginName = plugin.name;
  66841. successHandler();
  66842. }).catch(function (error) {
  66843. errorHandler(error.message, error);
  66844. });
  66845. }
  66846. if (SceneLoader.ShowLoadingScreen) {
  66847. scene.executeWhenReady(function () {
  66848. scene.getEngine().hideLoadingUI();
  66849. });
  66850. }
  66851. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  66852. };
  66853. /**
  66854. * Append a scene
  66855. * @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)
  66856. * @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)
  66857. * @param scene is the instance of BABYLON.Scene to append to
  66858. * @param onProgress a callback with a progress event for each file being loaded
  66859. * @param pluginExtension the extension used to determine the plugin
  66860. * @returns The given scene
  66861. */
  66862. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  66863. if (sceneFilename === void 0) { sceneFilename = ""; }
  66864. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  66865. if (onProgress === void 0) { onProgress = null; }
  66866. if (pluginExtension === void 0) { pluginExtension = null; }
  66867. return new Promise(function (resolve, reject) {
  66868. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  66869. resolve(scene);
  66870. }, onProgress, function (scene, message, exception) {
  66871. reject(exception || new Error(message));
  66872. }, pluginExtension);
  66873. });
  66874. };
  66875. /**
  66876. * Load a scene into an asset container
  66877. * @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)
  66878. * @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)
  66879. * @param scene is the instance of BABYLON.Scene to append to (default: last created scene)
  66880. * @param onSuccess a callback with the scene when import succeeds
  66881. * @param onProgress a callback with a progress event for each file being loaded
  66882. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  66883. * @param pluginExtension the extension used to determine the plugin
  66884. * @returns The loaded plugin
  66885. */
  66886. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  66887. if (sceneFilename === void 0) { sceneFilename = ""; }
  66888. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  66889. if (onSuccess === void 0) { onSuccess = null; }
  66890. if (onProgress === void 0) { onProgress = null; }
  66891. if (onError === void 0) { onError = null; }
  66892. if (pluginExtension === void 0) { pluginExtension = null; }
  66893. if (!scene) {
  66894. BABYLON.Tools.Error("No scene available to load asset container to");
  66895. return null;
  66896. }
  66897. if (!sceneFilename) {
  66898. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  66899. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  66900. }
  66901. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  66902. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  66903. return null;
  66904. }
  66905. var loadingToken = {};
  66906. scene._addPendingData(loadingToken);
  66907. var disposeHandler = function () {
  66908. scene._removePendingData(loadingToken);
  66909. };
  66910. var errorHandler = function (message, exception) {
  66911. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  66912. if (onError) {
  66913. onError(scene, errorMessage, exception);
  66914. }
  66915. else {
  66916. BABYLON.Tools.Error(errorMessage);
  66917. // should the exception be thrown?
  66918. }
  66919. disposeHandler();
  66920. };
  66921. var progressHandler = onProgress ? function (event) {
  66922. try {
  66923. onProgress(event);
  66924. }
  66925. catch (e) {
  66926. errorHandler("Error in onProgress callback", e);
  66927. }
  66928. } : undefined;
  66929. var successHandler = function (assets) {
  66930. if (onSuccess) {
  66931. try {
  66932. onSuccess(assets);
  66933. }
  66934. catch (e) {
  66935. errorHandler("Error in onSuccess callback", e);
  66936. }
  66937. }
  66938. scene._removePendingData(loadingToken);
  66939. };
  66940. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  66941. if (plugin.loadAssetContainer) {
  66942. var syncedPlugin = plugin;
  66943. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  66944. if (!assetContainer) {
  66945. return;
  66946. }
  66947. scene.loadingPluginName = plugin.name;
  66948. successHandler(assetContainer);
  66949. }
  66950. else if (plugin.loadAssetContainerAsync) {
  66951. var asyncedPlugin = plugin;
  66952. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  66953. scene.loadingPluginName = plugin.name;
  66954. successHandler(assetContainer);
  66955. }).catch(function (error) {
  66956. errorHandler(error.message, error);
  66957. });
  66958. }
  66959. else {
  66960. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  66961. }
  66962. if (SceneLoader.ShowLoadingScreen) {
  66963. scene.executeWhenReady(function () {
  66964. scene.getEngine().hideLoadingUI();
  66965. });
  66966. }
  66967. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  66968. };
  66969. /**
  66970. * Load a scene into an asset container
  66971. * @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)
  66972. * @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)
  66973. * @param scene is the instance of BABYLON.Scene to append to
  66974. * @param onProgress a callback with a progress event for each file being loaded
  66975. * @param pluginExtension the extension used to determine the plugin
  66976. * @returns The loaded asset container
  66977. */
  66978. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  66979. if (sceneFilename === void 0) { sceneFilename = ""; }
  66980. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  66981. if (onProgress === void 0) { onProgress = null; }
  66982. if (pluginExtension === void 0) { pluginExtension = null; }
  66983. return new Promise(function (resolve, reject) {
  66984. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  66985. resolve(assetContainer);
  66986. }, onProgress, function (scene, message, exception) {
  66987. reject(exception || new Error(message));
  66988. }, pluginExtension);
  66989. });
  66990. };
  66991. // Flags
  66992. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  66993. SceneLoader._ShowLoadingScreen = true;
  66994. SceneLoader._CleanBoneMatrixWeights = false;
  66995. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  66996. // Members
  66997. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  66998. SceneLoader._registeredPlugins = {};
  66999. return SceneLoader;
  67000. }());
  67001. BABYLON.SceneLoader = SceneLoader;
  67002. ;
  67003. })(BABYLON || (BABYLON = {}));
  67004. //# sourceMappingURL=babylon.sceneLoader.js.map
  67005. var BABYLON;
  67006. (function (BABYLON) {
  67007. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  67008. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  67009. var parsedMaterial = parsedData.materials[index];
  67010. if (parsedMaterial.id === id) {
  67011. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  67012. }
  67013. }
  67014. return null;
  67015. };
  67016. var isDescendantOf = function (mesh, names, hierarchyIds) {
  67017. for (var i in names) {
  67018. if (mesh.name === names[i]) {
  67019. hierarchyIds.push(mesh.id);
  67020. return true;
  67021. }
  67022. }
  67023. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  67024. hierarchyIds.push(mesh.id);
  67025. return true;
  67026. }
  67027. return false;
  67028. };
  67029. var logOperation = function (operation, producer) {
  67030. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  67031. };
  67032. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  67033. if (addToScene === void 0) { addToScene = false; }
  67034. var container = new BABYLON.AssetContainer(scene);
  67035. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  67036. // when SceneLoader.debugLogging = true (default), or exception encountered.
  67037. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  67038. // and avoid problems with multiple concurrent .babylon loads.
  67039. var log = "importScene has failed JSON parse";
  67040. try {
  67041. var parsedData = JSON.parse(data);
  67042. log = "";
  67043. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  67044. var index;
  67045. var cache;
  67046. // Lights
  67047. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  67048. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  67049. var parsedLight = parsedData.lights[index];
  67050. var light = BABYLON.Light.Parse(parsedLight, scene);
  67051. if (light) {
  67052. container.lights.push(light);
  67053. log += (index === 0 ? "\n\tLights:" : "");
  67054. log += "\n\t\t" + light.toString(fullDetails);
  67055. }
  67056. }
  67057. }
  67058. // Animations
  67059. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  67060. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  67061. var parsedAnimation = parsedData.animations[index];
  67062. var animation = BABYLON.Animation.Parse(parsedAnimation);
  67063. scene.animations.push(animation);
  67064. container.animations.push(animation);
  67065. log += (index === 0 ? "\n\tAnimations:" : "");
  67066. log += "\n\t\t" + animation.toString(fullDetails);
  67067. }
  67068. }
  67069. // Materials
  67070. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  67071. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  67072. var parsedMaterial = parsedData.materials[index];
  67073. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  67074. container.materials.push(mat);
  67075. log += (index === 0 ? "\n\tMaterials:" : "");
  67076. log += "\n\t\t" + mat.toString(fullDetails);
  67077. }
  67078. }
  67079. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  67080. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  67081. var parsedMultiMaterial = parsedData.multiMaterials[index];
  67082. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  67083. container.multiMaterials.push(mmat);
  67084. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  67085. log += "\n\t\t" + mmat.toString(fullDetails);
  67086. }
  67087. }
  67088. // Morph targets
  67089. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  67090. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  67091. var managerData = _a[_i];
  67092. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  67093. }
  67094. }
  67095. // Skeletons
  67096. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  67097. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  67098. var parsedSkeleton = parsedData.skeletons[index];
  67099. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  67100. container.skeletons.push(skeleton);
  67101. log += (index === 0 ? "\n\tSkeletons:" : "");
  67102. log += "\n\t\t" + skeleton.toString(fullDetails);
  67103. }
  67104. }
  67105. // Geometries
  67106. var geometries = parsedData.geometries;
  67107. if (geometries !== undefined && geometries !== null) {
  67108. var addedGeometry = new Array();
  67109. // Boxes
  67110. var boxes = geometries.boxes;
  67111. if (boxes !== undefined && boxes !== null) {
  67112. for (index = 0, cache = boxes.length; index < cache; index++) {
  67113. var parsedBox = boxes[index];
  67114. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  67115. }
  67116. }
  67117. // Spheres
  67118. var spheres = geometries.spheres;
  67119. if (spheres !== undefined && spheres !== null) {
  67120. for (index = 0, cache = spheres.length; index < cache; index++) {
  67121. var parsedSphere = spheres[index];
  67122. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  67123. }
  67124. }
  67125. // Cylinders
  67126. var cylinders = geometries.cylinders;
  67127. if (cylinders !== undefined && cylinders !== null) {
  67128. for (index = 0, cache = cylinders.length; index < cache; index++) {
  67129. var parsedCylinder = cylinders[index];
  67130. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  67131. }
  67132. }
  67133. // Toruses
  67134. var toruses = geometries.toruses;
  67135. if (toruses !== undefined && toruses !== null) {
  67136. for (index = 0, cache = toruses.length; index < cache; index++) {
  67137. var parsedTorus = toruses[index];
  67138. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  67139. }
  67140. }
  67141. // Grounds
  67142. var grounds = geometries.grounds;
  67143. if (grounds !== undefined && grounds !== null) {
  67144. for (index = 0, cache = grounds.length; index < cache; index++) {
  67145. var parsedGround = grounds[index];
  67146. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  67147. }
  67148. }
  67149. // Planes
  67150. var planes = geometries.planes;
  67151. if (planes !== undefined && planes !== null) {
  67152. for (index = 0, cache = planes.length; index < cache; index++) {
  67153. var parsedPlane = planes[index];
  67154. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  67155. }
  67156. }
  67157. // TorusKnots
  67158. var torusKnots = geometries.torusKnots;
  67159. if (torusKnots !== undefined && torusKnots !== null) {
  67160. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  67161. var parsedTorusKnot = torusKnots[index];
  67162. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  67163. }
  67164. }
  67165. // VertexData
  67166. var vertexData = geometries.vertexData;
  67167. if (vertexData !== undefined && vertexData !== null) {
  67168. for (index = 0, cache = vertexData.length; index < cache; index++) {
  67169. var parsedVertexData = vertexData[index];
  67170. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  67171. }
  67172. }
  67173. addedGeometry.forEach(function (g) {
  67174. if (g) {
  67175. container.geometries.push(g);
  67176. }
  67177. });
  67178. }
  67179. // Transform nodes
  67180. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  67181. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  67182. var parsedTransformNode = parsedData.transformNodes[index];
  67183. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  67184. container.transformNodes.push(node);
  67185. }
  67186. }
  67187. // Meshes
  67188. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  67189. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  67190. var parsedMesh = parsedData.meshes[index];
  67191. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  67192. container.meshes.push(mesh);
  67193. log += (index === 0 ? "\n\tMeshes:" : "");
  67194. log += "\n\t\t" + mesh.toString(fullDetails);
  67195. }
  67196. }
  67197. // Cameras
  67198. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  67199. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  67200. var parsedCamera = parsedData.cameras[index];
  67201. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  67202. container.cameras.push(camera);
  67203. log += (index === 0 ? "\n\tCameras:" : "");
  67204. log += "\n\t\t" + camera.toString(fullDetails);
  67205. }
  67206. }
  67207. // Browsing all the graph to connect the dots
  67208. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  67209. var camera = scene.cameras[index];
  67210. if (camera._waitingParentId) {
  67211. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  67212. camera._waitingParentId = null;
  67213. }
  67214. }
  67215. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  67216. var light_1 = scene.lights[index];
  67217. if (light_1 && light_1._waitingParentId) {
  67218. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  67219. light_1._waitingParentId = null;
  67220. }
  67221. }
  67222. // Sounds
  67223. // TODO: add sound
  67224. var loadedSounds = [];
  67225. var loadedSound;
  67226. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  67227. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  67228. var parsedSound = parsedData.sounds[index];
  67229. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  67230. if (!parsedSound.url)
  67231. parsedSound.url = parsedSound.name;
  67232. if (!loadedSounds[parsedSound.url]) {
  67233. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  67234. loadedSounds[parsedSound.url] = loadedSound;
  67235. container.sounds.push(loadedSound);
  67236. }
  67237. else {
  67238. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  67239. }
  67240. }
  67241. else {
  67242. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  67243. }
  67244. }
  67245. }
  67246. loadedSounds = [];
  67247. // Connect parents & children and parse actions
  67248. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  67249. var transformNode = scene.transformNodes[index];
  67250. if (transformNode._waitingParentId) {
  67251. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  67252. transformNode._waitingParentId = null;
  67253. }
  67254. }
  67255. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  67256. var mesh = scene.meshes[index];
  67257. if (mesh._waitingParentId) {
  67258. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  67259. mesh._waitingParentId = null;
  67260. }
  67261. if (mesh._waitingActions) {
  67262. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  67263. mesh._waitingActions = null;
  67264. }
  67265. }
  67266. // freeze world matrix application
  67267. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  67268. var currentMesh = scene.meshes[index];
  67269. if (currentMesh._waitingFreezeWorldMatrix) {
  67270. currentMesh.freezeWorldMatrix();
  67271. currentMesh._waitingFreezeWorldMatrix = null;
  67272. }
  67273. else {
  67274. currentMesh.computeWorldMatrix(true);
  67275. }
  67276. }
  67277. // Particles Systems
  67278. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  67279. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  67280. var parsedParticleSystem = parsedData.particleSystems[index];
  67281. if (parsedParticleSystem.activeParticleCount) {
  67282. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  67283. container.particleSystems.push(ps);
  67284. }
  67285. else {
  67286. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  67287. container.particleSystems.push(ps);
  67288. }
  67289. }
  67290. }
  67291. // Lens flares
  67292. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  67293. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  67294. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  67295. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  67296. container.lensFlareSystems.push(lf);
  67297. }
  67298. }
  67299. // Shadows
  67300. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  67301. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  67302. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  67303. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  67304. container.shadowGenerators.push(sg);
  67305. }
  67306. }
  67307. // Lights exclusions / inclusions
  67308. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  67309. var light_2 = scene.lights[index];
  67310. // Excluded check
  67311. if (light_2._excludedMeshesIds.length > 0) {
  67312. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  67313. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  67314. if (excludedMesh) {
  67315. light_2.excludedMeshes.push(excludedMesh);
  67316. }
  67317. }
  67318. light_2._excludedMeshesIds = [];
  67319. }
  67320. // Included check
  67321. if (light_2._includedOnlyMeshesIds.length > 0) {
  67322. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  67323. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  67324. if (includedOnlyMesh) {
  67325. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  67326. }
  67327. }
  67328. light_2._includedOnlyMeshesIds = [];
  67329. }
  67330. }
  67331. // Effect layers
  67332. if (parsedData.effectLayers) {
  67333. for (index = 0; index < parsedData.effectLayers.length; index++) {
  67334. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  67335. container.effectLayers.push(effectLayer);
  67336. }
  67337. }
  67338. // Actions (scene)
  67339. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  67340. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  67341. }
  67342. if (!addToScene) {
  67343. container.removeAllFromScene();
  67344. }
  67345. }
  67346. catch (err) {
  67347. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  67348. if (onError) {
  67349. onError(msg, err);
  67350. }
  67351. else {
  67352. BABYLON.Tools.Log(msg);
  67353. throw err;
  67354. }
  67355. }
  67356. finally {
  67357. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  67358. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  67359. }
  67360. }
  67361. return container;
  67362. };
  67363. BABYLON.SceneLoader.RegisterPlugin({
  67364. name: "babylon.js",
  67365. extensions: ".babylon",
  67366. canDirectLoad: function (data) {
  67367. if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
  67368. return true;
  67369. }
  67370. return false;
  67371. },
  67372. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  67373. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  67374. // when SceneLoader.debugLogging = true (default), or exception encountered.
  67375. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  67376. // and avoid problems with multiple concurrent .babylon loads.
  67377. var log = "importMesh has failed JSON parse";
  67378. try {
  67379. var parsedData = JSON.parse(data);
  67380. log = "";
  67381. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  67382. if (!meshesNames) {
  67383. meshesNames = null;
  67384. }
  67385. else if (!Array.isArray(meshesNames)) {
  67386. meshesNames = [meshesNames];
  67387. }
  67388. var hierarchyIds = new Array();
  67389. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  67390. var loadedSkeletonsIds = [];
  67391. var loadedMaterialsIds = [];
  67392. var index;
  67393. var cache;
  67394. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  67395. var parsedMesh = parsedData.meshes[index];
  67396. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  67397. if (meshesNames !== null) {
  67398. // Remove found mesh name from list.
  67399. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  67400. }
  67401. //Geometry?
  67402. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  67403. //does the file contain geometries?
  67404. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  67405. //find the correct geometry and add it to the scene
  67406. var found = false;
  67407. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  67408. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  67409. return;
  67410. }
  67411. else {
  67412. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  67413. if (parsedGeometryData.id === parsedMesh.geometryId) {
  67414. switch (geometryType) {
  67415. case "boxes":
  67416. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  67417. break;
  67418. case "spheres":
  67419. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  67420. break;
  67421. case "cylinders":
  67422. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  67423. break;
  67424. case "toruses":
  67425. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  67426. break;
  67427. case "grounds":
  67428. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  67429. break;
  67430. case "planes":
  67431. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  67432. break;
  67433. case "torusKnots":
  67434. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  67435. break;
  67436. case "vertexData":
  67437. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  67438. break;
  67439. }
  67440. found = true;
  67441. }
  67442. });
  67443. }
  67444. });
  67445. if (found === false) {
  67446. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  67447. }
  67448. }
  67449. }
  67450. // Material ?
  67451. if (parsedMesh.materialId) {
  67452. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  67453. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  67454. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  67455. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  67456. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  67457. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  67458. var subMatId = parsedMultiMaterial.materials[matIndex];
  67459. loadedMaterialsIds.push(subMatId);
  67460. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  67461. if (mat) {
  67462. log += "\n\tMaterial " + mat.toString(fullDetails);
  67463. }
  67464. }
  67465. loadedMaterialsIds.push(parsedMultiMaterial.id);
  67466. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  67467. if (mmat) {
  67468. materialFound = true;
  67469. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  67470. }
  67471. break;
  67472. }
  67473. }
  67474. }
  67475. if (materialFound === false) {
  67476. loadedMaterialsIds.push(parsedMesh.materialId);
  67477. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  67478. if (!mat) {
  67479. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  67480. }
  67481. else {
  67482. log += "\n\tMaterial " + mat.toString(fullDetails);
  67483. }
  67484. }
  67485. }
  67486. // Skeleton ?
  67487. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  67488. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  67489. if (skeletonAlreadyLoaded === false) {
  67490. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  67491. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  67492. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  67493. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  67494. skeletons.push(skeleton);
  67495. loadedSkeletonsIds.push(parsedSkeleton.id);
  67496. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  67497. }
  67498. }
  67499. }
  67500. }
  67501. // Morph targets ?
  67502. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  67503. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  67504. var managerData = _a[_i];
  67505. BABYLON.MorphTargetManager.Parse(managerData, scene);
  67506. }
  67507. }
  67508. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  67509. meshes.push(mesh);
  67510. log += "\n\tMesh " + mesh.toString(fullDetails);
  67511. }
  67512. }
  67513. // Connecting parents
  67514. var currentMesh;
  67515. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  67516. currentMesh = scene.meshes[index];
  67517. if (currentMesh._waitingParentId) {
  67518. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  67519. currentMesh._waitingParentId = null;
  67520. }
  67521. }
  67522. // freeze and compute world matrix application
  67523. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  67524. currentMesh = scene.meshes[index];
  67525. if (currentMesh._waitingFreezeWorldMatrix) {
  67526. currentMesh.freezeWorldMatrix();
  67527. currentMesh._waitingFreezeWorldMatrix = null;
  67528. }
  67529. else {
  67530. currentMesh.computeWorldMatrix(true);
  67531. }
  67532. }
  67533. }
  67534. // Particles
  67535. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  67536. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  67537. var parsedParticleSystem = parsedData.particleSystems[index];
  67538. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  67539. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  67540. }
  67541. }
  67542. }
  67543. return true;
  67544. }
  67545. catch (err) {
  67546. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  67547. if (onError) {
  67548. onError(msg, err);
  67549. }
  67550. else {
  67551. BABYLON.Tools.Log(msg);
  67552. throw err;
  67553. }
  67554. }
  67555. finally {
  67556. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  67557. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  67558. }
  67559. }
  67560. return false;
  67561. },
  67562. load: function (scene, data, rootUrl, onError) {
  67563. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  67564. // when SceneLoader.debugLogging = true (default), or exception encountered.
  67565. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  67566. // and avoid problems with multiple concurrent .babylon loads.
  67567. var log = "importScene has failed JSON parse";
  67568. try {
  67569. var parsedData = JSON.parse(data);
  67570. log = "";
  67571. // Scene
  67572. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  67573. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  67574. }
  67575. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  67576. scene.autoClear = parsedData.autoClear;
  67577. }
  67578. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  67579. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  67580. }
  67581. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  67582. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  67583. }
  67584. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  67585. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  67586. }
  67587. // Fog
  67588. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  67589. scene.fogMode = parsedData.fogMode;
  67590. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  67591. scene.fogStart = parsedData.fogStart;
  67592. scene.fogEnd = parsedData.fogEnd;
  67593. scene.fogDensity = parsedData.fogDensity;
  67594. log += "\tFog mode for scene: ";
  67595. switch (scene.fogMode) {
  67596. // getters not compiling, so using hardcoded
  67597. case 1:
  67598. log += "exp\n";
  67599. break;
  67600. case 2:
  67601. log += "exp2\n";
  67602. break;
  67603. case 3:
  67604. log += "linear\n";
  67605. break;
  67606. }
  67607. }
  67608. //Physics
  67609. if (parsedData.physicsEnabled) {
  67610. var physicsPlugin;
  67611. if (parsedData.physicsEngine === "cannon") {
  67612. physicsPlugin = new BABYLON.CannonJSPlugin();
  67613. }
  67614. else if (parsedData.physicsEngine === "oimo") {
  67615. physicsPlugin = new BABYLON.OimoJSPlugin();
  67616. }
  67617. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  67618. //else - default engine, which is currently oimo
  67619. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  67620. scene.enablePhysics(physicsGravity, physicsPlugin);
  67621. }
  67622. // Metadata
  67623. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  67624. scene.metadata = parsedData.metadata;
  67625. }
  67626. //collisions, if defined. otherwise, default is true
  67627. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  67628. scene.collisionsEnabled = parsedData.collisionsEnabled;
  67629. }
  67630. scene.workerCollisions = !!parsedData.workerCollisions;
  67631. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  67632. if (!container) {
  67633. return false;
  67634. }
  67635. if (parsedData.autoAnimate) {
  67636. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  67637. }
  67638. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  67639. scene.setActiveCameraByID(parsedData.activeCameraID);
  67640. }
  67641. // Environment texture
  67642. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  67643. if (parsedData.environmentTextureType && parsedData.environmentTextureType === "BABYLON.HDRCubeTexture") {
  67644. var hdrSize = (parsedData.environmentTextureSize) ? parsedData.environmentTextureSize : 128;
  67645. var hdrTexture = new BABYLON.HDRCubeTexture(rootUrl + parsedData.environmentTexture, scene, hdrSize);
  67646. if (parsedData.environmentTextureRotationY) {
  67647. hdrTexture.rotationY = parsedData.environmentTextureRotationY;
  67648. }
  67649. scene.environmentTexture = hdrTexture;
  67650. }
  67651. else {
  67652. var cubeTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  67653. if (parsedData.environmentTextureRotationY) {
  67654. cubeTexture.rotationY = parsedData.environmentTextureRotationY;
  67655. }
  67656. scene.environmentTexture = cubeTexture;
  67657. }
  67658. if (parsedData.createDefaultSkybox === true) {
  67659. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  67660. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  67661. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  67662. }
  67663. }
  67664. // Finish
  67665. return true;
  67666. }
  67667. catch (err) {
  67668. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  67669. if (onError) {
  67670. onError(msg, err);
  67671. }
  67672. else {
  67673. BABYLON.Tools.Log(msg);
  67674. throw err;
  67675. }
  67676. }
  67677. finally {
  67678. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  67679. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  67680. }
  67681. }
  67682. return false;
  67683. },
  67684. loadAssetContainer: function (scene, data, rootUrl, onError) {
  67685. var container = loadAssetContainer(scene, data, rootUrl, onError);
  67686. return container;
  67687. }
  67688. });
  67689. })(BABYLON || (BABYLON = {}));
  67690. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  67691. var BABYLON;
  67692. (function (BABYLON) {
  67693. var FilesInput = /** @class */ (function () {
  67694. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  67695. this.onProcessFileCallback = function () { return true; };
  67696. this._engine = engine;
  67697. this._currentScene = scene;
  67698. this._sceneLoadedCallback = sceneLoadedCallback;
  67699. this._progressCallback = progressCallback;
  67700. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  67701. this._textureLoadingCallback = textureLoadingCallback;
  67702. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  67703. this._onReloadCallback = onReloadCallback;
  67704. this._errorCallback = errorCallback;
  67705. }
  67706. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  67707. var _this = this;
  67708. if (elementToMonitor) {
  67709. this._elementToMonitor = elementToMonitor;
  67710. this._dragEnterHandler = function (e) { _this.drag(e); };
  67711. this._dragOverHandler = function (e) { _this.drag(e); };
  67712. this._dropHandler = function (e) { _this.drop(e); };
  67713. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  67714. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  67715. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  67716. }
  67717. };
  67718. FilesInput.prototype.dispose = function () {
  67719. if (!this._elementToMonitor) {
  67720. return;
  67721. }
  67722. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  67723. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  67724. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  67725. };
  67726. FilesInput.prototype.renderFunction = function () {
  67727. if (this._additionalRenderLoopLogicCallback) {
  67728. this._additionalRenderLoopLogicCallback();
  67729. }
  67730. if (this._currentScene) {
  67731. if (this._textureLoadingCallback) {
  67732. var remaining = this._currentScene.getWaitingItemsCount();
  67733. if (remaining > 0) {
  67734. this._textureLoadingCallback(remaining);
  67735. }
  67736. }
  67737. this._currentScene.render();
  67738. }
  67739. };
  67740. FilesInput.prototype.drag = function (e) {
  67741. e.stopPropagation();
  67742. e.preventDefault();
  67743. };
  67744. FilesInput.prototype.drop = function (eventDrop) {
  67745. eventDrop.stopPropagation();
  67746. eventDrop.preventDefault();
  67747. this.loadFiles(eventDrop);
  67748. };
  67749. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  67750. var _this = this;
  67751. var reader = folder.createReader();
  67752. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  67753. reader.readEntries(function (entries) {
  67754. remaining.count += entries.length;
  67755. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  67756. var entry = entries_1[_i];
  67757. if (entry.isFile) {
  67758. entry.file(function (file) {
  67759. file.correctName = relativePath + file.name;
  67760. files.push(file);
  67761. if (--remaining.count === 0) {
  67762. callback();
  67763. }
  67764. });
  67765. }
  67766. else if (entry.isDirectory) {
  67767. _this._traverseFolder(entry, files, remaining, callback);
  67768. }
  67769. }
  67770. if (--remaining.count) {
  67771. callback();
  67772. }
  67773. });
  67774. };
  67775. FilesInput.prototype._processFiles = function (files) {
  67776. for (var i = 0; i < files.length; i++) {
  67777. var name = files[i].correctName.toLowerCase();
  67778. var extension = name.split('.').pop();
  67779. if (!this.onProcessFileCallback(files[i], name, extension)) {
  67780. continue;
  67781. }
  67782. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  67783. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  67784. this._sceneFileToLoad = files[i];
  67785. }
  67786. else {
  67787. FilesInput.FilesToLoad[name] = files[i];
  67788. }
  67789. }
  67790. };
  67791. FilesInput.prototype.loadFiles = function (event) {
  67792. var _this = this;
  67793. if (this._startingProcessingFilesCallback)
  67794. this._startingProcessingFilesCallback();
  67795. // Handling data transfer via drag'n'drop
  67796. if (event && event.dataTransfer && event.dataTransfer.files) {
  67797. this._filesToLoad = event.dataTransfer.files;
  67798. }
  67799. // Handling files from input files
  67800. if (event && event.target && event.target.files) {
  67801. this._filesToLoad = event.target.files;
  67802. }
  67803. if (this._filesToLoad && this._filesToLoad.length > 0) {
  67804. var files_1 = new Array();
  67805. var folders = [];
  67806. var items = event.dataTransfer ? event.dataTransfer.items : null;
  67807. for (var i = 0; i < this._filesToLoad.length; i++) {
  67808. var fileToLoad = this._filesToLoad[i];
  67809. var name_1 = fileToLoad.name.toLowerCase();
  67810. var entry = void 0;
  67811. fileToLoad.correctName = name_1;
  67812. if (items) {
  67813. var item = items[i];
  67814. if (item.getAsEntry) {
  67815. entry = item.getAsEntry();
  67816. }
  67817. else if (item.webkitGetAsEntry) {
  67818. entry = item.webkitGetAsEntry();
  67819. }
  67820. }
  67821. if (!entry) {
  67822. files_1.push(fileToLoad);
  67823. }
  67824. else {
  67825. if (entry.isDirectory) {
  67826. folders.push(entry);
  67827. }
  67828. else {
  67829. files_1.push(fileToLoad);
  67830. }
  67831. }
  67832. }
  67833. if (folders.length === 0) {
  67834. this._processFiles(files_1);
  67835. this._processReload();
  67836. }
  67837. else {
  67838. var remaining = { count: folders.length };
  67839. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  67840. var folder = folders_1[_i];
  67841. this._traverseFolder(folder, files_1, remaining, function () {
  67842. _this._processFiles(files_1);
  67843. if (remaining.count === 0) {
  67844. _this._processReload();
  67845. }
  67846. });
  67847. }
  67848. }
  67849. }
  67850. };
  67851. FilesInput.prototype._processReload = function () {
  67852. if (this._onReloadCallback) {
  67853. this._onReloadCallback(this._sceneFileToLoad);
  67854. }
  67855. else {
  67856. this.reload();
  67857. }
  67858. };
  67859. FilesInput.prototype.reload = function () {
  67860. var _this = this;
  67861. // If a scene file has been provided
  67862. if (this._sceneFileToLoad) {
  67863. if (this._currentScene) {
  67864. if (BABYLON.Tools.errorsCount > 0) {
  67865. BABYLON.Tools.ClearLogCache();
  67866. }
  67867. this._engine.stopRenderLoop();
  67868. }
  67869. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  67870. if (_this._progressCallback) {
  67871. _this._progressCallback(progress);
  67872. }
  67873. }).then(function (scene) {
  67874. if (_this._currentScene) {
  67875. _this._currentScene.dispose();
  67876. }
  67877. _this._currentScene = scene;
  67878. if (_this._sceneLoadedCallback) {
  67879. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  67880. }
  67881. // Wait for textures and shaders to be ready
  67882. _this._currentScene.executeWhenReady(function () {
  67883. _this._engine.runRenderLoop(function () {
  67884. _this.renderFunction();
  67885. });
  67886. });
  67887. }).catch(function (error) {
  67888. if (_this._errorCallback) {
  67889. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  67890. }
  67891. });
  67892. }
  67893. else {
  67894. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  67895. }
  67896. };
  67897. FilesInput.FilesToLoad = {};
  67898. return FilesInput;
  67899. }());
  67900. BABYLON.FilesInput = FilesInput;
  67901. })(BABYLON || (BABYLON = {}));
  67902. //# sourceMappingURL=babylon.filesInput.js.map
  67903. var BABYLON;
  67904. (function (BABYLON) {
  67905. /**
  67906. * This class implement a typical dictionary using a string as key and the generic type T as value.
  67907. * The underlying implementation relies on an associative array to ensure the best performances.
  67908. * The value can be anything including 'null' but except 'undefined'
  67909. */
  67910. var StringDictionary = /** @class */ (function () {
  67911. function StringDictionary() {
  67912. this._count = 0;
  67913. this._data = {};
  67914. }
  67915. /**
  67916. * This will clear this dictionary and copy the content from the 'source' one.
  67917. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  67918. * @param source the dictionary to take the content from and copy to this dictionary
  67919. */
  67920. StringDictionary.prototype.copyFrom = function (source) {
  67921. var _this = this;
  67922. this.clear();
  67923. source.forEach(function (t, v) { return _this.add(t, v); });
  67924. };
  67925. /**
  67926. * Get a value based from its key
  67927. * @param key the given key to get the matching value from
  67928. * @return the value if found, otherwise undefined is returned
  67929. */
  67930. StringDictionary.prototype.get = function (key) {
  67931. var val = this._data[key];
  67932. if (val !== undefined) {
  67933. return val;
  67934. }
  67935. return undefined;
  67936. };
  67937. /**
  67938. * Get a value from its key or add it if it doesn't exist.
  67939. * This method will ensure you that a given key/data will be present in the dictionary.
  67940. * @param key the given key to get the matching value from
  67941. * @param factory the factory that will create the value if the key is not present in the dictionary.
  67942. * The factory will only be invoked if there's no data for the given key.
  67943. * @return the value corresponding to the key.
  67944. */
  67945. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  67946. var val = this.get(key);
  67947. if (val !== undefined) {
  67948. return val;
  67949. }
  67950. val = factory(key);
  67951. if (val) {
  67952. this.add(key, val);
  67953. }
  67954. return val;
  67955. };
  67956. /**
  67957. * Get a value from its key if present in the dictionary otherwise add it
  67958. * @param key the key to get the value from
  67959. * @param val if there's no such key/value pair in the dictionary add it with this value
  67960. * @return the value corresponding to the key
  67961. */
  67962. StringDictionary.prototype.getOrAdd = function (key, val) {
  67963. var curVal = this.get(key);
  67964. if (curVal !== undefined) {
  67965. return curVal;
  67966. }
  67967. this.add(key, val);
  67968. return val;
  67969. };
  67970. /**
  67971. * Check if there's a given key in the dictionary
  67972. * @param key the key to check for
  67973. * @return true if the key is present, false otherwise
  67974. */
  67975. StringDictionary.prototype.contains = function (key) {
  67976. return this._data[key] !== undefined;
  67977. };
  67978. /**
  67979. * Add a new key and its corresponding value
  67980. * @param key the key to add
  67981. * @param value the value corresponding to the key
  67982. * @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
  67983. */
  67984. StringDictionary.prototype.add = function (key, value) {
  67985. if (this._data[key] !== undefined) {
  67986. return false;
  67987. }
  67988. this._data[key] = value;
  67989. ++this._count;
  67990. return true;
  67991. };
  67992. StringDictionary.prototype.set = function (key, value) {
  67993. if (this._data[key] === undefined) {
  67994. return false;
  67995. }
  67996. this._data[key] = value;
  67997. return true;
  67998. };
  67999. /**
  68000. * Get the element of the given key and remove it from the dictionary
  68001. * @param key
  68002. */
  68003. StringDictionary.prototype.getAndRemove = function (key) {
  68004. var val = this.get(key);
  68005. if (val !== undefined) {
  68006. delete this._data[key];
  68007. --this._count;
  68008. return val;
  68009. }
  68010. return null;
  68011. };
  68012. /**
  68013. * Remove a key/value from the dictionary.
  68014. * @param key the key to remove
  68015. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  68016. */
  68017. StringDictionary.prototype.remove = function (key) {
  68018. if (this.contains(key)) {
  68019. delete this._data[key];
  68020. --this._count;
  68021. return true;
  68022. }
  68023. return false;
  68024. };
  68025. /**
  68026. * Clear the whole content of the dictionary
  68027. */
  68028. StringDictionary.prototype.clear = function () {
  68029. this._data = {};
  68030. this._count = 0;
  68031. };
  68032. Object.defineProperty(StringDictionary.prototype, "count", {
  68033. get: function () {
  68034. return this._count;
  68035. },
  68036. enumerable: true,
  68037. configurable: true
  68038. });
  68039. /**
  68040. * Execute a callback on each key/val of the dictionary.
  68041. * Note that you can remove any element in this dictionary in the callback implementation
  68042. * @param callback the callback to execute on a given key/value pair
  68043. */
  68044. StringDictionary.prototype.forEach = function (callback) {
  68045. for (var cur in this._data) {
  68046. var val = this._data[cur];
  68047. callback(cur, val);
  68048. }
  68049. };
  68050. /**
  68051. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  68052. * If the callback returns null or undefined the method will iterate to the next key/value pair
  68053. * Note that you can remove any element in this dictionary in the callback implementation
  68054. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  68055. */
  68056. StringDictionary.prototype.first = function (callback) {
  68057. for (var cur in this._data) {
  68058. var val = this._data[cur];
  68059. var res = callback(cur, val);
  68060. if (res) {
  68061. return res;
  68062. }
  68063. }
  68064. return null;
  68065. };
  68066. return StringDictionary;
  68067. }());
  68068. BABYLON.StringDictionary = StringDictionary;
  68069. })(BABYLON || (BABYLON = {}));
  68070. //# sourceMappingURL=babylon.stringDictionary.js.map
  68071. var BABYLON;
  68072. (function (BABYLON) {
  68073. var Tags = /** @class */ (function () {
  68074. function Tags() {
  68075. }
  68076. Tags.EnableFor = function (obj) {
  68077. obj._tags = obj._tags || {};
  68078. obj.hasTags = function () {
  68079. return Tags.HasTags(obj);
  68080. };
  68081. obj.addTags = function (tagsString) {
  68082. return Tags.AddTagsTo(obj, tagsString);
  68083. };
  68084. obj.removeTags = function (tagsString) {
  68085. return Tags.RemoveTagsFrom(obj, tagsString);
  68086. };
  68087. obj.matchesTagsQuery = function (tagsQuery) {
  68088. return Tags.MatchesQuery(obj, tagsQuery);
  68089. };
  68090. };
  68091. Tags.DisableFor = function (obj) {
  68092. delete obj._tags;
  68093. delete obj.hasTags;
  68094. delete obj.addTags;
  68095. delete obj.removeTags;
  68096. delete obj.matchesTagsQuery;
  68097. };
  68098. Tags.HasTags = function (obj) {
  68099. if (!obj._tags) {
  68100. return false;
  68101. }
  68102. return !BABYLON.Tools.IsEmpty(obj._tags);
  68103. };
  68104. Tags.GetTags = function (obj, asString) {
  68105. if (asString === void 0) { asString = true; }
  68106. if (!obj._tags) {
  68107. return null;
  68108. }
  68109. if (asString) {
  68110. var tagsArray = [];
  68111. for (var tag in obj._tags) {
  68112. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  68113. tagsArray.push(tag);
  68114. }
  68115. }
  68116. return tagsArray.join(" ");
  68117. }
  68118. else {
  68119. return obj._tags;
  68120. }
  68121. };
  68122. // the tags 'true' and 'false' are reserved and cannot be used as tags
  68123. // a tag cannot start with '||', '&&', and '!'
  68124. // it cannot contain whitespaces
  68125. Tags.AddTagsTo = function (obj, tagsString) {
  68126. if (!tagsString) {
  68127. return;
  68128. }
  68129. if (typeof tagsString !== "string") {
  68130. return;
  68131. }
  68132. var tags = tagsString.split(" ");
  68133. tags.forEach(function (tag, index, array) {
  68134. Tags._AddTagTo(obj, tag);
  68135. });
  68136. };
  68137. Tags._AddTagTo = function (obj, tag) {
  68138. tag = tag.trim();
  68139. if (tag === "" || tag === "true" || tag === "false") {
  68140. return;
  68141. }
  68142. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  68143. return;
  68144. }
  68145. Tags.EnableFor(obj);
  68146. obj._tags[tag] = true;
  68147. };
  68148. Tags.RemoveTagsFrom = function (obj, tagsString) {
  68149. if (!Tags.HasTags(obj)) {
  68150. return;
  68151. }
  68152. var tags = tagsString.split(" ");
  68153. for (var t in tags) {
  68154. Tags._RemoveTagFrom(obj, tags[t]);
  68155. }
  68156. };
  68157. Tags._RemoveTagFrom = function (obj, tag) {
  68158. delete obj._tags[tag];
  68159. };
  68160. Tags.MatchesQuery = function (obj, tagsQuery) {
  68161. if (tagsQuery === undefined) {
  68162. return true;
  68163. }
  68164. if (tagsQuery === "") {
  68165. return Tags.HasTags(obj);
  68166. }
  68167. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  68168. };
  68169. return Tags;
  68170. }());
  68171. BABYLON.Tags = Tags;
  68172. })(BABYLON || (BABYLON = {}));
  68173. //# sourceMappingURL=babylon.tags.js.map
  68174. var BABYLON;
  68175. (function (BABYLON) {
  68176. /**
  68177. * Class used to evalaute queries containing `and` and `or` operators
  68178. */
  68179. var AndOrNotEvaluator = /** @class */ (function () {
  68180. function AndOrNotEvaluator() {
  68181. }
  68182. /**
  68183. * Evaluate a query
  68184. * @param query defines the query to evaluate
  68185. * @param evaluateCallback defines the callback used to filter result
  68186. * @returns true if the query matches
  68187. */
  68188. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  68189. if (!query.match(/\([^\(\)]*\)/g)) {
  68190. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  68191. }
  68192. else {
  68193. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  68194. // remove parenthesis
  68195. r = r.slice(1, r.length - 1);
  68196. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  68197. });
  68198. }
  68199. if (query === "true") {
  68200. return true;
  68201. }
  68202. if (query === "false") {
  68203. return false;
  68204. }
  68205. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  68206. };
  68207. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  68208. evaluateCallback = evaluateCallback || (function (r) {
  68209. return r === "true" ? true : false;
  68210. });
  68211. var result;
  68212. var or = parenthesisContent.split("||");
  68213. for (var i in or) {
  68214. if (or.hasOwnProperty(i)) {
  68215. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  68216. var and = ori.split("&&");
  68217. if (and.length > 1) {
  68218. for (var j = 0; j < and.length; ++j) {
  68219. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  68220. if (andj !== "true" && andj !== "false") {
  68221. if (andj[0] === "!") {
  68222. result = !evaluateCallback(andj.substring(1));
  68223. }
  68224. else {
  68225. result = evaluateCallback(andj);
  68226. }
  68227. }
  68228. else {
  68229. result = andj === "true" ? true : false;
  68230. }
  68231. if (!result) { // no need to continue since 'false && ... && ...' will always return false
  68232. ori = "false";
  68233. break;
  68234. }
  68235. }
  68236. }
  68237. if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
  68238. result = true;
  68239. break;
  68240. }
  68241. // result equals false (or undefined)
  68242. if (ori !== "true" && ori !== "false") {
  68243. if (ori[0] === "!") {
  68244. result = !evaluateCallback(ori.substring(1));
  68245. }
  68246. else {
  68247. result = evaluateCallback(ori);
  68248. }
  68249. }
  68250. else {
  68251. result = ori === "true" ? true : false;
  68252. }
  68253. }
  68254. }
  68255. // the whole parenthesis scope is replaced by 'true' or 'false'
  68256. return result ? "true" : "false";
  68257. };
  68258. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  68259. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  68260. // remove whitespaces
  68261. r = r.replace(/[\s]/g, function () { return ""; });
  68262. return r.length % 2 ? "!" : "";
  68263. });
  68264. booleanString = booleanString.trim();
  68265. if (booleanString === "!true") {
  68266. booleanString = "false";
  68267. }
  68268. else if (booleanString === "!false") {
  68269. booleanString = "true";
  68270. }
  68271. return booleanString;
  68272. };
  68273. return AndOrNotEvaluator;
  68274. }());
  68275. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  68276. })(BABYLON || (BABYLON = {}));
  68277. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  68278. var BABYLON;
  68279. (function (BABYLON) {
  68280. /**
  68281. * Class used to enable access to IndexedDB
  68282. * @see @https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
  68283. */
  68284. var Database = /** @class */ (function () {
  68285. /**
  68286. * Creates a new Database
  68287. * @param urlToScene defines the url to load the scene
  68288. * @param callbackManifestChecked defines the callback to use when manifest is checked
  68289. * @param disableManifestCheck defines a boolean indicating that we want to skip the manifest validation (it will be considered validated and up to date)
  68290. */
  68291. function Database(urlToScene, callbackManifestChecked, disableManifestCheck) {
  68292. if (disableManifestCheck === void 0) { disableManifestCheck = false; }
  68293. var _this = this;
  68294. // Handling various flavors of prefixed version of IndexedDB
  68295. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  68296. this.callbackManifestChecked = callbackManifestChecked;
  68297. this.currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene);
  68298. this.db = null;
  68299. this._enableSceneOffline = false;
  68300. this._enableTexturesOffline = false;
  68301. this.manifestVersionFound = 0;
  68302. this.mustUpdateRessources = false;
  68303. this.hasReachedQuota = false;
  68304. if (!Database.IDBStorageEnabled) {
  68305. this.callbackManifestChecked(true);
  68306. }
  68307. else {
  68308. if (disableManifestCheck) {
  68309. this._enableSceneOffline = true;
  68310. this._enableTexturesOffline = true;
  68311. this.manifestVersionFound = 1;
  68312. BABYLON.Tools.SetImmediate(function () {
  68313. _this.callbackManifestChecked(true);
  68314. });
  68315. }
  68316. else {
  68317. this._checkManifestFile();
  68318. }
  68319. }
  68320. }
  68321. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  68322. /**
  68323. * Gets a boolean indicating if scene must be saved in the database
  68324. */
  68325. get: function () {
  68326. return this._enableSceneOffline;
  68327. },
  68328. enumerable: true,
  68329. configurable: true
  68330. });
  68331. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  68332. /**
  68333. * Gets a boolean indicating if textures must be saved in the database
  68334. */
  68335. get: function () {
  68336. return this._enableTexturesOffline;
  68337. },
  68338. enumerable: true,
  68339. configurable: true
  68340. });
  68341. Database.prototype._checkManifestFile = function () {
  68342. var _this = this;
  68343. var noManifestFile = function () {
  68344. _this._enableSceneOffline = false;
  68345. _this._enableTexturesOffline = false;
  68346. _this.callbackManifestChecked(false);
  68347. };
  68348. var timeStampUsed = false;
  68349. var manifestURL = this.currentSceneUrl + ".manifest";
  68350. var xhr = new XMLHttpRequest();
  68351. if (navigator.onLine) {
  68352. // Adding a timestamp to by-pass browsers' cache
  68353. timeStampUsed = true;
  68354. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + Date.now();
  68355. }
  68356. xhr.open("GET", manifestURL, true);
  68357. xhr.addEventListener("load", function () {
  68358. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  68359. try {
  68360. var manifestFile = JSON.parse(xhr.response);
  68361. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  68362. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  68363. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  68364. _this.manifestVersionFound = manifestFile.version;
  68365. }
  68366. if (_this.callbackManifestChecked) {
  68367. _this.callbackManifestChecked(true);
  68368. }
  68369. }
  68370. catch (ex) {
  68371. noManifestFile();
  68372. }
  68373. }
  68374. else {
  68375. noManifestFile();
  68376. }
  68377. }, false);
  68378. xhr.addEventListener("error", function (event) {
  68379. if (timeStampUsed) {
  68380. timeStampUsed = false;
  68381. // Let's retry without the timeStamp
  68382. // It could fail when coupled with HTML5 Offline API
  68383. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  68384. xhr.open("GET", retryManifestURL, true);
  68385. xhr.send();
  68386. }
  68387. else {
  68388. noManifestFile();
  68389. }
  68390. }, false);
  68391. try {
  68392. xhr.send();
  68393. }
  68394. catch (ex) {
  68395. BABYLON.Tools.Error("Error on XHR send request.");
  68396. this.callbackManifestChecked(false);
  68397. }
  68398. };
  68399. /**
  68400. * Open the database and make it available
  68401. * @param successCallback defines the callback to call on success
  68402. * @param errorCallback defines the callback to call on error
  68403. */
  68404. Database.prototype.openAsync = function (successCallback, errorCallback) {
  68405. var _this = this;
  68406. var handleError = function () {
  68407. _this.isSupported = false;
  68408. if (errorCallback)
  68409. errorCallback();
  68410. };
  68411. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  68412. // Your browser doesn't support IndexedDB
  68413. this.isSupported = false;
  68414. if (errorCallback)
  68415. errorCallback();
  68416. }
  68417. else {
  68418. // If the DB hasn't been opened or created yet
  68419. if (!this.db) {
  68420. this.hasReachedQuota = false;
  68421. this.isSupported = true;
  68422. var request = this.idbFactory.open("babylonjs", 1);
  68423. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  68424. request.onerror = function (event) {
  68425. handleError();
  68426. };
  68427. // executes when a version change transaction cannot complete due to other active transactions
  68428. request.onblocked = function (event) {
  68429. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  68430. handleError();
  68431. };
  68432. // DB has been opened successfully
  68433. request.onsuccess = function (event) {
  68434. _this.db = request.result;
  68435. successCallback();
  68436. };
  68437. // Initialization of the DB. Creating Scenes & Textures stores
  68438. request.onupgradeneeded = function (event) {
  68439. _this.db = (event.target).result;
  68440. if (_this.db) {
  68441. try {
  68442. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  68443. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  68444. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  68445. }
  68446. catch (ex) {
  68447. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  68448. handleError();
  68449. }
  68450. }
  68451. };
  68452. }
  68453. // DB has already been created and opened
  68454. else {
  68455. if (successCallback)
  68456. successCallback();
  68457. }
  68458. }
  68459. };
  68460. /**
  68461. * Loads an image from the database
  68462. * @param url defines the url to load from
  68463. * @param image defines the target DOM image
  68464. */
  68465. Database.prototype.loadImageFromDB = function (url, image) {
  68466. var _this = this;
  68467. var completeURL = Database._ReturnFullUrlLocation(url);
  68468. var saveAndLoadImage = function () {
  68469. if (!_this.hasReachedQuota && _this.db !== null) {
  68470. // the texture is not yet in the DB, let's try to save it
  68471. _this._saveImageIntoDBAsync(completeURL, image);
  68472. }
  68473. // If the texture is not in the DB and we've reached the DB quota limit
  68474. // let's load it directly from the web
  68475. else {
  68476. image.src = url;
  68477. }
  68478. };
  68479. if (!this.mustUpdateRessources) {
  68480. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  68481. }
  68482. // First time we're download the images or update requested in the manifest file by a version change
  68483. else {
  68484. saveAndLoadImage();
  68485. }
  68486. };
  68487. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  68488. if (this.isSupported && this.db !== null) {
  68489. var texture;
  68490. var transaction = this.db.transaction(["textures"]);
  68491. transaction.onabort = function (event) {
  68492. image.src = url;
  68493. };
  68494. transaction.oncomplete = function (event) {
  68495. var blobTextureURL;
  68496. if (texture) {
  68497. var URL = window.URL || window.webkitURL;
  68498. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  68499. image.onerror = function () {
  68500. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  68501. image.src = url;
  68502. };
  68503. image.src = blobTextureURL;
  68504. }
  68505. else {
  68506. notInDBCallback();
  68507. }
  68508. };
  68509. var getRequest = transaction.objectStore("textures").get(url);
  68510. getRequest.onsuccess = function (event) {
  68511. texture = (event.target).result;
  68512. };
  68513. getRequest.onerror = function (event) {
  68514. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  68515. image.src = url;
  68516. };
  68517. }
  68518. else {
  68519. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  68520. image.src = url;
  68521. }
  68522. };
  68523. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  68524. var _this = this;
  68525. if (this.isSupported) {
  68526. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  68527. var generateBlobUrl = function () {
  68528. var blobTextureURL;
  68529. if (blob) {
  68530. var URL = window.URL || window.webkitURL;
  68531. try {
  68532. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  68533. }
  68534. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  68535. catch (ex) {
  68536. blobTextureURL = URL.createObjectURL(blob);
  68537. }
  68538. }
  68539. if (blobTextureURL) {
  68540. image.src = blobTextureURL;
  68541. }
  68542. };
  68543. if (Database.IsUASupportingBlobStorage) { // Create XHR
  68544. var xhr = new XMLHttpRequest(), blob;
  68545. xhr.open("GET", url, true);
  68546. xhr.responseType = "blob";
  68547. xhr.addEventListener("load", function () {
  68548. if (xhr.status === 200 && _this.db) {
  68549. // Blob as response (XHR2)
  68550. blob = xhr.response;
  68551. var transaction = _this.db.transaction(["textures"], "readwrite");
  68552. // the transaction could abort because of a QuotaExceededError error
  68553. transaction.onabort = function (event) {
  68554. try {
  68555. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  68556. var srcElement = (event.srcElement || event.target);
  68557. var error = srcElement.error;
  68558. if (error && error.name === "QuotaExceededError") {
  68559. _this.hasReachedQuota = true;
  68560. }
  68561. }
  68562. catch (ex) { }
  68563. generateBlobUrl();
  68564. };
  68565. transaction.oncomplete = function (event) {
  68566. generateBlobUrl();
  68567. };
  68568. var newTexture = { textureUrl: url, data: blob };
  68569. try {
  68570. // Put the blob into the dabase
  68571. var addRequest = transaction.objectStore("textures").put(newTexture);
  68572. addRequest.onsuccess = function (event) {
  68573. };
  68574. addRequest.onerror = function (event) {
  68575. generateBlobUrl();
  68576. };
  68577. }
  68578. catch (ex) {
  68579. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  68580. if (ex.code === 25) {
  68581. Database.IsUASupportingBlobStorage = false;
  68582. }
  68583. image.src = url;
  68584. }
  68585. }
  68586. else {
  68587. image.src = url;
  68588. }
  68589. }, false);
  68590. xhr.addEventListener("error", function (event) {
  68591. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  68592. image.src = url;
  68593. }, false);
  68594. xhr.send();
  68595. }
  68596. else {
  68597. image.src = url;
  68598. }
  68599. }
  68600. else {
  68601. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  68602. image.src = url;
  68603. }
  68604. };
  68605. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  68606. var _this = this;
  68607. var updateVersion = function () {
  68608. // the version is not yet in the DB or we need to update it
  68609. _this._saveVersionIntoDBAsync(url, versionLoaded);
  68610. };
  68611. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  68612. };
  68613. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  68614. var _this = this;
  68615. if (this.isSupported && this.db) {
  68616. var version;
  68617. try {
  68618. var transaction = this.db.transaction(["versions"]);
  68619. transaction.oncomplete = function (event) {
  68620. if (version) {
  68621. // If the version in the JSON file is different from the version in DB
  68622. if (_this.manifestVersionFound !== version.data) {
  68623. _this.mustUpdateRessources = true;
  68624. updateInDBCallback();
  68625. }
  68626. else {
  68627. callback(version.data);
  68628. }
  68629. }
  68630. // version was not found in DB
  68631. else {
  68632. _this.mustUpdateRessources = true;
  68633. updateInDBCallback();
  68634. }
  68635. };
  68636. transaction.onabort = function (event) {
  68637. callback(-1);
  68638. };
  68639. var getRequest = transaction.objectStore("versions").get(url);
  68640. getRequest.onsuccess = function (event) {
  68641. version = (event.target).result;
  68642. };
  68643. getRequest.onerror = function (event) {
  68644. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  68645. callback(-1);
  68646. };
  68647. }
  68648. catch (ex) {
  68649. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  68650. callback(-1);
  68651. }
  68652. }
  68653. else {
  68654. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  68655. callback(-1);
  68656. }
  68657. };
  68658. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  68659. var _this = this;
  68660. if (this.isSupported && !this.hasReachedQuota && this.db) {
  68661. try {
  68662. // Open a transaction to the database
  68663. var transaction = this.db.transaction(["versions"], "readwrite");
  68664. // the transaction could abort because of a QuotaExceededError error
  68665. transaction.onabort = function (event) {
  68666. try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  68667. var error = event.srcElement['error'];
  68668. if (error && error.name === "QuotaExceededError") {
  68669. _this.hasReachedQuota = true;
  68670. }
  68671. }
  68672. catch (ex) { }
  68673. callback(-1);
  68674. };
  68675. transaction.oncomplete = function (event) {
  68676. callback(_this.manifestVersionFound);
  68677. };
  68678. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  68679. // Put the scene into the database
  68680. var addRequest = transaction.objectStore("versions").put(newVersion);
  68681. addRequest.onsuccess = function (event) {
  68682. };
  68683. addRequest.onerror = function (event) {
  68684. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  68685. };
  68686. }
  68687. catch (ex) {
  68688. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  68689. callback(-1);
  68690. }
  68691. }
  68692. else {
  68693. callback(-1);
  68694. }
  68695. };
  68696. /**
  68697. * Loads a file from database
  68698. * @param url defines the URL to load from
  68699. * @param sceneLoaded defines a callback to call on success
  68700. * @param progressCallBack defines a callback to call when progress changed
  68701. * @param errorCallback defines a callback to call on error
  68702. * @param useArrayBuffer defines a boolean to use array buffer instead of text string
  68703. */
  68704. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  68705. var _this = this;
  68706. var completeUrl = Database._ReturnFullUrlLocation(url);
  68707. var saveAndLoadFile = function () {
  68708. // the scene is not yet in the DB, let's try to save it
  68709. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  68710. };
  68711. this._checkVersionFromDB(completeUrl, function (version) {
  68712. if (version !== -1) {
  68713. if (!_this.mustUpdateRessources) {
  68714. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  68715. }
  68716. else {
  68717. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  68718. }
  68719. }
  68720. else {
  68721. if (errorCallback) {
  68722. errorCallback();
  68723. }
  68724. }
  68725. });
  68726. };
  68727. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  68728. if (this.isSupported && this.db) {
  68729. var targetStore;
  68730. if (url.indexOf(".babylon") !== -1) {
  68731. targetStore = "scenes";
  68732. }
  68733. else {
  68734. targetStore = "textures";
  68735. }
  68736. var file;
  68737. var transaction = this.db.transaction([targetStore]);
  68738. transaction.oncomplete = function (event) {
  68739. if (file) {
  68740. callback(file.data);
  68741. }
  68742. // file was not found in DB
  68743. else {
  68744. notInDBCallback();
  68745. }
  68746. };
  68747. transaction.onabort = function (event) {
  68748. notInDBCallback();
  68749. };
  68750. var getRequest = transaction.objectStore(targetStore).get(url);
  68751. getRequest.onsuccess = function (event) {
  68752. file = (event.target).result;
  68753. };
  68754. getRequest.onerror = function (event) {
  68755. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  68756. notInDBCallback();
  68757. };
  68758. }
  68759. else {
  68760. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  68761. callback();
  68762. }
  68763. };
  68764. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  68765. var _this = this;
  68766. if (this.isSupported) {
  68767. var targetStore;
  68768. if (url.indexOf(".babylon") !== -1) {
  68769. targetStore = "scenes";
  68770. }
  68771. else {
  68772. targetStore = "textures";
  68773. }
  68774. // Create XHR
  68775. var xhr = new XMLHttpRequest();
  68776. var fileData;
  68777. xhr.open("GET", url, true);
  68778. if (useArrayBuffer) {
  68779. xhr.responseType = "arraybuffer";
  68780. }
  68781. if (progressCallback) {
  68782. xhr.onprogress = progressCallback;
  68783. }
  68784. xhr.addEventListener("load", function () {
  68785. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  68786. // Blob as response (XHR2)
  68787. //fileData = xhr.responseText;
  68788. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  68789. if (!_this.hasReachedQuota && _this.db) {
  68790. // Open a transaction to the database
  68791. var transaction = _this.db.transaction([targetStore], "readwrite");
  68792. // the transaction could abort because of a QuotaExceededError error
  68793. transaction.onabort = function (event) {
  68794. try {
  68795. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  68796. var error = event.srcElement['error'];
  68797. if (error && error.name === "QuotaExceededError") {
  68798. _this.hasReachedQuota = true;
  68799. }
  68800. }
  68801. catch (ex) { }
  68802. callback(fileData);
  68803. };
  68804. transaction.oncomplete = function (event) {
  68805. callback(fileData);
  68806. };
  68807. var newFile;
  68808. if (targetStore === "scenes") {
  68809. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  68810. }
  68811. else {
  68812. newFile = { textureUrl: url, data: fileData };
  68813. }
  68814. try {
  68815. // Put the scene into the database
  68816. var addRequest = transaction.objectStore(targetStore).put(newFile);
  68817. addRequest.onsuccess = function (event) {
  68818. };
  68819. addRequest.onerror = function (event) {
  68820. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  68821. };
  68822. }
  68823. catch (ex) {
  68824. callback(fileData);
  68825. }
  68826. }
  68827. else {
  68828. callback(fileData);
  68829. }
  68830. }
  68831. else {
  68832. callback();
  68833. }
  68834. }, false);
  68835. xhr.addEventListener("error", function (event) {
  68836. BABYLON.Tools.Error("error on XHR request.");
  68837. callback();
  68838. }, false);
  68839. xhr.send();
  68840. }
  68841. else {
  68842. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  68843. callback();
  68844. }
  68845. };
  68846. /** Gets a boolean indicating if the user agent supports blob storage (this value will be updated after creating the first Database object) */
  68847. Database.IsUASupportingBlobStorage = true;
  68848. /** Gets a boolean indicating if Database storate is enabled */
  68849. Database.IDBStorageEnabled = true;
  68850. Database._ParseURL = function (url) {
  68851. var a = document.createElement('a');
  68852. a.href = url;
  68853. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  68854. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  68855. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  68856. return absLocation;
  68857. };
  68858. Database._ReturnFullUrlLocation = function (url) {
  68859. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  68860. return (Database._ParseURL(window.location.href) + url);
  68861. }
  68862. else {
  68863. return url;
  68864. }
  68865. };
  68866. return Database;
  68867. }());
  68868. BABYLON.Database = Database;
  68869. })(BABYLON || (BABYLON = {}));
  68870. //# sourceMappingURL=babylon.database.js.map
  68871. var BABYLON;
  68872. (function (BABYLON) {
  68873. var FresnelParameters = /** @class */ (function () {
  68874. function FresnelParameters() {
  68875. this._isEnabled = true;
  68876. this.leftColor = BABYLON.Color3.White();
  68877. this.rightColor = BABYLON.Color3.Black();
  68878. this.bias = 0;
  68879. this.power = 1;
  68880. }
  68881. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  68882. get: function () {
  68883. return this._isEnabled;
  68884. },
  68885. set: function (value) {
  68886. if (this._isEnabled === value) {
  68887. return;
  68888. }
  68889. this._isEnabled = value;
  68890. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  68891. },
  68892. enumerable: true,
  68893. configurable: true
  68894. });
  68895. FresnelParameters.prototype.clone = function () {
  68896. var newFresnelParameters = new FresnelParameters();
  68897. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  68898. return newFresnelParameters;
  68899. };
  68900. FresnelParameters.prototype.serialize = function () {
  68901. var serializationObject = {};
  68902. serializationObject.isEnabled = this.isEnabled;
  68903. serializationObject.leftColor = this.leftColor.asArray();
  68904. serializationObject.rightColor = this.rightColor.asArray();
  68905. serializationObject.bias = this.bias;
  68906. serializationObject.power = this.power;
  68907. return serializationObject;
  68908. };
  68909. FresnelParameters.Parse = function (parsedFresnelParameters) {
  68910. var fresnelParameters = new FresnelParameters();
  68911. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  68912. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  68913. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  68914. fresnelParameters.bias = parsedFresnelParameters.bias;
  68915. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  68916. return fresnelParameters;
  68917. };
  68918. return FresnelParameters;
  68919. }());
  68920. BABYLON.FresnelParameters = FresnelParameters;
  68921. })(BABYLON || (BABYLON = {}));
  68922. //# sourceMappingURL=babylon.fresnelParameters.js.map
  68923. var BABYLON;
  68924. (function (BABYLON) {
  68925. var MultiMaterial = /** @class */ (function (_super) {
  68926. __extends(MultiMaterial, _super);
  68927. function MultiMaterial(name, scene) {
  68928. var _this = _super.call(this, name, scene, true) || this;
  68929. scene.multiMaterials.push(_this);
  68930. _this.subMaterials = new Array();
  68931. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  68932. return _this;
  68933. }
  68934. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  68935. get: function () {
  68936. return this._subMaterials;
  68937. },
  68938. set: function (value) {
  68939. this._subMaterials = value;
  68940. this._hookArray(value);
  68941. },
  68942. enumerable: true,
  68943. configurable: true
  68944. });
  68945. MultiMaterial.prototype._hookArray = function (array) {
  68946. var _this = this;
  68947. var oldPush = array.push;
  68948. array.push = function () {
  68949. var items = [];
  68950. for (var _i = 0; _i < arguments.length; _i++) {
  68951. items[_i] = arguments[_i];
  68952. }
  68953. var result = oldPush.apply(array, items);
  68954. _this._markAllSubMeshesAsTexturesDirty();
  68955. return result;
  68956. };
  68957. var oldSplice = array.splice;
  68958. array.splice = function (index, deleteCount) {
  68959. var deleted = oldSplice.apply(array, [index, deleteCount]);
  68960. _this._markAllSubMeshesAsTexturesDirty();
  68961. return deleted;
  68962. };
  68963. };
  68964. // Properties
  68965. MultiMaterial.prototype.getSubMaterial = function (index) {
  68966. if (index < 0 || index >= this.subMaterials.length) {
  68967. return this.getScene().defaultMaterial;
  68968. }
  68969. return this.subMaterials[index];
  68970. };
  68971. MultiMaterial.prototype.getActiveTextures = function () {
  68972. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  68973. if (subMaterial) {
  68974. return subMaterial.getActiveTextures();
  68975. }
  68976. else {
  68977. return [];
  68978. }
  68979. }));
  68980. var _a;
  68981. };
  68982. // Methods
  68983. MultiMaterial.prototype.getClassName = function () {
  68984. return "MultiMaterial";
  68985. };
  68986. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  68987. for (var index = 0; index < this.subMaterials.length; index++) {
  68988. var subMaterial = this.subMaterials[index];
  68989. if (subMaterial) {
  68990. if (subMaterial.storeEffectOnSubMeshes) {
  68991. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  68992. return false;
  68993. }
  68994. continue;
  68995. }
  68996. if (!subMaterial.isReady(mesh)) {
  68997. return false;
  68998. }
  68999. }
  69000. }
  69001. return true;
  69002. };
  69003. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  69004. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  69005. for (var index = 0; index < this.subMaterials.length; index++) {
  69006. var subMaterial = null;
  69007. var current = this.subMaterials[index];
  69008. if (cloneChildren && current) {
  69009. subMaterial = current.clone(name + "-" + current.name);
  69010. }
  69011. else {
  69012. subMaterial = this.subMaterials[index];
  69013. }
  69014. newMultiMaterial.subMaterials.push(subMaterial);
  69015. }
  69016. return newMultiMaterial;
  69017. };
  69018. MultiMaterial.prototype.serialize = function () {
  69019. var serializationObject = {};
  69020. serializationObject.name = this.name;
  69021. serializationObject.id = this.id;
  69022. if (BABYLON.Tags) {
  69023. serializationObject.tags = BABYLON.Tags.GetTags(this);
  69024. }
  69025. serializationObject.materials = [];
  69026. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  69027. var subMat = this.subMaterials[matIndex];
  69028. if (subMat) {
  69029. serializationObject.materials.push(subMat.id);
  69030. }
  69031. else {
  69032. serializationObject.materials.push(null);
  69033. }
  69034. }
  69035. return serializationObject;
  69036. };
  69037. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  69038. var scene = this.getScene();
  69039. if (!scene) {
  69040. return;
  69041. }
  69042. var index = scene.multiMaterials.indexOf(this);
  69043. if (index >= 0) {
  69044. scene.multiMaterials.splice(index, 1);
  69045. }
  69046. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  69047. };
  69048. return MultiMaterial;
  69049. }(BABYLON.Material));
  69050. BABYLON.MultiMaterial = MultiMaterial;
  69051. })(BABYLON || (BABYLON = {}));
  69052. //# sourceMappingURL=babylon.multiMaterial.js.map
  69053. var BABYLON;
  69054. (function (BABYLON) {
  69055. var FreeCameraTouchInput = /** @class */ (function () {
  69056. function FreeCameraTouchInput() {
  69057. this._offsetX = null;
  69058. this._offsetY = null;
  69059. this._pointerPressed = new Array();
  69060. this.touchAngularSensibility = 200000.0;
  69061. this.touchMoveSensibility = 250.0;
  69062. }
  69063. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  69064. var _this = this;
  69065. var previousPosition = null;
  69066. if (this._pointerInput === undefined) {
  69067. this._onLostFocus = function (evt) {
  69068. _this._offsetX = null;
  69069. _this._offsetY = null;
  69070. };
  69071. this._pointerInput = function (p, s) {
  69072. var evt = p.event;
  69073. if (evt.pointerType === "mouse") {
  69074. return;
  69075. }
  69076. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  69077. if (!noPreventDefault) {
  69078. evt.preventDefault();
  69079. }
  69080. _this._pointerPressed.push(evt.pointerId);
  69081. if (_this._pointerPressed.length !== 1) {
  69082. return;
  69083. }
  69084. previousPosition = {
  69085. x: evt.clientX,
  69086. y: evt.clientY
  69087. };
  69088. }
  69089. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  69090. if (!noPreventDefault) {
  69091. evt.preventDefault();
  69092. }
  69093. var index = _this._pointerPressed.indexOf(evt.pointerId);
  69094. if (index === -1) {
  69095. return;
  69096. }
  69097. _this._pointerPressed.splice(index, 1);
  69098. if (index != 0) {
  69099. return;
  69100. }
  69101. previousPosition = null;
  69102. _this._offsetX = null;
  69103. _this._offsetY = null;
  69104. }
  69105. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  69106. if (!noPreventDefault) {
  69107. evt.preventDefault();
  69108. }
  69109. if (!previousPosition) {
  69110. return;
  69111. }
  69112. var index = _this._pointerPressed.indexOf(evt.pointerId);
  69113. if (index != 0) {
  69114. return;
  69115. }
  69116. _this._offsetX = evt.clientX - previousPosition.x;
  69117. _this._offsetY = -(evt.clientY - previousPosition.y);
  69118. }
  69119. };
  69120. }
  69121. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  69122. if (this._onLostFocus) {
  69123. element.addEventListener("blur", this._onLostFocus);
  69124. }
  69125. };
  69126. FreeCameraTouchInput.prototype.detachControl = function (element) {
  69127. if (this._pointerInput && element) {
  69128. if (this._observer) {
  69129. this.camera.getScene().onPointerObservable.remove(this._observer);
  69130. this._observer = null;
  69131. }
  69132. if (this._onLostFocus) {
  69133. element.removeEventListener("blur", this._onLostFocus);
  69134. this._onLostFocus = null;
  69135. }
  69136. this._pointerPressed = [];
  69137. this._offsetX = null;
  69138. this._offsetY = null;
  69139. }
  69140. };
  69141. FreeCameraTouchInput.prototype.checkInputs = function () {
  69142. if (this._offsetX && this._offsetY) {
  69143. var camera = this.camera;
  69144. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  69145. if (this._pointerPressed.length > 1) {
  69146. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  69147. }
  69148. else {
  69149. var speed = camera._computeLocalCameraSpeed();
  69150. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  69151. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  69152. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  69153. }
  69154. }
  69155. };
  69156. FreeCameraTouchInput.prototype.getClassName = function () {
  69157. return "FreeCameraTouchInput";
  69158. };
  69159. FreeCameraTouchInput.prototype.getSimpleName = function () {
  69160. return "touch";
  69161. };
  69162. __decorate([
  69163. BABYLON.serialize()
  69164. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  69165. __decorate([
  69166. BABYLON.serialize()
  69167. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  69168. return FreeCameraTouchInput;
  69169. }());
  69170. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  69171. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  69172. })(BABYLON || (BABYLON = {}));
  69173. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  69174. var BABYLON;
  69175. (function (BABYLON) {
  69176. // We're mainly based on the logic defined into the FreeCamera code
  69177. var TouchCamera = /** @class */ (function (_super) {
  69178. __extends(TouchCamera, _super);
  69179. //-- end properties for backward compatibility for inputs
  69180. function TouchCamera(name, position, scene) {
  69181. var _this = _super.call(this, name, position, scene) || this;
  69182. _this.inputs.addTouch();
  69183. _this._setupInputs();
  69184. return _this;
  69185. }
  69186. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  69187. //-- Begin properties for backward compatibility for inputs
  69188. get: function () {
  69189. var touch = this.inputs.attached["touch"];
  69190. if (touch)
  69191. return touch.touchAngularSensibility;
  69192. return 0;
  69193. },
  69194. set: function (value) {
  69195. var touch = this.inputs.attached["touch"];
  69196. if (touch)
  69197. touch.touchAngularSensibility = value;
  69198. },
  69199. enumerable: true,
  69200. configurable: true
  69201. });
  69202. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  69203. get: function () {
  69204. var touch = this.inputs.attached["touch"];
  69205. if (touch)
  69206. return touch.touchMoveSensibility;
  69207. return 0;
  69208. },
  69209. set: function (value) {
  69210. var touch = this.inputs.attached["touch"];
  69211. if (touch)
  69212. touch.touchMoveSensibility = value;
  69213. },
  69214. enumerable: true,
  69215. configurable: true
  69216. });
  69217. TouchCamera.prototype.getClassName = function () {
  69218. return "TouchCamera";
  69219. };
  69220. TouchCamera.prototype._setupInputs = function () {
  69221. var mouse = this.inputs.attached["mouse"];
  69222. if (mouse) {
  69223. mouse.touchEnabled = false;
  69224. }
  69225. };
  69226. return TouchCamera;
  69227. }(BABYLON.FreeCamera));
  69228. BABYLON.TouchCamera = TouchCamera;
  69229. })(BABYLON || (BABYLON = {}));
  69230. //# sourceMappingURL=babylon.touchCamera.js.map
  69231. var BABYLON;
  69232. (function (BABYLON) {
  69233. var ProceduralTexture = /** @class */ (function (_super) {
  69234. __extends(ProceduralTexture, _super);
  69235. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  69236. if (fallbackTexture === void 0) { fallbackTexture = null; }
  69237. if (generateMipMaps === void 0) { generateMipMaps = true; }
  69238. if (isCube === void 0) { isCube = false; }
  69239. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  69240. _this.isCube = isCube;
  69241. _this.isEnabled = true;
  69242. _this._currentRefreshId = -1;
  69243. _this._refreshRate = 1;
  69244. _this._vertexBuffers = {};
  69245. _this._uniforms = new Array();
  69246. _this._samplers = new Array();
  69247. _this._textures = {};
  69248. _this._floats = {};
  69249. _this._floatsArrays = {};
  69250. _this._colors3 = {};
  69251. _this._colors4 = {};
  69252. _this._vectors2 = {};
  69253. _this._vectors3 = {};
  69254. _this._matrices = {};
  69255. _this._fallbackTextureUsed = false;
  69256. scene.proceduralTextures.push(_this);
  69257. _this._engine = scene.getEngine();
  69258. _this.name = name;
  69259. _this.isRenderTarget = true;
  69260. _this._size = size;
  69261. _this._generateMipMaps = generateMipMaps;
  69262. _this.setFragment(fragment);
  69263. _this._fallbackTexture = fallbackTexture;
  69264. if (isCube) {
  69265. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  69266. _this.setFloat("face", 0);
  69267. }
  69268. else {
  69269. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  69270. }
  69271. // VBO
  69272. var vertices = [];
  69273. vertices.push(1, 1);
  69274. vertices.push(-1, 1);
  69275. vertices.push(-1, -1);
  69276. vertices.push(1, -1);
  69277. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  69278. _this._createIndexBuffer();
  69279. return _this;
  69280. }
  69281. ProceduralTexture.prototype._createIndexBuffer = function () {
  69282. var engine = this._engine;
  69283. // Indices
  69284. var indices = [];
  69285. indices.push(0);
  69286. indices.push(1);
  69287. indices.push(2);
  69288. indices.push(0);
  69289. indices.push(2);
  69290. indices.push(3);
  69291. this._indexBuffer = engine.createIndexBuffer(indices);
  69292. };
  69293. ProceduralTexture.prototype._rebuild = function () {
  69294. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  69295. if (vb) {
  69296. vb._rebuild();
  69297. }
  69298. this._createIndexBuffer();
  69299. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  69300. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  69301. }
  69302. };
  69303. ProceduralTexture.prototype.reset = function () {
  69304. if (this._effect === undefined) {
  69305. return;
  69306. }
  69307. var engine = this._engine;
  69308. engine._releaseEffect(this._effect);
  69309. };
  69310. ProceduralTexture.prototype.isReady = function () {
  69311. var _this = this;
  69312. var engine = this._engine;
  69313. var shaders;
  69314. if (!this._fragment) {
  69315. return false;
  69316. }
  69317. if (this._fallbackTextureUsed) {
  69318. return true;
  69319. }
  69320. if (this._fragment.fragmentElement !== undefined) {
  69321. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  69322. }
  69323. else {
  69324. shaders = { vertex: "procedural", fragment: this._fragment };
  69325. }
  69326. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  69327. _this.releaseInternalTexture();
  69328. if (_this._fallbackTexture) {
  69329. _this._texture = _this._fallbackTexture._texture;
  69330. if (_this._texture) {
  69331. _this._texture.incrementReferences();
  69332. }
  69333. }
  69334. _this._fallbackTextureUsed = true;
  69335. });
  69336. return this._effect.isReady();
  69337. };
  69338. ProceduralTexture.prototype.resetRefreshCounter = function () {
  69339. this._currentRefreshId = -1;
  69340. };
  69341. ProceduralTexture.prototype.setFragment = function (fragment) {
  69342. this._fragment = fragment;
  69343. };
  69344. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  69345. get: function () {
  69346. return this._refreshRate;
  69347. },
  69348. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  69349. set: function (value) {
  69350. this._refreshRate = value;
  69351. this.resetRefreshCounter();
  69352. },
  69353. enumerable: true,
  69354. configurable: true
  69355. });
  69356. ProceduralTexture.prototype._shouldRender = function () {
  69357. if (!this.isEnabled || !this.isReady() || !this._texture) {
  69358. return false;
  69359. }
  69360. if (this._fallbackTextureUsed) {
  69361. return false;
  69362. }
  69363. if (this._currentRefreshId === -1) { // At least render once
  69364. this._currentRefreshId = 1;
  69365. return true;
  69366. }
  69367. if (this.refreshRate === this._currentRefreshId) {
  69368. this._currentRefreshId = 1;
  69369. return true;
  69370. }
  69371. this._currentRefreshId++;
  69372. return false;
  69373. };
  69374. ProceduralTexture.prototype.getRenderSize = function () {
  69375. return this._size;
  69376. };
  69377. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  69378. if (this._fallbackTextureUsed) {
  69379. return;
  69380. }
  69381. this.releaseInternalTexture();
  69382. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  69383. // Update properties
  69384. this._size = size;
  69385. this._generateMipMaps = generateMipMaps;
  69386. };
  69387. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  69388. if (this._uniforms.indexOf(uniformName) === -1) {
  69389. this._uniforms.push(uniformName);
  69390. }
  69391. };
  69392. ProceduralTexture.prototype.setTexture = function (name, texture) {
  69393. if (this._samplers.indexOf(name) === -1) {
  69394. this._samplers.push(name);
  69395. }
  69396. this._textures[name] = texture;
  69397. return this;
  69398. };
  69399. ProceduralTexture.prototype.setFloat = function (name, value) {
  69400. this._checkUniform(name);
  69401. this._floats[name] = value;
  69402. return this;
  69403. };
  69404. ProceduralTexture.prototype.setFloats = function (name, value) {
  69405. this._checkUniform(name);
  69406. this._floatsArrays[name] = value;
  69407. return this;
  69408. };
  69409. ProceduralTexture.prototype.setColor3 = function (name, value) {
  69410. this._checkUniform(name);
  69411. this._colors3[name] = value;
  69412. return this;
  69413. };
  69414. ProceduralTexture.prototype.setColor4 = function (name, value) {
  69415. this._checkUniform(name);
  69416. this._colors4[name] = value;
  69417. return this;
  69418. };
  69419. ProceduralTexture.prototype.setVector2 = function (name, value) {
  69420. this._checkUniform(name);
  69421. this._vectors2[name] = value;
  69422. return this;
  69423. };
  69424. ProceduralTexture.prototype.setVector3 = function (name, value) {
  69425. this._checkUniform(name);
  69426. this._vectors3[name] = value;
  69427. return this;
  69428. };
  69429. ProceduralTexture.prototype.setMatrix = function (name, value) {
  69430. this._checkUniform(name);
  69431. this._matrices[name] = value;
  69432. return this;
  69433. };
  69434. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  69435. var scene = this.getScene();
  69436. if (!scene) {
  69437. return;
  69438. }
  69439. var engine = this._engine;
  69440. // Render
  69441. engine.enableEffect(this._effect);
  69442. engine.setState(false);
  69443. // Texture
  69444. for (var name in this._textures) {
  69445. this._effect.setTexture(name, this._textures[name]);
  69446. }
  69447. // Float
  69448. for (name in this._floats) {
  69449. this._effect.setFloat(name, this._floats[name]);
  69450. }
  69451. // Floats
  69452. for (name in this._floatsArrays) {
  69453. this._effect.setArray(name, this._floatsArrays[name]);
  69454. }
  69455. // Color3
  69456. for (name in this._colors3) {
  69457. this._effect.setColor3(name, this._colors3[name]);
  69458. }
  69459. // Color4
  69460. for (name in this._colors4) {
  69461. var color = this._colors4[name];
  69462. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  69463. }
  69464. // Vector2
  69465. for (name in this._vectors2) {
  69466. this._effect.setVector2(name, this._vectors2[name]);
  69467. }
  69468. // Vector3
  69469. for (name in this._vectors3) {
  69470. this._effect.setVector3(name, this._vectors3[name]);
  69471. }
  69472. // Matrix
  69473. for (name in this._matrices) {
  69474. this._effect.setMatrix(name, this._matrices[name]);
  69475. }
  69476. if (!this._texture) {
  69477. return;
  69478. }
  69479. if (this.isCube) {
  69480. for (var face = 0; face < 6; face++) {
  69481. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  69482. // VBOs
  69483. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  69484. this._effect.setFloat("face", face);
  69485. // Clear
  69486. engine.clear(scene.clearColor, true, true, true);
  69487. // Draw order
  69488. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  69489. // Mipmaps
  69490. if (face === 5) {
  69491. engine.generateMipMapsForCubemap(this._texture);
  69492. }
  69493. }
  69494. }
  69495. else {
  69496. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  69497. // VBOs
  69498. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  69499. // Clear
  69500. engine.clear(scene.clearColor, true, true, true);
  69501. // Draw order
  69502. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  69503. }
  69504. // Unbind
  69505. engine.unBindFramebuffer(this._texture, this.isCube);
  69506. if (this.onGenerated) {
  69507. this.onGenerated();
  69508. }
  69509. };
  69510. ProceduralTexture.prototype.clone = function () {
  69511. var textureSize = this.getSize();
  69512. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  69513. // Base texture
  69514. newTexture.hasAlpha = this.hasAlpha;
  69515. newTexture.level = this.level;
  69516. // RenderTarget Texture
  69517. newTexture.coordinatesMode = this.coordinatesMode;
  69518. return newTexture;
  69519. };
  69520. ProceduralTexture.prototype.dispose = function () {
  69521. var scene = this.getScene();
  69522. if (!scene) {
  69523. return;
  69524. }
  69525. var index = scene.proceduralTextures.indexOf(this);
  69526. if (index >= 0) {
  69527. scene.proceduralTextures.splice(index, 1);
  69528. }
  69529. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  69530. if (vertexBuffer) {
  69531. vertexBuffer.dispose();
  69532. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  69533. }
  69534. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  69535. this._indexBuffer = null;
  69536. }
  69537. _super.prototype.dispose.call(this);
  69538. };
  69539. __decorate([
  69540. BABYLON.serialize()
  69541. ], ProceduralTexture.prototype, "_size", void 0);
  69542. __decorate([
  69543. BABYLON.serialize()
  69544. ], ProceduralTexture.prototype, "_generateMipMaps", void 0);
  69545. __decorate([
  69546. BABYLON.serialize()
  69547. ], ProceduralTexture.prototype, "isEnabled", void 0);
  69548. __decorate([
  69549. BABYLON.serialize()
  69550. ], ProceduralTexture.prototype, "refreshRate", null);
  69551. return ProceduralTexture;
  69552. }(BABYLON.Texture));
  69553. BABYLON.ProceduralTexture = ProceduralTexture;
  69554. })(BABYLON || (BABYLON = {}));
  69555. //# sourceMappingURL=babylon.proceduralTexture.js.map
  69556. var BABYLON;
  69557. (function (BABYLON) {
  69558. var CustomProceduralTexture = /** @class */ (function (_super) {
  69559. __extends(CustomProceduralTexture, _super);
  69560. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  69561. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  69562. _this._animate = true;
  69563. _this._time = 0;
  69564. _this._texturePath = texturePath;
  69565. //Try to load json
  69566. _this.loadJson(texturePath);
  69567. _this.refreshRate = 1;
  69568. return _this;
  69569. }
  69570. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  69571. var _this = this;
  69572. var noConfigFile = function () {
  69573. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  69574. try {
  69575. _this.setFragment(_this._texturePath);
  69576. }
  69577. catch (ex) {
  69578. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  69579. }
  69580. };
  69581. var configFileUrl = jsonUrl + "/config.json";
  69582. var xhr = new XMLHttpRequest();
  69583. xhr.open("GET", configFileUrl, true);
  69584. xhr.addEventListener("load", function () {
  69585. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  69586. try {
  69587. _this._config = JSON.parse(xhr.response);
  69588. _this.updateShaderUniforms();
  69589. _this.updateTextures();
  69590. _this.setFragment(_this._texturePath + "/custom");
  69591. _this._animate = _this._config.animate;
  69592. _this.refreshRate = _this._config.refreshrate;
  69593. }
  69594. catch (ex) {
  69595. noConfigFile();
  69596. }
  69597. }
  69598. else {
  69599. noConfigFile();
  69600. }
  69601. }, false);
  69602. xhr.addEventListener("error", function () {
  69603. noConfigFile();
  69604. }, false);
  69605. try {
  69606. xhr.send();
  69607. }
  69608. catch (ex) {
  69609. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  69610. }
  69611. };
  69612. CustomProceduralTexture.prototype.isReady = function () {
  69613. if (!_super.prototype.isReady.call(this)) {
  69614. return false;
  69615. }
  69616. for (var name in this._textures) {
  69617. var texture = this._textures[name];
  69618. if (!texture.isReady()) {
  69619. return false;
  69620. }
  69621. }
  69622. return true;
  69623. };
  69624. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  69625. var scene = this.getScene();
  69626. if (this._animate && scene) {
  69627. this._time += scene.getAnimationRatio() * 0.03;
  69628. this.updateShaderUniforms();
  69629. }
  69630. _super.prototype.render.call(this, useCameraPostProcess);
  69631. };
  69632. CustomProceduralTexture.prototype.updateTextures = function () {
  69633. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  69634. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  69635. }
  69636. };
  69637. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  69638. if (this._config) {
  69639. for (var j = 0; j < this._config.uniforms.length; j++) {
  69640. var uniform = this._config.uniforms[j];
  69641. switch (uniform.type) {
  69642. case "float":
  69643. this.setFloat(uniform.name, uniform.value);
  69644. break;
  69645. case "color3":
  69646. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  69647. break;
  69648. case "color4":
  69649. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  69650. break;
  69651. case "vector2":
  69652. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  69653. break;
  69654. case "vector3":
  69655. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  69656. break;
  69657. }
  69658. }
  69659. }
  69660. this.setFloat("time", this._time);
  69661. };
  69662. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  69663. get: function () {
  69664. return this._animate;
  69665. },
  69666. set: function (value) {
  69667. this._animate = value;
  69668. },
  69669. enumerable: true,
  69670. configurable: true
  69671. });
  69672. return CustomProceduralTexture;
  69673. }(BABYLON.ProceduralTexture));
  69674. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  69675. })(BABYLON || (BABYLON = {}));
  69676. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  69677. var BABYLON;
  69678. (function (BABYLON) {
  69679. var FreeCameraGamepadInput = /** @class */ (function () {
  69680. function FreeCameraGamepadInput() {
  69681. this.gamepadAngularSensibility = 200;
  69682. this.gamepadMoveSensibility = 40;
  69683. // private members
  69684. this._cameraTransform = BABYLON.Matrix.Identity();
  69685. this._deltaTransform = BABYLON.Vector3.Zero();
  69686. this._vector3 = BABYLON.Vector3.Zero();
  69687. this._vector2 = BABYLON.Vector2.Zero();
  69688. }
  69689. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  69690. var _this = this;
  69691. var manager = this.camera.getScene().gamepadManager;
  69692. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  69693. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  69694. // prioritize XBOX gamepads.
  69695. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  69696. _this.gamepad = gamepad;
  69697. }
  69698. }
  69699. });
  69700. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  69701. if (_this.gamepad === gamepad) {
  69702. _this.gamepad = null;
  69703. }
  69704. });
  69705. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  69706. };
  69707. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  69708. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  69709. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  69710. this.gamepad = null;
  69711. };
  69712. FreeCameraGamepadInput.prototype.checkInputs = function () {
  69713. if (this.gamepad && this.gamepad.leftStick) {
  69714. var camera = this.camera;
  69715. var LSValues = this.gamepad.leftStick;
  69716. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  69717. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  69718. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  69719. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  69720. var RSValues = this.gamepad.rightStick;
  69721. if (RSValues) {
  69722. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  69723. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  69724. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  69725. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  69726. }
  69727. else {
  69728. RSValues = { x: 0, y: 0 };
  69729. }
  69730. if (!camera.rotationQuaternion) {
  69731. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  69732. }
  69733. else {
  69734. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  69735. }
  69736. var speed = camera._computeLocalCameraSpeed() * 50.0;
  69737. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  69738. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  69739. camera.cameraDirection.addInPlace(this._deltaTransform);
  69740. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  69741. camera.cameraRotation.addInPlace(this._vector2);
  69742. }
  69743. };
  69744. FreeCameraGamepadInput.prototype.getClassName = function () {
  69745. return "FreeCameraGamepadInput";
  69746. };
  69747. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  69748. return "gamepad";
  69749. };
  69750. __decorate([
  69751. BABYLON.serialize()
  69752. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  69753. __decorate([
  69754. BABYLON.serialize()
  69755. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  69756. return FreeCameraGamepadInput;
  69757. }());
  69758. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  69759. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  69760. })(BABYLON || (BABYLON = {}));
  69761. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  69762. var BABYLON;
  69763. (function (BABYLON) {
  69764. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  69765. function ArcRotateCameraGamepadInput() {
  69766. this.gamepadRotationSensibility = 80;
  69767. this.gamepadMoveSensibility = 40;
  69768. }
  69769. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  69770. var _this = this;
  69771. var manager = this.camera.getScene().gamepadManager;
  69772. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  69773. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  69774. // prioritize XBOX gamepads.
  69775. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  69776. _this.gamepad = gamepad;
  69777. }
  69778. }
  69779. });
  69780. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  69781. if (_this.gamepad === gamepad) {
  69782. _this.gamepad = null;
  69783. }
  69784. });
  69785. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  69786. };
  69787. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  69788. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  69789. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  69790. this.gamepad = null;
  69791. };
  69792. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  69793. if (this.gamepad) {
  69794. var camera = this.camera;
  69795. var RSValues = this.gamepad.rightStick;
  69796. if (RSValues) {
  69797. if (RSValues.x != 0) {
  69798. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  69799. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  69800. camera.inertialAlphaOffset += normalizedRX;
  69801. }
  69802. }
  69803. if (RSValues.y != 0) {
  69804. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  69805. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  69806. camera.inertialBetaOffset += normalizedRY;
  69807. }
  69808. }
  69809. }
  69810. var LSValues = this.gamepad.leftStick;
  69811. if (LSValues && LSValues.y != 0) {
  69812. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  69813. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  69814. this.camera.inertialRadiusOffset -= normalizedLY;
  69815. }
  69816. }
  69817. }
  69818. };
  69819. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  69820. return "ArcRotateCameraGamepadInput";
  69821. };
  69822. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  69823. return "gamepad";
  69824. };
  69825. __decorate([
  69826. BABYLON.serialize()
  69827. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  69828. __decorate([
  69829. BABYLON.serialize()
  69830. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  69831. return ArcRotateCameraGamepadInput;
  69832. }());
  69833. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  69834. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  69835. })(BABYLON || (BABYLON = {}));
  69836. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  69837. var BABYLON;
  69838. (function (BABYLON) {
  69839. var GamepadManager = /** @class */ (function () {
  69840. function GamepadManager(_scene) {
  69841. var _this = this;
  69842. this._scene = _scene;
  69843. this._babylonGamepads = [];
  69844. this._oneGamepadConnected = false;
  69845. this._isMonitoring = false;
  69846. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  69847. if (!BABYLON.Tools.IsWindowObjectExist()) {
  69848. this._gamepadEventSupported = false;
  69849. }
  69850. else {
  69851. this._gamepadEventSupported = 'GamepadEvent' in window;
  69852. this._gamepadSupport = (navigator.getGamepads ||
  69853. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  69854. }
  69855. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  69856. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  69857. for (var i in _this._babylonGamepads) {
  69858. var gamepad = _this._babylonGamepads[i];
  69859. if (gamepad && gamepad._isConnected) {
  69860. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  69861. }
  69862. }
  69863. });
  69864. this._onGamepadConnectedEvent = function (evt) {
  69865. var gamepad = evt.gamepad;
  69866. if (gamepad.index in _this._babylonGamepads) {
  69867. if (_this._babylonGamepads[gamepad.index].isConnected) {
  69868. return;
  69869. }
  69870. }
  69871. var newGamepad;
  69872. if (_this._babylonGamepads[gamepad.index]) {
  69873. newGamepad = _this._babylonGamepads[gamepad.index];
  69874. newGamepad.browserGamepad = gamepad;
  69875. newGamepad._isConnected = true;
  69876. }
  69877. else {
  69878. newGamepad = _this._addNewGamepad(gamepad);
  69879. }
  69880. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  69881. _this._startMonitoringGamepads();
  69882. };
  69883. this._onGamepadDisconnectedEvent = function (evt) {
  69884. var gamepad = evt.gamepad;
  69885. // Remove the gamepad from the list of gamepads to monitor.
  69886. for (var i in _this._babylonGamepads) {
  69887. if (_this._babylonGamepads[i].index === gamepad.index) {
  69888. var disconnectedGamepad = _this._babylonGamepads[i];
  69889. disconnectedGamepad._isConnected = false;
  69890. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  69891. break;
  69892. }
  69893. }
  69894. };
  69895. if (this._gamepadSupport) {
  69896. //first add already-connected gamepads
  69897. this._updateGamepadObjects();
  69898. if (this._babylonGamepads.length) {
  69899. this._startMonitoringGamepads();
  69900. }
  69901. // Checking if the gamepad connected event is supported (like in Firefox)
  69902. if (this._gamepadEventSupported) {
  69903. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  69904. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  69905. }
  69906. else {
  69907. this._startMonitoringGamepads();
  69908. }
  69909. }
  69910. }
  69911. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  69912. get: function () {
  69913. return this._babylonGamepads;
  69914. },
  69915. enumerable: true,
  69916. configurable: true
  69917. });
  69918. GamepadManager.prototype.getGamepadByType = function (type) {
  69919. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  69920. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  69921. var gamepad = _a[_i];
  69922. if (gamepad && gamepad.type === type) {
  69923. return gamepad;
  69924. }
  69925. }
  69926. return null;
  69927. };
  69928. GamepadManager.prototype.dispose = function () {
  69929. if (this._gamepadEventSupported) {
  69930. if (this._onGamepadConnectedEvent) {
  69931. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  69932. }
  69933. if (this._onGamepadDisconnectedEvent) {
  69934. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  69935. }
  69936. this._onGamepadConnectedEvent = null;
  69937. this._onGamepadDisconnectedEvent = null;
  69938. }
  69939. this._babylonGamepads.forEach(function (gamepad) {
  69940. gamepad.dispose();
  69941. });
  69942. this.onGamepadConnectedObservable.clear();
  69943. this.onGamepadDisconnectedObservable.clear();
  69944. this._oneGamepadConnected = false;
  69945. this._stopMonitoringGamepads();
  69946. this._babylonGamepads = [];
  69947. };
  69948. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  69949. if (!this._oneGamepadConnected) {
  69950. this._oneGamepadConnected = true;
  69951. }
  69952. var newGamepad;
  69953. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  69954. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  69955. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  69956. }
  69957. // if pose is supported, use the (WebVR) pose enabled controller
  69958. else if (gamepad.pose) {
  69959. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  69960. }
  69961. else {
  69962. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  69963. }
  69964. this._babylonGamepads[newGamepad.index] = newGamepad;
  69965. return newGamepad;
  69966. };
  69967. GamepadManager.prototype._startMonitoringGamepads = function () {
  69968. if (!this._isMonitoring) {
  69969. this._isMonitoring = true;
  69970. //back-comp
  69971. if (!this._scene) {
  69972. this._checkGamepadsStatus();
  69973. }
  69974. }
  69975. };
  69976. GamepadManager.prototype._stopMonitoringGamepads = function () {
  69977. this._isMonitoring = false;
  69978. };
  69979. GamepadManager.prototype._checkGamepadsStatus = function () {
  69980. var _this = this;
  69981. // Hack to be compatible Chrome
  69982. this._updateGamepadObjects();
  69983. for (var i in this._babylonGamepads) {
  69984. var gamepad = this._babylonGamepads[i];
  69985. if (!gamepad || !gamepad.isConnected) {
  69986. continue;
  69987. }
  69988. gamepad.update();
  69989. }
  69990. if (this._isMonitoring && !this._scene) {
  69991. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  69992. }
  69993. };
  69994. // This function is called only on Chrome, which does not properly support
  69995. // connection/disconnection events and forces you to recopy again the gamepad object
  69996. GamepadManager.prototype._updateGamepadObjects = function () {
  69997. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  69998. for (var i = 0; i < gamepads.length; i++) {
  69999. var gamepad = gamepads[i];
  70000. if (gamepad) {
  70001. if (!this._babylonGamepads[gamepad.index]) {
  70002. var newGamepad = this._addNewGamepad(gamepad);
  70003. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  70004. }
  70005. else {
  70006. // Forced to copy again this object for Chrome for unknown reason
  70007. this._babylonGamepads[i].browserGamepad = gamepad;
  70008. if (!this._babylonGamepads[i].isConnected) {
  70009. this._babylonGamepads[i]._isConnected = true;
  70010. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  70011. }
  70012. }
  70013. }
  70014. }
  70015. };
  70016. return GamepadManager;
  70017. }());
  70018. BABYLON.GamepadManager = GamepadManager;
  70019. })(BABYLON || (BABYLON = {}));
  70020. //# sourceMappingURL=babylon.gamepadManager.js.map
  70021. var BABYLON;
  70022. (function (BABYLON) {
  70023. var StickValues = /** @class */ (function () {
  70024. function StickValues(x, y) {
  70025. this.x = x;
  70026. this.y = y;
  70027. }
  70028. return StickValues;
  70029. }());
  70030. BABYLON.StickValues = StickValues;
  70031. var Gamepad = /** @class */ (function () {
  70032. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  70033. if (leftStickX === void 0) { leftStickX = 0; }
  70034. if (leftStickY === void 0) { leftStickY = 1; }
  70035. if (rightStickX === void 0) { rightStickX = 2; }
  70036. if (rightStickY === void 0) { rightStickY = 3; }
  70037. this.id = id;
  70038. this.index = index;
  70039. this.browserGamepad = browserGamepad;
  70040. this._isConnected = true;
  70041. this._invertLeftStickY = false;
  70042. this.type = Gamepad.GAMEPAD;
  70043. this._leftStickAxisX = leftStickX;
  70044. this._leftStickAxisY = leftStickY;
  70045. this._rightStickAxisX = rightStickX;
  70046. this._rightStickAxisY = rightStickY;
  70047. if (this.browserGamepad.axes.length >= 2) {
  70048. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  70049. }
  70050. if (this.browserGamepad.axes.length >= 4) {
  70051. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  70052. }
  70053. }
  70054. Object.defineProperty(Gamepad.prototype, "isConnected", {
  70055. get: function () {
  70056. return this._isConnected;
  70057. },
  70058. enumerable: true,
  70059. configurable: true
  70060. });
  70061. Gamepad.prototype.onleftstickchanged = function (callback) {
  70062. this._onleftstickchanged = callback;
  70063. };
  70064. Gamepad.prototype.onrightstickchanged = function (callback) {
  70065. this._onrightstickchanged = callback;
  70066. };
  70067. Object.defineProperty(Gamepad.prototype, "leftStick", {
  70068. get: function () {
  70069. return this._leftStick;
  70070. },
  70071. set: function (newValues) {
  70072. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  70073. this._onleftstickchanged(newValues);
  70074. }
  70075. this._leftStick = newValues;
  70076. },
  70077. enumerable: true,
  70078. configurable: true
  70079. });
  70080. Object.defineProperty(Gamepad.prototype, "rightStick", {
  70081. get: function () {
  70082. return this._rightStick;
  70083. },
  70084. set: function (newValues) {
  70085. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  70086. this._onrightstickchanged(newValues);
  70087. }
  70088. this._rightStick = newValues;
  70089. },
  70090. enumerable: true,
  70091. configurable: true
  70092. });
  70093. Gamepad.prototype.update = function () {
  70094. if (this._leftStick) {
  70095. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  70096. if (this._invertLeftStickY) {
  70097. this.leftStick.y *= -1;
  70098. }
  70099. }
  70100. if (this._rightStick) {
  70101. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  70102. }
  70103. };
  70104. Gamepad.prototype.dispose = function () {
  70105. };
  70106. Gamepad.GAMEPAD = 0;
  70107. Gamepad.GENERIC = 1;
  70108. Gamepad.XBOX = 2;
  70109. Gamepad.POSE_ENABLED = 3;
  70110. return Gamepad;
  70111. }());
  70112. BABYLON.Gamepad = Gamepad;
  70113. var GenericPad = /** @class */ (function (_super) {
  70114. __extends(GenericPad, _super);
  70115. function GenericPad(id, index, browserGamepad) {
  70116. var _this = _super.call(this, id, index, browserGamepad) || this;
  70117. _this.onButtonDownObservable = new BABYLON.Observable();
  70118. _this.onButtonUpObservable = new BABYLON.Observable();
  70119. _this.type = Gamepad.GENERIC;
  70120. _this._buttons = new Array(browserGamepad.buttons.length);
  70121. return _this;
  70122. }
  70123. GenericPad.prototype.onbuttondown = function (callback) {
  70124. this._onbuttondown = callback;
  70125. };
  70126. GenericPad.prototype.onbuttonup = function (callback) {
  70127. this._onbuttonup = callback;
  70128. };
  70129. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  70130. if (newValue !== currentValue) {
  70131. if (newValue === 1) {
  70132. if (this._onbuttondown) {
  70133. this._onbuttondown(buttonIndex);
  70134. }
  70135. this.onButtonDownObservable.notifyObservers(buttonIndex);
  70136. }
  70137. if (newValue === 0) {
  70138. if (this._onbuttonup) {
  70139. this._onbuttonup(buttonIndex);
  70140. }
  70141. this.onButtonUpObservable.notifyObservers(buttonIndex);
  70142. }
  70143. }
  70144. return newValue;
  70145. };
  70146. GenericPad.prototype.update = function () {
  70147. _super.prototype.update.call(this);
  70148. for (var index = 0; index < this._buttons.length; index++) {
  70149. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  70150. }
  70151. };
  70152. GenericPad.prototype.dispose = function () {
  70153. _super.prototype.dispose.call(this);
  70154. this.onButtonDownObservable.clear();
  70155. this.onButtonUpObservable.clear();
  70156. };
  70157. return GenericPad;
  70158. }(Gamepad));
  70159. BABYLON.GenericPad = GenericPad;
  70160. })(BABYLON || (BABYLON = {}));
  70161. //# sourceMappingURL=babylon.gamepad.js.map
  70162. var BABYLON;
  70163. (function (BABYLON) {
  70164. /**
  70165. * Defines supported buttons for XBox360 compatible gamepads
  70166. */
  70167. var Xbox360Button;
  70168. (function (Xbox360Button) {
  70169. /** A */
  70170. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  70171. /** B */
  70172. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  70173. /** X */
  70174. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  70175. /** Y */
  70176. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  70177. /** Start */
  70178. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  70179. /** Back */
  70180. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  70181. /** Left button */
  70182. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  70183. /** Right button */
  70184. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  70185. /** Left stick */
  70186. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  70187. /** Right stick */
  70188. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  70189. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  70190. /** Defines values for XBox360 DPad */
  70191. var Xbox360Dpad;
  70192. (function (Xbox360Dpad) {
  70193. /** Up */
  70194. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  70195. /** Down */
  70196. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  70197. /** Left */
  70198. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  70199. /** Right */
  70200. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  70201. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  70202. /**
  70203. * Defines a XBox360 gamepad
  70204. */
  70205. var Xbox360Pad = /** @class */ (function (_super) {
  70206. __extends(Xbox360Pad, _super);
  70207. /**
  70208. * Creates a new XBox360 gamepad object
  70209. * @param id defines the id of this gamepad
  70210. * @param index defines its index
  70211. * @param gamepad defines the internal HTML gamepad object
  70212. * @param xboxOne defines if it is a XBox One gamepad
  70213. */
  70214. function Xbox360Pad(id, index, gamepad, xboxOne) {
  70215. if (xboxOne === void 0) { xboxOne = false; }
  70216. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  70217. _this._leftTrigger = 0;
  70218. _this._rightTrigger = 0;
  70219. /** Observable raised when a button is pressed */
  70220. _this.onButtonDownObservable = new BABYLON.Observable();
  70221. /** Observable raised when a button is released */
  70222. _this.onButtonUpObservable = new BABYLON.Observable();
  70223. /** Observable raised when a pad is pressed */
  70224. _this.onPadDownObservable = new BABYLON.Observable();
  70225. /** Observable raised when a pad is released */
  70226. _this.onPadUpObservable = new BABYLON.Observable();
  70227. _this._buttonA = 0;
  70228. _this._buttonB = 0;
  70229. _this._buttonX = 0;
  70230. _this._buttonY = 0;
  70231. _this._buttonBack = 0;
  70232. _this._buttonStart = 0;
  70233. _this._buttonLB = 0;
  70234. _this._buttonRB = 0;
  70235. _this._buttonLeftStick = 0;
  70236. _this._buttonRightStick = 0;
  70237. _this._dPadUp = 0;
  70238. _this._dPadDown = 0;
  70239. _this._dPadLeft = 0;
  70240. _this._dPadRight = 0;
  70241. _this._isXboxOnePad = false;
  70242. _this.type = BABYLON.Gamepad.XBOX;
  70243. _this._isXboxOnePad = xboxOne;
  70244. return _this;
  70245. }
  70246. /**
  70247. * Defines the callback to call when left trigger is pressed
  70248. * @param callback defines the callback to use
  70249. */
  70250. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  70251. this._onlefttriggerchanged = callback;
  70252. };
  70253. /**
  70254. * Defines the callback to call when right trigger is pressed
  70255. * @param callback defines the callback to use
  70256. */
  70257. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  70258. this._onrighttriggerchanged = callback;
  70259. };
  70260. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  70261. /**
  70262. * Gets or sets left trigger value
  70263. */
  70264. get: function () {
  70265. return this._leftTrigger;
  70266. },
  70267. set: function (newValue) {
  70268. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  70269. this._onlefttriggerchanged(newValue);
  70270. }
  70271. this._leftTrigger = newValue;
  70272. },
  70273. enumerable: true,
  70274. configurable: true
  70275. });
  70276. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  70277. /**
  70278. * Gets or sets right trigger value
  70279. */
  70280. get: function () {
  70281. return this._rightTrigger;
  70282. },
  70283. set: function (newValue) {
  70284. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  70285. this._onrighttriggerchanged(newValue);
  70286. }
  70287. this._rightTrigger = newValue;
  70288. },
  70289. enumerable: true,
  70290. configurable: true
  70291. });
  70292. /**
  70293. * Defines the callback to call when a button is pressed
  70294. * @param callback defines the callback to use
  70295. */
  70296. Xbox360Pad.prototype.onbuttondown = function (callback) {
  70297. this._onbuttondown = callback;
  70298. };
  70299. /**
  70300. * Defines the callback to call when a button is released
  70301. * @param callback defines the callback to use
  70302. */
  70303. Xbox360Pad.prototype.onbuttonup = function (callback) {
  70304. this._onbuttonup = callback;
  70305. };
  70306. /**
  70307. * Defines the callback to call when a pad is pressed
  70308. * @param callback defines the callback to use
  70309. */
  70310. Xbox360Pad.prototype.ondpaddown = function (callback) {
  70311. this._ondpaddown = callback;
  70312. };
  70313. /**
  70314. * Defines the callback to call when a pad is released
  70315. * @param callback defines the callback to use
  70316. */
  70317. Xbox360Pad.prototype.ondpadup = function (callback) {
  70318. this._ondpadup = callback;
  70319. };
  70320. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  70321. if (newValue !== currentValue) {
  70322. if (newValue === 1) {
  70323. if (this._onbuttondown) {
  70324. this._onbuttondown(buttonType);
  70325. }
  70326. this.onButtonDownObservable.notifyObservers(buttonType);
  70327. }
  70328. if (newValue === 0) {
  70329. if (this._onbuttonup) {
  70330. this._onbuttonup(buttonType);
  70331. }
  70332. this.onButtonUpObservable.notifyObservers(buttonType);
  70333. }
  70334. }
  70335. return newValue;
  70336. };
  70337. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  70338. if (newValue !== currentValue) {
  70339. if (newValue === 1) {
  70340. if (this._ondpaddown) {
  70341. this._ondpaddown(buttonType);
  70342. }
  70343. this.onPadDownObservable.notifyObservers(buttonType);
  70344. }
  70345. if (newValue === 0) {
  70346. if (this._ondpadup) {
  70347. this._ondpadup(buttonType);
  70348. }
  70349. this.onPadUpObservable.notifyObservers(buttonType);
  70350. }
  70351. }
  70352. return newValue;
  70353. };
  70354. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  70355. /** Gets or sets value of A button */
  70356. get: function () {
  70357. return this._buttonA;
  70358. },
  70359. set: function (value) {
  70360. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  70361. },
  70362. enumerable: true,
  70363. configurable: true
  70364. });
  70365. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  70366. /** Gets or sets value of B button */
  70367. get: function () {
  70368. return this._buttonB;
  70369. },
  70370. set: function (value) {
  70371. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  70372. },
  70373. enumerable: true,
  70374. configurable: true
  70375. });
  70376. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  70377. /** Gets or sets value of X button */
  70378. get: function () {
  70379. return this._buttonX;
  70380. },
  70381. set: function (value) {
  70382. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  70383. },
  70384. enumerable: true,
  70385. configurable: true
  70386. });
  70387. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  70388. /** Gets or sets value of Y button */
  70389. get: function () {
  70390. return this._buttonY;
  70391. },
  70392. set: function (value) {
  70393. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  70394. },
  70395. enumerable: true,
  70396. configurable: true
  70397. });
  70398. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  70399. /** Gets or sets value of Start button */
  70400. get: function () {
  70401. return this._buttonStart;
  70402. },
  70403. set: function (value) {
  70404. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  70405. },
  70406. enumerable: true,
  70407. configurable: true
  70408. });
  70409. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  70410. /** Gets or sets value of Back button */
  70411. get: function () {
  70412. return this._buttonBack;
  70413. },
  70414. set: function (value) {
  70415. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  70416. },
  70417. enumerable: true,
  70418. configurable: true
  70419. });
  70420. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  70421. /** Gets or sets value of Left button */
  70422. get: function () {
  70423. return this._buttonLB;
  70424. },
  70425. set: function (value) {
  70426. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  70427. },
  70428. enumerable: true,
  70429. configurable: true
  70430. });
  70431. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  70432. /** Gets or sets value of Right button */
  70433. get: function () {
  70434. return this._buttonRB;
  70435. },
  70436. set: function (value) {
  70437. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  70438. },
  70439. enumerable: true,
  70440. configurable: true
  70441. });
  70442. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  70443. /** Gets or sets value of left stick */
  70444. get: function () {
  70445. return this._buttonLeftStick;
  70446. },
  70447. set: function (value) {
  70448. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  70449. },
  70450. enumerable: true,
  70451. configurable: true
  70452. });
  70453. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  70454. /** Gets or sets value of right stick */
  70455. get: function () {
  70456. return this._buttonRightStick;
  70457. },
  70458. set: function (value) {
  70459. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  70460. },
  70461. enumerable: true,
  70462. configurable: true
  70463. });
  70464. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  70465. /** Gets or sets value of DPad up */
  70466. get: function () {
  70467. return this._dPadUp;
  70468. },
  70469. set: function (value) {
  70470. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  70471. },
  70472. enumerable: true,
  70473. configurable: true
  70474. });
  70475. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  70476. /** Gets or sets value of DPad down */
  70477. get: function () {
  70478. return this._dPadDown;
  70479. },
  70480. set: function (value) {
  70481. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  70482. },
  70483. enumerable: true,
  70484. configurable: true
  70485. });
  70486. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  70487. /** Gets or sets value of DPad left */
  70488. get: function () {
  70489. return this._dPadLeft;
  70490. },
  70491. set: function (value) {
  70492. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  70493. },
  70494. enumerable: true,
  70495. configurable: true
  70496. });
  70497. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  70498. /** Gets or sets value of DPad right */
  70499. get: function () {
  70500. return this._dPadRight;
  70501. },
  70502. set: function (value) {
  70503. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  70504. },
  70505. enumerable: true,
  70506. configurable: true
  70507. });
  70508. /**
  70509. * Force the gamepad to synchronize with device values
  70510. */
  70511. Xbox360Pad.prototype.update = function () {
  70512. _super.prototype.update.call(this);
  70513. if (this._isXboxOnePad) {
  70514. this.buttonA = this.browserGamepad.buttons[0].value;
  70515. this.buttonB = this.browserGamepad.buttons[1].value;
  70516. this.buttonX = this.browserGamepad.buttons[2].value;
  70517. this.buttonY = this.browserGamepad.buttons[3].value;
  70518. this.buttonLB = this.browserGamepad.buttons[4].value;
  70519. this.buttonRB = this.browserGamepad.buttons[5].value;
  70520. this.leftTrigger = this.browserGamepad.axes[2];
  70521. this.rightTrigger = this.browserGamepad.axes[5];
  70522. this.buttonBack = this.browserGamepad.buttons[9].value;
  70523. this.buttonStart = this.browserGamepad.buttons[8].value;
  70524. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  70525. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  70526. this.dPadUp = this.browserGamepad.buttons[11].value;
  70527. this.dPadDown = this.browserGamepad.buttons[12].value;
  70528. this.dPadLeft = this.browserGamepad.buttons[13].value;
  70529. this.dPadRight = this.browserGamepad.buttons[14].value;
  70530. }
  70531. else {
  70532. this.buttonA = this.browserGamepad.buttons[0].value;
  70533. this.buttonB = this.browserGamepad.buttons[1].value;
  70534. this.buttonX = this.browserGamepad.buttons[2].value;
  70535. this.buttonY = this.browserGamepad.buttons[3].value;
  70536. this.buttonLB = this.browserGamepad.buttons[4].value;
  70537. this.buttonRB = this.browserGamepad.buttons[5].value;
  70538. this.leftTrigger = this.browserGamepad.buttons[6].value;
  70539. this.rightTrigger = this.browserGamepad.buttons[7].value;
  70540. this.buttonBack = this.browserGamepad.buttons[8].value;
  70541. this.buttonStart = this.browserGamepad.buttons[9].value;
  70542. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  70543. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  70544. this.dPadUp = this.browserGamepad.buttons[12].value;
  70545. this.dPadDown = this.browserGamepad.buttons[13].value;
  70546. this.dPadLeft = this.browserGamepad.buttons[14].value;
  70547. this.dPadRight = this.browserGamepad.buttons[15].value;
  70548. }
  70549. };
  70550. Xbox360Pad.prototype.dispose = function () {
  70551. _super.prototype.dispose.call(this);
  70552. this.onButtonDownObservable.clear();
  70553. this.onButtonUpObservable.clear();
  70554. this.onPadDownObservable.clear();
  70555. this.onPadUpObservable.clear();
  70556. };
  70557. return Xbox360Pad;
  70558. }(BABYLON.Gamepad));
  70559. BABYLON.Xbox360Pad = Xbox360Pad;
  70560. })(BABYLON || (BABYLON = {}));
  70561. //# sourceMappingURL=babylon.xboxGamepad.js.map
  70562. var BABYLON;
  70563. (function (BABYLON) {
  70564. /**
  70565. * Defines the types of pose enabled controllers that are supported
  70566. */
  70567. var PoseEnabledControllerType;
  70568. (function (PoseEnabledControllerType) {
  70569. /**
  70570. * HTC Vive
  70571. */
  70572. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  70573. /**
  70574. * Oculus Rift
  70575. */
  70576. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  70577. /**
  70578. * Windows mixed reality
  70579. */
  70580. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  70581. /**
  70582. * Samsung gear VR
  70583. */
  70584. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  70585. /**
  70586. * Google Daydream
  70587. */
  70588. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  70589. /**
  70590. * Generic
  70591. */
  70592. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  70593. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  70594. /**
  70595. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  70596. */
  70597. var PoseEnabledControllerHelper = /** @class */ (function () {
  70598. function PoseEnabledControllerHelper() {
  70599. }
  70600. /**
  70601. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  70602. * @param vrGamepad the gamepad to initialized
  70603. * @returns a vr controller of the type the gamepad identified as
  70604. */
  70605. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  70606. // Oculus Touch
  70607. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  70608. return new BABYLON.OculusTouchController(vrGamepad);
  70609. }
  70610. // Windows Mixed Reality controllers
  70611. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  70612. return new BABYLON.WindowsMotionController(vrGamepad);
  70613. }
  70614. // HTC Vive
  70615. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  70616. return new BABYLON.ViveController(vrGamepad);
  70617. }
  70618. // Samsung/Oculus Gear VR or Oculus Go
  70619. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0 || vrGamepad.id.indexOf('Oculus Go') !== -1) {
  70620. return new BABYLON.GearVRController(vrGamepad);
  70621. }
  70622. // Google Daydream
  70623. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  70624. return new BABYLON.DaydreamController(vrGamepad);
  70625. }
  70626. // Generic
  70627. else {
  70628. return new BABYLON.GenericController(vrGamepad);
  70629. }
  70630. };
  70631. return PoseEnabledControllerHelper;
  70632. }());
  70633. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  70634. /**
  70635. * Defines the PoseEnabledController object that contains state of a vr capable controller
  70636. */
  70637. var PoseEnabledController = /** @class */ (function (_super) {
  70638. __extends(PoseEnabledController, _super);
  70639. /**
  70640. * Creates a new PoseEnabledController from a gamepad
  70641. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  70642. */
  70643. function PoseEnabledController(browserGamepad) {
  70644. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  70645. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  70646. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  70647. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  70648. /**
  70649. * The device position in babylon space
  70650. */
  70651. _this.devicePosition = BABYLON.Vector3.Zero();
  70652. /**
  70653. * The device rotation in babylon space
  70654. */
  70655. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  70656. /**
  70657. * The scale factor of the device in babylon space
  70658. */
  70659. _this.deviceScaleFactor = 1;
  70660. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  70661. /**
  70662. * Internal, matrix used to convert room space to babylon space
  70663. */
  70664. _this._deviceToWorld = BABYLON.Matrix.Identity();
  70665. /**
  70666. * Node to be used when casting a ray from the controller
  70667. */
  70668. _this._pointingPoseNode = null;
  70669. _this._workingMatrix = BABYLON.Matrix.Identity();
  70670. /**
  70671. * @hidden
  70672. */
  70673. _this._meshAttachedObservable = new BABYLON.Observable();
  70674. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  70675. _this.controllerType = PoseEnabledControllerType.GENERIC;
  70676. _this.position = BABYLON.Vector3.Zero();
  70677. _this.rotationQuaternion = new BABYLON.Quaternion();
  70678. _this._calculatedPosition = BABYLON.Vector3.Zero();
  70679. _this._calculatedRotation = new BABYLON.Quaternion();
  70680. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  70681. return _this;
  70682. }
  70683. /**
  70684. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  70685. */
  70686. PoseEnabledController.prototype.update = function () {
  70687. _super.prototype.update.call(this);
  70688. var pose = this.browserGamepad.pose;
  70689. this.updateFromDevice(pose);
  70690. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  70691. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  70692. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  70693. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  70694. if (this._mesh) {
  70695. this._mesh.position.copyFrom(this.devicePosition);
  70696. if (this._mesh.rotationQuaternion) {
  70697. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  70698. }
  70699. }
  70700. };
  70701. /**
  70702. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  70703. * @param poseData raw pose fromthe device
  70704. */
  70705. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  70706. if (poseData) {
  70707. this.rawPose = poseData;
  70708. if (poseData.position) {
  70709. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  70710. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  70711. this._deviceRoomPosition.z *= -1;
  70712. }
  70713. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  70714. this._calculatedPosition.addInPlace(this.position);
  70715. }
  70716. var pose = this.rawPose;
  70717. if (poseData.orientation && pose.orientation) {
  70718. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  70719. if (this._mesh) {
  70720. if (this._mesh.getScene().useRightHandedSystem) {
  70721. this._deviceRoomRotationQuaternion.z *= -1;
  70722. this._deviceRoomRotationQuaternion.w *= -1;
  70723. }
  70724. else {
  70725. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  70726. }
  70727. }
  70728. // if the camera is set, rotate to the camera's rotation
  70729. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  70730. }
  70731. }
  70732. };
  70733. /**
  70734. * Attaches a mesh to the controller
  70735. * @param mesh the mesh to be attached
  70736. */
  70737. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  70738. if (this._mesh) {
  70739. this._mesh.parent = null;
  70740. }
  70741. this._mesh = mesh;
  70742. if (this._poseControlledCamera) {
  70743. this._mesh.parent = this._poseControlledCamera;
  70744. }
  70745. if (!this._mesh.rotationQuaternion) {
  70746. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  70747. }
  70748. this._meshAttachedObservable.notifyObservers(mesh);
  70749. };
  70750. /**
  70751. * Attaches the controllers mesh to a camera
  70752. * @param camera the camera the mesh should be attached to
  70753. */
  70754. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  70755. this._poseControlledCamera = camera;
  70756. if (this._mesh) {
  70757. this._mesh.parent = this._poseControlledCamera;
  70758. }
  70759. };
  70760. /**
  70761. * Disposes of the controller
  70762. */
  70763. PoseEnabledController.prototype.dispose = function () {
  70764. if (this._mesh) {
  70765. this._mesh.dispose();
  70766. }
  70767. this._mesh = null;
  70768. _super.prototype.dispose.call(this);
  70769. };
  70770. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  70771. /**
  70772. * The mesh that is attached to the controller
  70773. */
  70774. get: function () {
  70775. return this._mesh;
  70776. },
  70777. enumerable: true,
  70778. configurable: true
  70779. });
  70780. /**
  70781. * Gets the ray of the controller in the direction the controller is pointing
  70782. * @param length the length the resulting ray should be
  70783. * @returns a ray in the direction the controller is pointing
  70784. */
  70785. PoseEnabledController.prototype.getForwardRay = function (length) {
  70786. if (length === void 0) { length = 100; }
  70787. if (!this.mesh) {
  70788. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  70789. }
  70790. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  70791. var origin = m.getTranslation();
  70792. var forward = new BABYLON.Vector3(0, 0, -1);
  70793. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  70794. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  70795. return new BABYLON.Ray(origin, direction, length);
  70796. };
  70797. /**
  70798. * Name of the child mesh that can be used to cast a ray from the controller
  70799. */
  70800. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  70801. return PoseEnabledController;
  70802. }(BABYLON.Gamepad));
  70803. BABYLON.PoseEnabledController = PoseEnabledController;
  70804. })(BABYLON || (BABYLON = {}));
  70805. //# sourceMappingURL=babylon.poseEnabledController.js.map
  70806. var BABYLON;
  70807. (function (BABYLON) {
  70808. /**
  70809. * Defines the WebVRController object that represents controllers tracked in 3D space
  70810. */
  70811. var WebVRController = /** @class */ (function (_super) {
  70812. __extends(WebVRController, _super);
  70813. /**
  70814. * Creates a new WebVRController from a gamepad
  70815. * @param vrGamepad the gamepad that the WebVRController should be created from
  70816. */
  70817. function WebVRController(vrGamepad) {
  70818. var _this = _super.call(this, vrGamepad) || this;
  70819. // Observables
  70820. /**
  70821. * Fired when the trigger state has changed
  70822. */
  70823. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  70824. /**
  70825. * Fired when the main button state has changed
  70826. */
  70827. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  70828. /**
  70829. * Fired when the secondary button state has changed
  70830. */
  70831. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  70832. /**
  70833. * Fired when the pad state has changed
  70834. */
  70835. _this.onPadStateChangedObservable = new BABYLON.Observable();
  70836. /**
  70837. * Fired when controllers stick values have changed
  70838. */
  70839. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  70840. /**
  70841. * X and Y axis corrisponding to the controllers joystick
  70842. */
  70843. _this.pad = { x: 0, y: 0 };
  70844. // avoid GC, store state in a tmp object
  70845. _this._changes = {
  70846. pressChanged: false,
  70847. touchChanged: false,
  70848. valueChanged: false,
  70849. changed: false
  70850. };
  70851. _this._buttons = new Array(vrGamepad.buttons.length);
  70852. _this.hand = vrGamepad.hand;
  70853. return _this;
  70854. }
  70855. /**
  70856. * Fired when a controller button's state has changed
  70857. * @param callback the callback containing the button that was modified
  70858. */
  70859. WebVRController.prototype.onButtonStateChange = function (callback) {
  70860. this._onButtonStateChange = callback;
  70861. };
  70862. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  70863. /**
  70864. * The default controller model for the controller
  70865. */
  70866. get: function () {
  70867. return this._defaultModel;
  70868. },
  70869. enumerable: true,
  70870. configurable: true
  70871. });
  70872. /**
  70873. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  70874. */
  70875. WebVRController.prototype.update = function () {
  70876. _super.prototype.update.call(this);
  70877. for (var index = 0; index < this._buttons.length; index++) {
  70878. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  70879. }
  70880. ;
  70881. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  70882. this.pad.x = this.leftStick.x;
  70883. this.pad.y = this.leftStick.y;
  70884. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  70885. }
  70886. };
  70887. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  70888. if (!newState) {
  70889. newState = {
  70890. pressed: false,
  70891. touched: false,
  70892. value: 0
  70893. };
  70894. }
  70895. if (!currentState) {
  70896. this._buttons[buttonIndex] = {
  70897. pressed: newState.pressed,
  70898. touched: newState.touched,
  70899. value: newState.value
  70900. };
  70901. return;
  70902. }
  70903. this._checkChanges(newState, currentState);
  70904. if (this._changes.changed) {
  70905. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  70906. this._handleButtonChange(buttonIndex, newState, this._changes);
  70907. }
  70908. this._buttons[buttonIndex].pressed = newState.pressed;
  70909. this._buttons[buttonIndex].touched = newState.touched;
  70910. // oculus triggers are never 0, thou not touched.
  70911. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  70912. };
  70913. WebVRController.prototype._checkChanges = function (newState, currentState) {
  70914. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  70915. this._changes.touchChanged = newState.touched !== currentState.touched;
  70916. this._changes.valueChanged = newState.value !== currentState.value;
  70917. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  70918. return this._changes;
  70919. };
  70920. /**
  70921. * Disposes of th webVRCOntroller
  70922. */
  70923. WebVRController.prototype.dispose = function () {
  70924. _super.prototype.dispose.call(this);
  70925. this.onTriggerStateChangedObservable.clear();
  70926. this.onMainButtonStateChangedObservable.clear();
  70927. this.onSecondaryButtonStateChangedObservable.clear();
  70928. this.onPadStateChangedObservable.clear();
  70929. this.onPadValuesChangedObservable.clear();
  70930. };
  70931. return WebVRController;
  70932. }(BABYLON.PoseEnabledController));
  70933. BABYLON.WebVRController = WebVRController;
  70934. })(BABYLON || (BABYLON = {}));
  70935. //# sourceMappingURL=babylon.webVRController.js.map
  70936. var BABYLON;
  70937. (function (BABYLON) {
  70938. /**
  70939. * Oculus Touch Controller
  70940. */
  70941. var OculusTouchController = /** @class */ (function (_super) {
  70942. __extends(OculusTouchController, _super);
  70943. /**
  70944. * Creates a new OculusTouchController from a gamepad
  70945. * @param vrGamepad the gamepad that the controller should be created from
  70946. */
  70947. function OculusTouchController(vrGamepad) {
  70948. var _this = _super.call(this, vrGamepad) || this;
  70949. /**
  70950. * Fired when the secondary trigger on this controller is modified
  70951. */
  70952. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  70953. /**
  70954. * Fired when the thumb rest on this controller is modified
  70955. */
  70956. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  70957. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  70958. return _this;
  70959. }
  70960. /**
  70961. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  70962. * @param scene scene in which to add meshes
  70963. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  70964. */
  70965. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  70966. var _this = this;
  70967. var meshName;
  70968. // Hand
  70969. if (this.hand === 'left') {
  70970. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  70971. }
  70972. else { // Right is the default if no hand is specified
  70973. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  70974. }
  70975. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  70976. /*
  70977. Parent Mesh name: oculus_touch_left
  70978. - body
  70979. - trigger
  70980. - thumbstick
  70981. - grip
  70982. - button_y
  70983. - button_x
  70984. - button_enter
  70985. */
  70986. _this._defaultModel = newMeshes[1];
  70987. _this.attachToMesh(_this._defaultModel);
  70988. if (meshLoaded) {
  70989. meshLoaded(_this._defaultModel);
  70990. }
  70991. });
  70992. };
  70993. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  70994. /**
  70995. * Fired when the A button on this controller is modified
  70996. */
  70997. get: function () {
  70998. if (this.hand === 'right') {
  70999. return this.onMainButtonStateChangedObservable;
  71000. }
  71001. else {
  71002. throw new Error('No A button on left hand');
  71003. }
  71004. },
  71005. enumerable: true,
  71006. configurable: true
  71007. });
  71008. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  71009. /**
  71010. * Fired when the B button on this controller is modified
  71011. */
  71012. get: function () {
  71013. if (this.hand === 'right') {
  71014. return this.onSecondaryButtonStateChangedObservable;
  71015. }
  71016. else {
  71017. throw new Error('No B button on left hand');
  71018. }
  71019. },
  71020. enumerable: true,
  71021. configurable: true
  71022. });
  71023. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  71024. /**
  71025. * Fired when the X button on this controller is modified
  71026. */
  71027. get: function () {
  71028. if (this.hand === 'left') {
  71029. return this.onMainButtonStateChangedObservable;
  71030. }
  71031. else {
  71032. throw new Error('No X button on right hand');
  71033. }
  71034. },
  71035. enumerable: true,
  71036. configurable: true
  71037. });
  71038. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  71039. /**
  71040. * Fired when the Y button on this controller is modified
  71041. */
  71042. get: function () {
  71043. if (this.hand === 'left') {
  71044. return this.onSecondaryButtonStateChangedObservable;
  71045. }
  71046. else {
  71047. throw new Error('No Y button on right hand');
  71048. }
  71049. },
  71050. enumerable: true,
  71051. configurable: true
  71052. });
  71053. /**
  71054. * Called once for each button that changed state since the last frame
  71055. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  71056. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  71057. * 2) secondary trigger (same)
  71058. * 3) A (right) X (left), touch, pressed = value
  71059. * 4) B / Y
  71060. * 5) thumb rest
  71061. * @param buttonIdx Which button index changed
  71062. * @param state New state of the button
  71063. * @param changes Which properties on the state changed since last frame
  71064. */
  71065. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71066. var notifyObject = state; //{ state: state, changes: changes };
  71067. var triggerDirection = this.hand === 'right' ? -1 : 1;
  71068. switch (buttonIdx) {
  71069. case 0:
  71070. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  71071. return;
  71072. case 1: // index trigger
  71073. if (this._defaultModel) {
  71074. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  71075. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  71076. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  71077. }
  71078. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  71079. return;
  71080. case 2: // secondary trigger
  71081. if (this._defaultModel) {
  71082. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  71083. }
  71084. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  71085. return;
  71086. case 3:
  71087. if (this._defaultModel) {
  71088. if (notifyObject.pressed) {
  71089. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  71090. }
  71091. else {
  71092. (this._defaultModel.getChildren()[1]).position.y = 0;
  71093. }
  71094. }
  71095. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  71096. return;
  71097. case 4:
  71098. if (this._defaultModel) {
  71099. if (notifyObject.pressed) {
  71100. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  71101. }
  71102. else {
  71103. (this._defaultModel.getChildren()[2]).position.y = 0;
  71104. }
  71105. }
  71106. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  71107. return;
  71108. case 5:
  71109. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  71110. return;
  71111. }
  71112. };
  71113. /**
  71114. * Base Url for the controller model.
  71115. */
  71116. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  71117. /**
  71118. * File name for the left controller model.
  71119. */
  71120. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  71121. /**
  71122. * File name for the right controller model.
  71123. */
  71124. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  71125. return OculusTouchController;
  71126. }(BABYLON.WebVRController));
  71127. BABYLON.OculusTouchController = OculusTouchController;
  71128. })(BABYLON || (BABYLON = {}));
  71129. //# sourceMappingURL=babylon.oculusTouchController.js.map
  71130. var BABYLON;
  71131. (function (BABYLON) {
  71132. /**
  71133. * Vive Controller
  71134. */
  71135. var ViveController = /** @class */ (function (_super) {
  71136. __extends(ViveController, _super);
  71137. /**
  71138. * Creates a new ViveController from a gamepad
  71139. * @param vrGamepad the gamepad that the controller should be created from
  71140. */
  71141. function ViveController(vrGamepad) {
  71142. var _this = _super.call(this, vrGamepad) || this;
  71143. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  71144. _this._invertLeftStickY = true;
  71145. return _this;
  71146. }
  71147. /**
  71148. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71149. * @param scene scene in which to add meshes
  71150. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71151. */
  71152. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71153. var _this = this;
  71154. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  71155. /*
  71156. Parent Mesh name: ViveWand
  71157. - body
  71158. - r_gripper
  71159. - l_gripper
  71160. - menu_button
  71161. - system_button
  71162. - trackpad
  71163. - trigger
  71164. - LED
  71165. */
  71166. _this._defaultModel = newMeshes[1];
  71167. _this.attachToMesh(_this._defaultModel);
  71168. if (meshLoaded) {
  71169. meshLoaded(_this._defaultModel);
  71170. }
  71171. });
  71172. };
  71173. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  71174. /**
  71175. * Fired when the left button on this controller is modified
  71176. */
  71177. get: function () {
  71178. return this.onMainButtonStateChangedObservable;
  71179. },
  71180. enumerable: true,
  71181. configurable: true
  71182. });
  71183. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  71184. /**
  71185. * Fired when the right button on this controller is modified
  71186. */
  71187. get: function () {
  71188. return this.onMainButtonStateChangedObservable;
  71189. },
  71190. enumerable: true,
  71191. configurable: true
  71192. });
  71193. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  71194. /**
  71195. * Fired when the menu button on this controller is modified
  71196. */
  71197. get: function () {
  71198. return this.onSecondaryButtonStateChangedObservable;
  71199. },
  71200. enumerable: true,
  71201. configurable: true
  71202. });
  71203. /**
  71204. * Called once for each button that changed state since the last frame
  71205. * Vive mapping:
  71206. * 0: touchpad
  71207. * 1: trigger
  71208. * 2: left AND right buttons
  71209. * 3: menu button
  71210. * @param buttonIdx Which button index changed
  71211. * @param state New state of the button
  71212. * @param changes Which properties on the state changed since last frame
  71213. */
  71214. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71215. var notifyObject = state; //{ state: state, changes: changes };
  71216. switch (buttonIdx) {
  71217. case 0:
  71218. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  71219. return;
  71220. case 1: // index trigger
  71221. if (this._defaultModel) {
  71222. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  71223. }
  71224. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  71225. return;
  71226. case 2: // left AND right button
  71227. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  71228. return;
  71229. case 3:
  71230. if (this._defaultModel) {
  71231. if (notifyObject.pressed) {
  71232. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  71233. }
  71234. else {
  71235. (this._defaultModel.getChildren()[2]).position.y = 0;
  71236. }
  71237. }
  71238. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  71239. return;
  71240. }
  71241. };
  71242. /**
  71243. * Base Url for the controller model.
  71244. */
  71245. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  71246. /**
  71247. * File name for the controller model.
  71248. */
  71249. ViveController.MODEL_FILENAME = 'wand.babylon';
  71250. return ViveController;
  71251. }(BABYLON.WebVRController));
  71252. BABYLON.ViveController = ViveController;
  71253. })(BABYLON || (BABYLON = {}));
  71254. //# sourceMappingURL=babylon.viveController.js.map
  71255. var BABYLON;
  71256. (function (BABYLON) {
  71257. /**
  71258. * Generic Controller
  71259. */
  71260. var GenericController = /** @class */ (function (_super) {
  71261. __extends(GenericController, _super);
  71262. /**
  71263. * Creates a new GenericController from a gamepad
  71264. * @param vrGamepad the gamepad that the controller should be created from
  71265. */
  71266. function GenericController(vrGamepad) {
  71267. return _super.call(this, vrGamepad) || this;
  71268. }
  71269. /**
  71270. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71271. * @param scene scene in which to add meshes
  71272. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71273. */
  71274. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71275. var _this = this;
  71276. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  71277. _this._defaultModel = newMeshes[1];
  71278. _this.attachToMesh(_this._defaultModel);
  71279. if (meshLoaded) {
  71280. meshLoaded(_this._defaultModel);
  71281. }
  71282. });
  71283. };
  71284. /**
  71285. * Called once for each button that changed state since the last frame
  71286. * @param buttonIdx Which button index changed
  71287. * @param state New state of the button
  71288. * @param changes Which properties on the state changed since last frame
  71289. */
  71290. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71291. console.log("Button id: " + buttonIdx + "state: ");
  71292. console.dir(state);
  71293. };
  71294. /**
  71295. * Base Url for the controller model.
  71296. */
  71297. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  71298. /**
  71299. * File name for the controller model.
  71300. */
  71301. GenericController.MODEL_FILENAME = 'generic.babylon';
  71302. return GenericController;
  71303. }(BABYLON.WebVRController));
  71304. BABYLON.GenericController = GenericController;
  71305. })(BABYLON || (BABYLON = {}));
  71306. //# sourceMappingURL=babylon.genericController.js.map
  71307. var BABYLON;
  71308. (function (BABYLON) {
  71309. /**
  71310. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  71311. */
  71312. var LoadedMeshInfo = /** @class */ (function () {
  71313. function LoadedMeshInfo() {
  71314. /**
  71315. * Map of the button meshes contained in the controller
  71316. */
  71317. this.buttonMeshes = {};
  71318. /**
  71319. * Map of the axis meshes contained in the controller
  71320. */
  71321. this.axisMeshes = {};
  71322. }
  71323. return LoadedMeshInfo;
  71324. }());
  71325. /**
  71326. * Defines the WindowsMotionController object that the state of the windows motion controller
  71327. */
  71328. var WindowsMotionController = /** @class */ (function (_super) {
  71329. __extends(WindowsMotionController, _super);
  71330. /**
  71331. * Creates a new WindowsMotionController from a gamepad
  71332. * @param vrGamepad the gamepad that the controller should be created from
  71333. */
  71334. function WindowsMotionController(vrGamepad) {
  71335. var _this = _super.call(this, vrGamepad) || this;
  71336. _this._mapping = {
  71337. // Semantic button names
  71338. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  71339. // A mapping of the button name to glTF model node name
  71340. // that should be transformed by button value.
  71341. buttonMeshNames: {
  71342. 'trigger': 'SELECT',
  71343. 'menu': 'MENU',
  71344. 'grip': 'GRASP',
  71345. 'thumbstick': 'THUMBSTICK_PRESS',
  71346. 'trackpad': 'TOUCHPAD_PRESS'
  71347. },
  71348. // This mapping is used to translate from the Motion Controller to Babylon semantics
  71349. buttonObservableNames: {
  71350. 'trigger': 'onTriggerStateChangedObservable',
  71351. 'menu': 'onSecondaryButtonStateChangedObservable',
  71352. 'grip': 'onMainButtonStateChangedObservable',
  71353. 'thumbstick': 'onPadStateChangedObservable',
  71354. 'trackpad': 'onTrackpadChangedObservable'
  71355. },
  71356. // A mapping of the axis name to glTF model node name
  71357. // that should be transformed by axis value.
  71358. // This array mirrors the browserGamepad.axes array, such that
  71359. // the mesh corresponding to axis 0 is in this array index 0.
  71360. axisMeshNames: [
  71361. 'THUMBSTICK_X',
  71362. 'THUMBSTICK_Y',
  71363. 'TOUCHPAD_TOUCH_X',
  71364. 'TOUCHPAD_TOUCH_Y'
  71365. ],
  71366. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  71367. };
  71368. /**
  71369. * Fired when the trackpad on this controller is clicked
  71370. */
  71371. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  71372. /**
  71373. * Fired when the trackpad on this controller is modified
  71374. */
  71375. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  71376. /**
  71377. * The current x and y values of this controller's trackpad
  71378. */
  71379. _this.trackpad = { x: 0, y: 0 };
  71380. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  71381. _this._loadedMeshInfo = null;
  71382. return _this;
  71383. }
  71384. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  71385. /**
  71386. * Fired when the trigger on this controller is modified
  71387. */
  71388. get: function () {
  71389. return this.onTriggerStateChangedObservable;
  71390. },
  71391. enumerable: true,
  71392. configurable: true
  71393. });
  71394. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  71395. /**
  71396. * Fired when the menu button on this controller is modified
  71397. */
  71398. get: function () {
  71399. return this.onSecondaryButtonStateChangedObservable;
  71400. },
  71401. enumerable: true,
  71402. configurable: true
  71403. });
  71404. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  71405. /**
  71406. * Fired when the grip button on this controller is modified
  71407. */
  71408. get: function () {
  71409. return this.onMainButtonStateChangedObservable;
  71410. },
  71411. enumerable: true,
  71412. configurable: true
  71413. });
  71414. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  71415. /**
  71416. * Fired when the thumbstick button on this controller is modified
  71417. */
  71418. get: function () {
  71419. return this.onPadStateChangedObservable;
  71420. },
  71421. enumerable: true,
  71422. configurable: true
  71423. });
  71424. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  71425. /**
  71426. * Fired when the touchpad button on this controller is modified
  71427. */
  71428. get: function () {
  71429. return this.onTrackpadChangedObservable;
  71430. },
  71431. enumerable: true,
  71432. configurable: true
  71433. });
  71434. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  71435. /**
  71436. * Fired when the touchpad values on this controller are modified
  71437. */
  71438. get: function () {
  71439. return this.onTrackpadValuesChangedObservable;
  71440. },
  71441. enumerable: true,
  71442. configurable: true
  71443. });
  71444. WindowsMotionController.prototype._updateTrackpad = function () {
  71445. if (this.browserGamepad.axes && (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y)) {
  71446. this.trackpad.x = this.browserGamepad["axes"][2];
  71447. this.trackpad.y = this.browserGamepad["axes"][3];
  71448. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  71449. }
  71450. };
  71451. /**
  71452. * Called once per frame by the engine.
  71453. */
  71454. WindowsMotionController.prototype.update = function () {
  71455. _super.prototype.update.call(this);
  71456. if (this.browserGamepad.axes) {
  71457. this._updateTrackpad();
  71458. // Only need to animate axes if there is a loaded mesh
  71459. if (this._loadedMeshInfo) {
  71460. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  71461. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  71462. }
  71463. }
  71464. }
  71465. };
  71466. /**
  71467. * Called once for each button that changed state since the last frame
  71468. * @param buttonIdx Which button index changed
  71469. * @param state New state of the button
  71470. * @param changes Which properties on the state changed since last frame
  71471. */
  71472. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71473. var buttonName = this._mapping.buttons[buttonIdx];
  71474. if (!buttonName) {
  71475. return;
  71476. }
  71477. // Update the trackpad to ensure trackpad.x/y are accurate during button events between frames
  71478. this._updateTrackpad();
  71479. // Only emit events for buttons that we know how to map from index to name
  71480. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  71481. if (observable) {
  71482. observable.notifyObservers(state);
  71483. }
  71484. this._lerpButtonTransform(buttonName, state.value);
  71485. };
  71486. /**
  71487. * Moves the buttons on the controller mesh based on their current state
  71488. * @param buttonName the name of the button to move
  71489. * @param buttonValue the value of the button which determines the buttons new position
  71490. */
  71491. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  71492. // If there is no loaded mesh, there is nothing to transform.
  71493. if (!this._loadedMeshInfo) {
  71494. return;
  71495. }
  71496. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  71497. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  71498. return;
  71499. }
  71500. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  71501. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  71502. };
  71503. /**
  71504. * Moves the axis on the controller mesh based on its current state
  71505. * @param axis the index of the axis
  71506. * @param axisValue the value of the axis which determines the meshes new position
  71507. * @hidden
  71508. */
  71509. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  71510. if (!this._loadedMeshInfo) {
  71511. return;
  71512. }
  71513. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  71514. if (!meshInfo) {
  71515. return;
  71516. }
  71517. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  71518. return;
  71519. }
  71520. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  71521. var lerpValue = axisValue * 0.5 + 0.5;
  71522. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  71523. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  71524. };
  71525. /**
  71526. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71527. * @param scene scene in which to add meshes
  71528. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71529. */
  71530. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  71531. var _this = this;
  71532. if (forceDefault === void 0) { forceDefault = false; }
  71533. var path;
  71534. var filename;
  71535. // Checking if GLB loader is present
  71536. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  71537. // Determine the device specific folder based on the ID suffix
  71538. var device = 'default';
  71539. if (this.id && !forceDefault) {
  71540. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  71541. device = ((match && match[0]) || device);
  71542. }
  71543. // Hand
  71544. if (this.hand === 'left') {
  71545. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  71546. }
  71547. else { // Right is the default if no hand is specified
  71548. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  71549. }
  71550. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  71551. }
  71552. else {
  71553. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  71554. path = BABYLON.GenericController.MODEL_BASE_URL;
  71555. filename = BABYLON.GenericController.MODEL_FILENAME;
  71556. }
  71557. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  71558. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  71559. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  71560. if (!_this._loadedMeshInfo) {
  71561. return;
  71562. }
  71563. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  71564. _this.attachToMesh(_this._defaultModel);
  71565. if (meshLoaded) {
  71566. meshLoaded(_this._defaultModel);
  71567. }
  71568. }, null, function (scene, message) {
  71569. BABYLON.Tools.Log(message);
  71570. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  71571. if (!forceDefault) {
  71572. _this.initControllerMesh(scene, meshLoaded, true);
  71573. }
  71574. });
  71575. };
  71576. /**
  71577. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  71578. * can be transformed by button presses and axes values, based on this._mapping.
  71579. *
  71580. * @param scene scene in which the meshes exist
  71581. * @param meshes list of meshes that make up the controller model to process
  71582. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  71583. */
  71584. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  71585. var loadedMeshInfo = null;
  71586. // Create a new mesh to contain the glTF hierarchy
  71587. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  71588. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  71589. var childMesh = null;
  71590. for (var i = 0; i < meshes.length; i++) {
  71591. var mesh = meshes[i];
  71592. if (!mesh.parent) {
  71593. // Exclude controller meshes from picking results
  71594. mesh.isPickable = false;
  71595. // Handle root node, attach to the new parentMesh
  71596. childMesh = mesh;
  71597. break;
  71598. }
  71599. }
  71600. if (childMesh) {
  71601. childMesh.setParent(parentMesh);
  71602. // Create our mesh info. Note that this method will always return non-null.
  71603. loadedMeshInfo = this.createMeshInfo(parentMesh);
  71604. }
  71605. else {
  71606. BABYLON.Tools.Warn('Could not find root node in model file.');
  71607. }
  71608. return loadedMeshInfo;
  71609. };
  71610. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  71611. var loadedMeshInfo = new LoadedMeshInfo();
  71612. var i;
  71613. loadedMeshInfo.rootNode = rootNode;
  71614. // Reset the caches
  71615. loadedMeshInfo.buttonMeshes = {};
  71616. loadedMeshInfo.axisMeshes = {};
  71617. // Button Meshes
  71618. for (i = 0; i < this._mapping.buttons.length; i++) {
  71619. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  71620. if (!buttonMeshName) {
  71621. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  71622. continue;
  71623. }
  71624. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  71625. if (!buttonMesh) {
  71626. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  71627. continue;
  71628. }
  71629. var buttonMeshInfo = {
  71630. index: i,
  71631. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  71632. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  71633. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  71634. };
  71635. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  71636. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  71637. }
  71638. else {
  71639. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  71640. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  71641. '(VALUE: ' + !!buttonMeshInfo.value +
  71642. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  71643. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  71644. ')');
  71645. }
  71646. }
  71647. // Axis Meshes
  71648. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  71649. var axisMeshName = this._mapping.axisMeshNames[i];
  71650. if (!axisMeshName) {
  71651. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  71652. continue;
  71653. }
  71654. var axisMesh = getChildByName(rootNode, axisMeshName);
  71655. if (!axisMesh) {
  71656. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  71657. continue;
  71658. }
  71659. var axisMeshInfo = {
  71660. index: i,
  71661. value: getImmediateChildByName(axisMesh, 'VALUE'),
  71662. min: getImmediateChildByName(axisMesh, 'MIN'),
  71663. max: getImmediateChildByName(axisMesh, 'MAX')
  71664. };
  71665. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  71666. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  71667. }
  71668. else {
  71669. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  71670. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  71671. '(VALUE: ' + !!axisMeshInfo.value +
  71672. ', MIN: ' + !!axisMeshInfo.min +
  71673. ', MAX:' + !!axisMeshInfo.max +
  71674. ')');
  71675. }
  71676. }
  71677. // Pointing Ray
  71678. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  71679. if (!loadedMeshInfo.pointingPoseNode) {
  71680. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  71681. }
  71682. return loadedMeshInfo;
  71683. // Look through all children recursively. This will return null if no mesh exists with the given name.
  71684. function getChildByName(node, name) {
  71685. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  71686. }
  71687. // Look through only immediate children. This will return null if no mesh exists with the given name.
  71688. function getImmediateChildByName(node, name) {
  71689. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  71690. }
  71691. };
  71692. /**
  71693. * Gets the ray of the controller in the direction the controller is pointing
  71694. * @param length the length the resulting ray should be
  71695. * @returns a ray in the direction the controller is pointing
  71696. */
  71697. WindowsMotionController.prototype.getForwardRay = function (length) {
  71698. if (length === void 0) { length = 100; }
  71699. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  71700. return _super.prototype.getForwardRay.call(this, length);
  71701. }
  71702. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  71703. var origin = m.getTranslation();
  71704. var forward = new BABYLON.Vector3(0, 0, -1);
  71705. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  71706. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  71707. return new BABYLON.Ray(origin, direction, length);
  71708. };
  71709. /**
  71710. * Disposes of the controller
  71711. */
  71712. WindowsMotionController.prototype.dispose = function () {
  71713. _super.prototype.dispose.call(this);
  71714. this.onTrackpadChangedObservable.clear();
  71715. };
  71716. /**
  71717. * The base url used to load the left and right controller models
  71718. */
  71719. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  71720. /**
  71721. * The name of the left controller model file
  71722. */
  71723. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  71724. /**
  71725. * The name of the right controller model file
  71726. */
  71727. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  71728. /**
  71729. * The controller name prefix for this controller type
  71730. */
  71731. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  71732. /**
  71733. * The controller id pattern for this controller type
  71734. */
  71735. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  71736. return WindowsMotionController;
  71737. }(BABYLON.WebVRController));
  71738. BABYLON.WindowsMotionController = WindowsMotionController;
  71739. })(BABYLON || (BABYLON = {}));
  71740. //# sourceMappingURL=babylon.windowsMotionController.js.map
  71741. var BABYLON;
  71742. (function (BABYLON) {
  71743. /**
  71744. * Gear VR Controller
  71745. */
  71746. var GearVRController = /** @class */ (function (_super) {
  71747. __extends(GearVRController, _super);
  71748. /**
  71749. * Creates a new GearVRController from a gamepad
  71750. * @param vrGamepad the gamepad that the controller should be created from
  71751. */
  71752. function GearVRController(vrGamepad) {
  71753. var _this = _super.call(this, vrGamepad) || this;
  71754. _this._buttonIndexToObservableNameMap = [
  71755. 'onTrackpadChangedObservable',
  71756. 'onTriggerStateChangedObservable' // Trigger
  71757. ];
  71758. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  71759. // Initial starting position defaults to where hand would be (incase of only 3dof controller)
  71760. _this._calculatedPosition = new BABYLON.Vector3(_this.hand == "left" ? -0.15 : 0.15, -0.5, 0.4);
  71761. return _this;
  71762. }
  71763. /**
  71764. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71765. * @param scene scene in which to add meshes
  71766. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71767. */
  71768. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71769. var _this = this;
  71770. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  71771. _this._defaultModel = newMeshes[1];
  71772. _this.attachToMesh(_this._defaultModel);
  71773. if (meshLoaded) {
  71774. meshLoaded(_this._defaultModel);
  71775. }
  71776. });
  71777. };
  71778. /**
  71779. * Called once for each button that changed state since the last frame
  71780. * @param buttonIdx Which button index changed
  71781. * @param state New state of the button
  71782. * @param changes Which properties on the state changed since last frame
  71783. */
  71784. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71785. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  71786. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  71787. // Only emit events for buttons that we know how to map from index to observable
  71788. var observable = this[observableName];
  71789. if (observable) {
  71790. observable.notifyObservers(state);
  71791. }
  71792. }
  71793. };
  71794. /**
  71795. * Base Url for the controller model.
  71796. */
  71797. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  71798. /**
  71799. * File name for the controller model.
  71800. */
  71801. GearVRController.MODEL_FILENAME = 'generic.babylon';
  71802. /**
  71803. * Gamepad Id prefix used to identify this controller.
  71804. */
  71805. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  71806. return GearVRController;
  71807. }(BABYLON.WebVRController));
  71808. BABYLON.GearVRController = GearVRController;
  71809. })(BABYLON || (BABYLON = {}));
  71810. //# sourceMappingURL=babylon.gearVRController.js.map
  71811. var BABYLON;
  71812. (function (BABYLON) {
  71813. /**
  71814. * Google Daydream controller
  71815. */
  71816. var DaydreamController = /** @class */ (function (_super) {
  71817. __extends(DaydreamController, _super);
  71818. /**
  71819. * Creates a new DaydreamController from a gamepad
  71820. * @param vrGamepad the gamepad that the controller should be created from
  71821. */
  71822. function DaydreamController(vrGamepad) {
  71823. var _this = _super.call(this, vrGamepad) || this;
  71824. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  71825. return _this;
  71826. }
  71827. /**
  71828. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71829. * @param scene scene in which to add meshes
  71830. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71831. */
  71832. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71833. var _this = this;
  71834. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  71835. _this._defaultModel = newMeshes[1];
  71836. _this.attachToMesh(_this._defaultModel);
  71837. if (meshLoaded) {
  71838. meshLoaded(_this._defaultModel);
  71839. }
  71840. });
  71841. };
  71842. /**
  71843. * Called once for each button that changed state since the last frame
  71844. * @param buttonIdx Which button index changed
  71845. * @param state New state of the button
  71846. * @param changes Which properties on the state changed since last frame
  71847. */
  71848. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71849. // Daydream controller only has 1 GamepadButton (on the trackpad).
  71850. if (buttonIdx === 0) {
  71851. var observable = this.onTriggerStateChangedObservable;
  71852. if (observable) {
  71853. observable.notifyObservers(state);
  71854. }
  71855. }
  71856. else {
  71857. // If the app or home buttons are ever made available
  71858. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  71859. }
  71860. };
  71861. /**
  71862. * Base Url for the controller model.
  71863. */
  71864. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  71865. /**
  71866. * File name for the controller model.
  71867. */
  71868. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  71869. /**
  71870. * Gamepad Id prefix used to identify Daydream Controller.
  71871. */
  71872. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  71873. return DaydreamController;
  71874. }(BABYLON.WebVRController));
  71875. BABYLON.DaydreamController = DaydreamController;
  71876. })(BABYLON || (BABYLON = {}));
  71877. //# sourceMappingURL=babylon.daydreamController.js.map
  71878. var BABYLON;
  71879. (function (BABYLON) {
  71880. var FollowCamera = /** @class */ (function (_super) {
  71881. __extends(FollowCamera, _super);
  71882. function FollowCamera(name, position, scene, lockedTarget) {
  71883. if (lockedTarget === void 0) { lockedTarget = null; }
  71884. var _this = _super.call(this, name, position, scene) || this;
  71885. _this.radius = 12;
  71886. _this.rotationOffset = 0;
  71887. _this.heightOffset = 4;
  71888. _this.cameraAcceleration = 0.05;
  71889. _this.maxCameraSpeed = 20;
  71890. _this.lockedTarget = lockedTarget;
  71891. return _this;
  71892. }
  71893. FollowCamera.prototype.getRadians = function (degrees) {
  71894. return degrees * Math.PI / 180;
  71895. };
  71896. FollowCamera.prototype.follow = function (cameraTarget) {
  71897. if (!cameraTarget)
  71898. return;
  71899. var yRotation;
  71900. if (cameraTarget.rotationQuaternion) {
  71901. var rotMatrix = new BABYLON.Matrix();
  71902. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  71903. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  71904. }
  71905. else {
  71906. yRotation = cameraTarget.rotation.y;
  71907. }
  71908. var radians = this.getRadians(this.rotationOffset) + yRotation;
  71909. var targetPosition = cameraTarget.getAbsolutePosition();
  71910. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  71911. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  71912. var dx = targetX - this.position.x;
  71913. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  71914. var dz = (targetZ) - this.position.z;
  71915. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  71916. var vy = dy * this.cameraAcceleration;
  71917. var vz = dz * this.cameraAcceleration * 2;
  71918. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  71919. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  71920. }
  71921. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  71922. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  71923. }
  71924. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  71925. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  71926. }
  71927. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  71928. this.setTarget(targetPosition);
  71929. };
  71930. FollowCamera.prototype._checkInputs = function () {
  71931. _super.prototype._checkInputs.call(this);
  71932. if (this.lockedTarget) {
  71933. this.follow(this.lockedTarget);
  71934. }
  71935. };
  71936. FollowCamera.prototype.getClassName = function () {
  71937. return "FollowCamera";
  71938. };
  71939. __decorate([
  71940. BABYLON.serialize()
  71941. ], FollowCamera.prototype, "radius", void 0);
  71942. __decorate([
  71943. BABYLON.serialize()
  71944. ], FollowCamera.prototype, "rotationOffset", void 0);
  71945. __decorate([
  71946. BABYLON.serialize()
  71947. ], FollowCamera.prototype, "heightOffset", void 0);
  71948. __decorate([
  71949. BABYLON.serialize()
  71950. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  71951. __decorate([
  71952. BABYLON.serialize()
  71953. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  71954. __decorate([
  71955. BABYLON.serializeAsMeshReference("lockedTargetId")
  71956. ], FollowCamera.prototype, "lockedTarget", void 0);
  71957. return FollowCamera;
  71958. }(BABYLON.TargetCamera));
  71959. BABYLON.FollowCamera = FollowCamera;
  71960. var ArcFollowCamera = /** @class */ (function (_super) {
  71961. __extends(ArcFollowCamera, _super);
  71962. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  71963. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  71964. _this.alpha = alpha;
  71965. _this.beta = beta;
  71966. _this.radius = radius;
  71967. _this.target = target;
  71968. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  71969. _this.follow();
  71970. return _this;
  71971. }
  71972. ArcFollowCamera.prototype.follow = function () {
  71973. if (!this.target) {
  71974. return;
  71975. }
  71976. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  71977. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  71978. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  71979. var targetPosition = this.target.getAbsolutePosition();
  71980. this.position = targetPosition.add(this._cartesianCoordinates);
  71981. this.setTarget(targetPosition);
  71982. };
  71983. ArcFollowCamera.prototype._checkInputs = function () {
  71984. _super.prototype._checkInputs.call(this);
  71985. this.follow();
  71986. };
  71987. ArcFollowCamera.prototype.getClassName = function () {
  71988. return "ArcFollowCamera";
  71989. };
  71990. return ArcFollowCamera;
  71991. }(BABYLON.TargetCamera));
  71992. BABYLON.ArcFollowCamera = ArcFollowCamera;
  71993. })(BABYLON || (BABYLON = {}));
  71994. //# sourceMappingURL=babylon.followCamera.js.map
  71995. var BABYLON;
  71996. (function (BABYLON) {
  71997. // We're mainly based on the logic defined into the FreeCamera code
  71998. var UniversalCamera = /** @class */ (function (_super) {
  71999. __extends(UniversalCamera, _super);
  72000. //-- end properties for backward compatibility for inputs
  72001. function UniversalCamera(name, position, scene) {
  72002. var _this = _super.call(this, name, position, scene) || this;
  72003. _this.inputs.addGamepad();
  72004. return _this;
  72005. }
  72006. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  72007. //-- Begin properties for backward compatibility for inputs
  72008. get: function () {
  72009. var gamepad = this.inputs.attached["gamepad"];
  72010. if (gamepad)
  72011. return gamepad.gamepadAngularSensibility;
  72012. return 0;
  72013. },
  72014. set: function (value) {
  72015. var gamepad = this.inputs.attached["gamepad"];
  72016. if (gamepad)
  72017. gamepad.gamepadAngularSensibility = value;
  72018. },
  72019. enumerable: true,
  72020. configurable: true
  72021. });
  72022. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  72023. get: function () {
  72024. var gamepad = this.inputs.attached["gamepad"];
  72025. if (gamepad)
  72026. return gamepad.gamepadMoveSensibility;
  72027. return 0;
  72028. },
  72029. set: function (value) {
  72030. var gamepad = this.inputs.attached["gamepad"];
  72031. if (gamepad)
  72032. gamepad.gamepadMoveSensibility = value;
  72033. },
  72034. enumerable: true,
  72035. configurable: true
  72036. });
  72037. UniversalCamera.prototype.getClassName = function () {
  72038. return "UniversalCamera";
  72039. };
  72040. return UniversalCamera;
  72041. }(BABYLON.TouchCamera));
  72042. BABYLON.UniversalCamera = UniversalCamera;
  72043. })(BABYLON || (BABYLON = {}));
  72044. //# sourceMappingURL=babylon.universalCamera.js.map
  72045. var BABYLON;
  72046. (function (BABYLON) {
  72047. // We're mainly based on the logic defined into the FreeCamera code
  72048. var GamepadCamera = /** @class */ (function (_super) {
  72049. __extends(GamepadCamera, _super);
  72050. //-- end properties for backward compatibility for inputs
  72051. function GamepadCamera(name, position, scene) {
  72052. return _super.call(this, name, position, scene) || this;
  72053. }
  72054. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  72055. //-- Begin properties for backward compatibility for inputs
  72056. get: function () {
  72057. var gamepad = this.inputs.attached["gamepad"];
  72058. if (gamepad)
  72059. return gamepad.gamepadAngularSensibility;
  72060. return 0;
  72061. },
  72062. set: function (value) {
  72063. var gamepad = this.inputs.attached["gamepad"];
  72064. if (gamepad)
  72065. gamepad.gamepadAngularSensibility = value;
  72066. },
  72067. enumerable: true,
  72068. configurable: true
  72069. });
  72070. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  72071. get: function () {
  72072. var gamepad = this.inputs.attached["gamepad"];
  72073. if (gamepad)
  72074. return gamepad.gamepadMoveSensibility;
  72075. return 0;
  72076. },
  72077. set: function (value) {
  72078. var gamepad = this.inputs.attached["gamepad"];
  72079. if (gamepad)
  72080. gamepad.gamepadMoveSensibility = value;
  72081. },
  72082. enumerable: true,
  72083. configurable: true
  72084. });
  72085. GamepadCamera.prototype.getClassName = function () {
  72086. return "GamepadCamera";
  72087. };
  72088. return GamepadCamera;
  72089. }(BABYLON.UniversalCamera));
  72090. BABYLON.GamepadCamera = GamepadCamera;
  72091. })(BABYLON || (BABYLON = {}));
  72092. //# sourceMappingURL=babylon.gamepadCamera.js.map
  72093. var BABYLON;
  72094. (function (BABYLON) {
  72095. var PostProcessRenderPipelineManager = /** @class */ (function () {
  72096. function PostProcessRenderPipelineManager() {
  72097. this._renderPipelines = {};
  72098. }
  72099. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  72100. this._renderPipelines[renderPipeline._name] = renderPipeline;
  72101. };
  72102. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  72103. if (unique === void 0) { unique = false; }
  72104. var renderPipeline = this._renderPipelines[renderPipelineName];
  72105. if (!renderPipeline) {
  72106. return;
  72107. }
  72108. renderPipeline._attachCameras(cameras, unique);
  72109. };
  72110. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  72111. var renderPipeline = this._renderPipelines[renderPipelineName];
  72112. if (!renderPipeline) {
  72113. return;
  72114. }
  72115. renderPipeline._detachCameras(cameras);
  72116. };
  72117. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  72118. var renderPipeline = this._renderPipelines[renderPipelineName];
  72119. if (!renderPipeline) {
  72120. return;
  72121. }
  72122. renderPipeline._enableEffect(renderEffectName, cameras);
  72123. };
  72124. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  72125. var renderPipeline = this._renderPipelines[renderPipelineName];
  72126. if (!renderPipeline) {
  72127. return;
  72128. }
  72129. renderPipeline._disableEffect(renderEffectName, cameras);
  72130. };
  72131. PostProcessRenderPipelineManager.prototype.update = function () {
  72132. for (var renderPipelineName in this._renderPipelines) {
  72133. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  72134. var pipeline = this._renderPipelines[renderPipelineName];
  72135. if (!pipeline.isSupported) {
  72136. pipeline.dispose();
  72137. delete this._renderPipelines[renderPipelineName];
  72138. }
  72139. else {
  72140. pipeline._update();
  72141. }
  72142. }
  72143. }
  72144. };
  72145. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  72146. for (var renderPipelineName in this._renderPipelines) {
  72147. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  72148. var pipeline = this._renderPipelines[renderPipelineName];
  72149. pipeline._rebuild();
  72150. }
  72151. }
  72152. };
  72153. PostProcessRenderPipelineManager.prototype.dispose = function () {
  72154. for (var renderPipelineName in this._renderPipelines) {
  72155. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  72156. var pipeline = this._renderPipelines[renderPipelineName];
  72157. pipeline.dispose();
  72158. }
  72159. }
  72160. };
  72161. return PostProcessRenderPipelineManager;
  72162. }());
  72163. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  72164. })(BABYLON || (BABYLON = {}));
  72165. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  72166. var BABYLON;
  72167. (function (BABYLON) {
  72168. /**
  72169. * This represents a set of one or more post processes in Babylon.
  72170. * A post process can be used to apply a shader to a texture after it is rendered.
  72171. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  72172. */
  72173. var PostProcessRenderEffect = /** @class */ (function () {
  72174. /**
  72175. * Instantiates a post process render effect.
  72176. * A post process can be used to apply a shader to a texture after it is rendered.
  72177. * @param engine The engine the effect is tied to
  72178. * @param name The name of the effect
  72179. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  72180. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  72181. */
  72182. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  72183. this._name = name;
  72184. this._singleInstance = singleInstance || true;
  72185. this._getPostProcesses = getPostProcesses;
  72186. this._cameras = {};
  72187. this._indicesForCamera = {};
  72188. this._postProcesses = {};
  72189. }
  72190. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  72191. /**
  72192. * Checks if all the post processes in the effect are supported.
  72193. */
  72194. get: function () {
  72195. for (var index in this._postProcesses) {
  72196. if (this._postProcesses.hasOwnProperty(index)) {
  72197. var pps = this._postProcesses[index];
  72198. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  72199. if (!pps[ppIndex].isSupported) {
  72200. return false;
  72201. }
  72202. }
  72203. }
  72204. }
  72205. return true;
  72206. },
  72207. enumerable: true,
  72208. configurable: true
  72209. });
  72210. /**
  72211. * Updates the current state of the effect
  72212. */
  72213. PostProcessRenderEffect.prototype._update = function () {
  72214. };
  72215. /**
  72216. * Attaches the effect on cameras
  72217. * @param cameras The camera to attach to.
  72218. */
  72219. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  72220. var _this = this;
  72221. var cameraKey;
  72222. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72223. if (!cams) {
  72224. return;
  72225. }
  72226. for (var i = 0; i < cams.length; i++) {
  72227. var camera = cams[i];
  72228. var cameraName = camera.name;
  72229. if (this._singleInstance) {
  72230. cameraKey = 0;
  72231. }
  72232. else {
  72233. cameraKey = cameraName;
  72234. }
  72235. if (!this._postProcesses[cameraKey]) {
  72236. var postProcess = this._getPostProcesses();
  72237. if (postProcess) {
  72238. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  72239. }
  72240. }
  72241. if (!this._indicesForCamera[cameraName]) {
  72242. this._indicesForCamera[cameraName] = [];
  72243. }
  72244. this._postProcesses[cameraKey].forEach(function (postProcess) {
  72245. var index = camera.attachPostProcess(postProcess);
  72246. _this._indicesForCamera[cameraName].push(index);
  72247. });
  72248. if (!this._cameras[cameraName]) {
  72249. this._cameras[cameraName] = camera;
  72250. }
  72251. }
  72252. };
  72253. /**
  72254. * Detatches the effect on cameras
  72255. * @param cameras The camera to detatch from.
  72256. */
  72257. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  72258. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72259. if (!cams) {
  72260. return;
  72261. }
  72262. for (var i = 0; i < cams.length; i++) {
  72263. var camera = cams[i];
  72264. var cameraName = camera.name;
  72265. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  72266. camera.detachPostProcess(postProcess);
  72267. });
  72268. if (this._cameras[cameraName]) {
  72269. //this._indicesForCamera.splice(index, 1);
  72270. this._cameras[cameraName] = null;
  72271. }
  72272. }
  72273. };
  72274. /**
  72275. * Enables the effect on given cameras
  72276. * @param cameras The camera to enable.
  72277. */
  72278. PostProcessRenderEffect.prototype._enable = function (cameras) {
  72279. var _this = this;
  72280. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72281. if (!cams) {
  72282. return;
  72283. }
  72284. for (var i = 0; i < cams.length; i++) {
  72285. var camera = cams[i];
  72286. var cameraName = camera.name;
  72287. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  72288. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  72289. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  72290. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  72291. });
  72292. }
  72293. }
  72294. }
  72295. };
  72296. /**
  72297. * Disables the effect on the given cameras
  72298. * @param cameras The camera to disable.
  72299. */
  72300. PostProcessRenderEffect.prototype._disable = function (cameras) {
  72301. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72302. if (!cams) {
  72303. return;
  72304. }
  72305. for (var i = 0; i < cams.length; i++) {
  72306. var camera = cams[i];
  72307. var cameraName = camera.name;
  72308. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  72309. camera.detachPostProcess(postProcess);
  72310. });
  72311. }
  72312. };
  72313. /**
  72314. * Gets a list of the post processes contained in the effect.
  72315. * @param camera The camera to get the post processes on.
  72316. * @returns The list of the post processes in the effect.
  72317. */
  72318. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  72319. if (this._singleInstance) {
  72320. return this._postProcesses[0];
  72321. }
  72322. else {
  72323. if (!camera) {
  72324. return null;
  72325. }
  72326. return this._postProcesses[camera.name];
  72327. }
  72328. };
  72329. return PostProcessRenderEffect;
  72330. }());
  72331. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  72332. })(BABYLON || (BABYLON = {}));
  72333. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  72334. var BABYLON;
  72335. (function (BABYLON) {
  72336. var PostProcessRenderPipeline = /** @class */ (function () {
  72337. function PostProcessRenderPipeline(engine, name) {
  72338. this.engine = engine;
  72339. this._name = name;
  72340. this._renderEffects = {};
  72341. this._renderEffectsForIsolatedPass = new Array();
  72342. this._cameras = [];
  72343. }
  72344. PostProcessRenderPipeline.prototype.getClassName = function () {
  72345. return "PostProcessRenderPipeline";
  72346. };
  72347. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  72348. get: function () {
  72349. for (var renderEffectName in this._renderEffects) {
  72350. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  72351. if (!this._renderEffects[renderEffectName].isSupported) {
  72352. return false;
  72353. }
  72354. }
  72355. }
  72356. return true;
  72357. },
  72358. enumerable: true,
  72359. configurable: true
  72360. });
  72361. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  72362. this._renderEffects[renderEffect._name] = renderEffect;
  72363. };
  72364. // private
  72365. PostProcessRenderPipeline.prototype._rebuild = function () {
  72366. };
  72367. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  72368. var renderEffects = this._renderEffects[renderEffectName];
  72369. if (!renderEffects) {
  72370. return;
  72371. }
  72372. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  72373. };
  72374. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  72375. var renderEffects = this._renderEffects[renderEffectName];
  72376. if (!renderEffects) {
  72377. return;
  72378. }
  72379. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  72380. };
  72381. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  72382. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72383. if (!cams) {
  72384. return;
  72385. }
  72386. var indicesToDelete = [];
  72387. var i;
  72388. for (i = 0; i < cams.length; i++) {
  72389. var camera = cams[i];
  72390. var cameraName = camera.name;
  72391. if (this._cameras.indexOf(camera) === -1) {
  72392. this._cameras[cameraName] = camera;
  72393. }
  72394. else if (unique) {
  72395. indicesToDelete.push(i);
  72396. }
  72397. }
  72398. for (i = 0; i < indicesToDelete.length; i++) {
  72399. cameras.splice(indicesToDelete[i], 1);
  72400. }
  72401. for (var renderEffectName in this._renderEffects) {
  72402. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  72403. this._renderEffects[renderEffectName]._attachCameras(cams);
  72404. }
  72405. }
  72406. };
  72407. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  72408. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72409. if (!cams) {
  72410. return;
  72411. }
  72412. for (var renderEffectName in this._renderEffects) {
  72413. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  72414. this._renderEffects[renderEffectName]._detachCameras(cams);
  72415. }
  72416. }
  72417. for (var i = 0; i < cams.length; i++) {
  72418. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  72419. }
  72420. };
  72421. PostProcessRenderPipeline.prototype._update = function () {
  72422. for (var renderEffectName in this._renderEffects) {
  72423. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  72424. this._renderEffects[renderEffectName]._update();
  72425. }
  72426. }
  72427. for (var i = 0; i < this._cameras.length; i++) {
  72428. var cameraName = this._cameras[i].name;
  72429. if (this._renderEffectsForIsolatedPass[cameraName]) {
  72430. this._renderEffectsForIsolatedPass[cameraName]._update();
  72431. }
  72432. }
  72433. };
  72434. PostProcessRenderPipeline.prototype._reset = function () {
  72435. this._renderEffects = {};
  72436. this._renderEffectsForIsolatedPass = new Array();
  72437. };
  72438. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  72439. // 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)
  72440. var effectKeys = Object.keys(this._renderEffects);
  72441. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  72442. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  72443. if (postProcesses) {
  72444. postProcesses[0].samples = sampleCount;
  72445. return true;
  72446. }
  72447. }
  72448. return false;
  72449. };
  72450. PostProcessRenderPipeline.prototype.dispose = function () {
  72451. // Must be implemented by children
  72452. };
  72453. __decorate([
  72454. BABYLON.serialize()
  72455. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  72456. return PostProcessRenderPipeline;
  72457. }());
  72458. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  72459. })(BABYLON || (BABYLON = {}));
  72460. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  72461. var BABYLON;
  72462. (function (BABYLON) {
  72463. /**
  72464. * This represents a depth renderer in Babylon.
  72465. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  72466. */
  72467. var DepthRenderer = /** @class */ (function () {
  72468. /**
  72469. * Instantiates a depth renderer
  72470. * @param scene The scene the renderer belongs to
  72471. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  72472. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  72473. */
  72474. function DepthRenderer(scene, type, camera) {
  72475. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  72476. if (camera === void 0) { camera = null; }
  72477. var _this = this;
  72478. this._scene = scene;
  72479. this._camera = camera;
  72480. var engine = scene.getEngine();
  72481. // Render target
  72482. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  72483. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72484. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72485. this._depthMap.refreshRate = 1;
  72486. this._depthMap.renderParticles = false;
  72487. this._depthMap.renderList = null;
  72488. // Camera to get depth map from to support multiple concurrent cameras
  72489. this._depthMap.activeCamera = this._camera;
  72490. this._depthMap.ignoreCameraViewport = true;
  72491. this._depthMap.useCameraPostProcesses = false;
  72492. // set default depth value to 1.0 (far away)
  72493. this._depthMap.onClearObservable.add(function (engine) {
  72494. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  72495. });
  72496. // Custom render function
  72497. var renderSubMesh = function (subMesh) {
  72498. var mesh = subMesh.getRenderingMesh();
  72499. var scene = _this._scene;
  72500. var engine = scene.getEngine();
  72501. var material = subMesh.getMaterial();
  72502. if (!material) {
  72503. return;
  72504. }
  72505. // Culling and reverse (right handed system)
  72506. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  72507. // Managing instances
  72508. var batch = mesh._getInstancesRenderList(subMesh._id);
  72509. if (batch.mustReturn) {
  72510. return;
  72511. }
  72512. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  72513. var camera = _this._camera || scene.activeCamera;
  72514. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  72515. engine.enableEffect(_this._effect);
  72516. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  72517. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  72518. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  72519. // Alpha test
  72520. if (material && material.needAlphaTesting()) {
  72521. var alphaTexture = material.getAlphaTestTexture();
  72522. if (alphaTexture) {
  72523. _this._effect.setTexture("diffuseSampler", alphaTexture);
  72524. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  72525. }
  72526. }
  72527. // Bones
  72528. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  72529. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  72530. }
  72531. // Draw
  72532. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  72533. }
  72534. };
  72535. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  72536. var index;
  72537. if (depthOnlySubMeshes.length) {
  72538. engine.setColorWrite(false);
  72539. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  72540. renderSubMesh(depthOnlySubMeshes.data[index]);
  72541. }
  72542. engine.setColorWrite(true);
  72543. }
  72544. for (index = 0; index < opaqueSubMeshes.length; index++) {
  72545. renderSubMesh(opaqueSubMeshes.data[index]);
  72546. }
  72547. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  72548. renderSubMesh(alphaTestSubMeshes.data[index]);
  72549. }
  72550. };
  72551. }
  72552. /**
  72553. * Creates the depth rendering effect and checks if the effect is ready.
  72554. * @param subMesh The submesh to be used to render the depth map of
  72555. * @param useInstances If multiple world instances should be used
  72556. * @returns if the depth renderer is ready to render the depth map
  72557. */
  72558. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  72559. var material = subMesh.getMaterial();
  72560. if (material.disableDepthWrite) {
  72561. return false;
  72562. }
  72563. var defines = [];
  72564. var attribs = [BABYLON.VertexBuffer.PositionKind];
  72565. var mesh = subMesh.getMesh();
  72566. // Alpha test
  72567. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  72568. defines.push("#define ALPHATEST");
  72569. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  72570. attribs.push(BABYLON.VertexBuffer.UVKind);
  72571. defines.push("#define UV1");
  72572. }
  72573. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  72574. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  72575. defines.push("#define UV2");
  72576. }
  72577. }
  72578. // Bones
  72579. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  72580. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  72581. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  72582. if (mesh.numBoneInfluencers > 4) {
  72583. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  72584. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  72585. }
  72586. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  72587. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  72588. }
  72589. else {
  72590. defines.push("#define NUM_BONE_INFLUENCERS 0");
  72591. }
  72592. // Instances
  72593. if (useInstances) {
  72594. defines.push("#define INSTANCES");
  72595. attribs.push("world0");
  72596. attribs.push("world1");
  72597. attribs.push("world2");
  72598. attribs.push("world3");
  72599. }
  72600. // Get correct effect
  72601. var join = defines.join("\n");
  72602. if (this._cachedDefines !== join) {
  72603. this._cachedDefines = join;
  72604. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  72605. }
  72606. return this._effect.isReady();
  72607. };
  72608. /**
  72609. * Gets the texture which the depth map will be written to.
  72610. * @returns The depth map texture
  72611. */
  72612. DepthRenderer.prototype.getDepthMap = function () {
  72613. return this._depthMap;
  72614. };
  72615. /**
  72616. * Disposes of the depth renderer.
  72617. */
  72618. DepthRenderer.prototype.dispose = function () {
  72619. this._depthMap.dispose();
  72620. };
  72621. return DepthRenderer;
  72622. }());
  72623. BABYLON.DepthRenderer = DepthRenderer;
  72624. })(BABYLON || (BABYLON = {}));
  72625. //# sourceMappingURL=babylon.depthRenderer.js.map
  72626. var BABYLON;
  72627. (function (BABYLON) {
  72628. var SSAORenderingPipeline = /** @class */ (function (_super) {
  72629. __extends(SSAORenderingPipeline, _super);
  72630. /**
  72631. * @constructor
  72632. * @param {string} name - The rendering pipeline name
  72633. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  72634. * @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 }
  72635. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  72636. */
  72637. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  72638. var _this = _super.call(this, scene.getEngine(), name) || this;
  72639. // Members
  72640. /**
  72641. * The PassPostProcess id in the pipeline that contains the original scene color
  72642. */
  72643. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  72644. /**
  72645. * The SSAO PostProcess id in the pipeline
  72646. */
  72647. _this.SSAORenderEffect = "SSAORenderEffect";
  72648. /**
  72649. * The horizontal blur PostProcess id in the pipeline
  72650. */
  72651. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  72652. /**
  72653. * The vertical blur PostProcess id in the pipeline
  72654. */
  72655. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  72656. /**
  72657. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  72658. */
  72659. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  72660. /**
  72661. * The output strength of the SSAO post-process. Default value is 1.0.
  72662. */
  72663. _this.totalStrength = 1.0;
  72664. /**
  72665. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  72666. */
  72667. _this.radius = 0.0001;
  72668. /**
  72669. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  72670. * Must not be equal to fallOff and superior to fallOff.
  72671. * Default value is 0.975
  72672. */
  72673. _this.area = 0.0075;
  72674. /**
  72675. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  72676. * Must not be equal to area and inferior to area.
  72677. * Default value is 0.0
  72678. */
  72679. _this.fallOff = 0.000001;
  72680. /**
  72681. * The base color of the SSAO post-process
  72682. * The final result is "base + ssao" between [0, 1]
  72683. */
  72684. _this.base = 0.5;
  72685. _this._firstUpdate = true;
  72686. _this._scene = scene;
  72687. // Set up assets
  72688. _this._createRandomTexture();
  72689. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  72690. var ssaoRatio = ratio.ssaoRatio || ratio;
  72691. var combineRatio = ratio.combineRatio || ratio;
  72692. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  72693. _this._createSSAOPostProcess(ssaoRatio);
  72694. _this._createBlurPostProcess(ssaoRatio);
  72695. _this._createSSAOCombinePostProcess(combineRatio);
  72696. // Set up pipeline
  72697. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  72698. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  72699. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  72700. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  72701. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  72702. // Finish
  72703. scene.postProcessRenderPipelineManager.addPipeline(_this);
  72704. if (cameras)
  72705. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  72706. return _this;
  72707. }
  72708. // Public Methods
  72709. /**
  72710. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  72711. */
  72712. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  72713. if (disableDepthRender === void 0) { disableDepthRender = false; }
  72714. for (var i = 0; i < this._scene.cameras.length; i++) {
  72715. var camera = this._scene.cameras[i];
  72716. this._originalColorPostProcess.dispose(camera);
  72717. this._ssaoPostProcess.dispose(camera);
  72718. this._blurHPostProcess.dispose(camera);
  72719. this._blurVPostProcess.dispose(camera);
  72720. this._ssaoCombinePostProcess.dispose(camera);
  72721. }
  72722. this._randomTexture.dispose();
  72723. if (disableDepthRender)
  72724. this._scene.disableDepthRenderer();
  72725. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  72726. _super.prototype.dispose.call(this);
  72727. };
  72728. // Private Methods
  72729. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  72730. var _this = this;
  72731. var size = 16;
  72732. 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);
  72733. 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);
  72734. this._blurHPostProcess.onActivateObservable.add(function () {
  72735. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  72736. _this._blurHPostProcess.kernel = size * dw;
  72737. });
  72738. this._blurVPostProcess.onActivateObservable.add(function () {
  72739. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  72740. _this._blurVPostProcess.kernel = size * dw;
  72741. });
  72742. };
  72743. SSAORenderingPipeline.prototype._rebuild = function () {
  72744. this._firstUpdate = true;
  72745. _super.prototype._rebuild.call(this);
  72746. };
  72747. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  72748. var _this = this;
  72749. var numSamples = 16;
  72750. var sampleSphere = [
  72751. 0.5381, 0.1856, -0.4319,
  72752. 0.1379, 0.2486, 0.4430,
  72753. 0.3371, 0.5679, -0.0057,
  72754. -0.6999, -0.0451, -0.0019,
  72755. 0.0689, -0.1598, -0.8547,
  72756. 0.0560, 0.0069, -0.1843,
  72757. -0.0146, 0.1402, 0.0762,
  72758. 0.0100, -0.1924, -0.0344,
  72759. -0.3577, -0.5301, -0.4358,
  72760. -0.3169, 0.1063, 0.0158,
  72761. 0.0103, -0.5869, 0.0046,
  72762. -0.0897, -0.4940, 0.3287,
  72763. 0.7119, -0.0154, -0.0918,
  72764. -0.0533, 0.0596, -0.5411,
  72765. 0.0352, -0.0631, 0.5460,
  72766. -0.4776, 0.2847, -0.0271
  72767. ];
  72768. var samplesFactor = 1.0 / numSamples;
  72769. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  72770. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  72771. "area", "fallOff", "base", "range", "viewport"
  72772. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  72773. this._ssaoPostProcess.onApply = function (effect) {
  72774. if (_this._firstUpdate) {
  72775. effect.setArray3("sampleSphere", sampleSphere);
  72776. effect.setFloat("samplesFactor", samplesFactor);
  72777. effect.setFloat("randTextureTiles", 4.0);
  72778. }
  72779. effect.setFloat("totalStrength", _this.totalStrength);
  72780. effect.setFloat("radius", _this.radius);
  72781. effect.setFloat("area", _this.area);
  72782. effect.setFloat("fallOff", _this.fallOff);
  72783. effect.setFloat("base", _this.base);
  72784. effect.setTexture("textureSampler", _this._depthTexture);
  72785. effect.setTexture("randomSampler", _this._randomTexture);
  72786. };
  72787. };
  72788. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  72789. var _this = this;
  72790. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  72791. this._ssaoCombinePostProcess.onApply = function (effect) {
  72792. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(0, 0, 1.0, 1.0));
  72793. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  72794. };
  72795. };
  72796. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  72797. var size = 512;
  72798. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  72799. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  72800. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  72801. var context = this._randomTexture.getContext();
  72802. var rand = function (min, max) {
  72803. return Math.random() * (max - min) + min;
  72804. };
  72805. var randVector = BABYLON.Vector3.Zero();
  72806. for (var x = 0; x < size; x++) {
  72807. for (var y = 0; y < size; y++) {
  72808. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  72809. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  72810. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  72811. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  72812. context.fillRect(x, y, 1, 1);
  72813. }
  72814. }
  72815. this._randomTexture.update(false);
  72816. };
  72817. __decorate([
  72818. BABYLON.serialize()
  72819. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  72820. __decorate([
  72821. BABYLON.serialize()
  72822. ], SSAORenderingPipeline.prototype, "radius", void 0);
  72823. __decorate([
  72824. BABYLON.serialize()
  72825. ], SSAORenderingPipeline.prototype, "area", void 0);
  72826. __decorate([
  72827. BABYLON.serialize()
  72828. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  72829. __decorate([
  72830. BABYLON.serialize()
  72831. ], SSAORenderingPipeline.prototype, "base", void 0);
  72832. return SSAORenderingPipeline;
  72833. }(BABYLON.PostProcessRenderPipeline));
  72834. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  72835. })(BABYLON || (BABYLON = {}));
  72836. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  72837. var BABYLON;
  72838. (function (BABYLON) {
  72839. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  72840. __extends(SSAO2RenderingPipeline, _super);
  72841. /**
  72842. * @constructor
  72843. * @param {string} name - The rendering pipeline name
  72844. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  72845. * @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 }
  72846. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  72847. */
  72848. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  72849. var _this = _super.call(this, scene.getEngine(), name) || this;
  72850. // Members
  72851. /**
  72852. * The PassPostProcess id in the pipeline that contains the original scene color
  72853. */
  72854. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  72855. /**
  72856. * The SSAO PostProcess id in the pipeline
  72857. */
  72858. _this.SSAORenderEffect = "SSAORenderEffect";
  72859. /**
  72860. * The horizontal blur PostProcess id in the pipeline
  72861. */
  72862. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  72863. /**
  72864. * The vertical blur PostProcess id in the pipeline
  72865. */
  72866. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  72867. /**
  72868. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  72869. */
  72870. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  72871. /**
  72872. * The output strength of the SSAO post-process. Default value is 1.0.
  72873. */
  72874. _this.totalStrength = 1.0;
  72875. /**
  72876. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  72877. */
  72878. _this.maxZ = 100.0;
  72879. /**
  72880. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  72881. */
  72882. _this.minZAspect = 0.2;
  72883. /**
  72884. * Number of samples used for the SSAO calculations. Default value is 8
  72885. */
  72886. _this._samples = 8;
  72887. /**
  72888. * Are we using bilateral blur ?
  72889. */
  72890. _this._expensiveBlur = true;
  72891. /**
  72892. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  72893. */
  72894. _this.radius = 2.0;
  72895. /**
  72896. * The base color of the SSAO post-process
  72897. * The final result is "base + ssao" between [0, 1]
  72898. */
  72899. _this.base = 0.1;
  72900. _this._firstUpdate = true;
  72901. _this._scene = scene;
  72902. _this._ratio = ratio;
  72903. if (!_this.isSupported) {
  72904. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  72905. return _this;
  72906. }
  72907. var ssaoRatio = _this._ratio.ssaoRatio || ratio;
  72908. var blurRatio = _this._ratio.blurRatio || ratio;
  72909. // Set up assets
  72910. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  72911. _this._createRandomTexture();
  72912. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  72913. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  72914. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  72915. _this._createSSAOPostProcess(1.0);
  72916. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  72917. _this._createSSAOCombinePostProcess(blurRatio);
  72918. // Set up pipeline
  72919. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  72920. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  72921. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  72922. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  72923. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  72924. // Finish
  72925. scene.postProcessRenderPipelineManager.addPipeline(_this);
  72926. if (cameras)
  72927. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  72928. return _this;
  72929. }
  72930. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  72931. get: function () {
  72932. return this._samples;
  72933. },
  72934. set: function (n) {
  72935. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  72936. this._samples = n;
  72937. this._sampleSphere = this._generateHemisphere();
  72938. this._firstUpdate = true;
  72939. },
  72940. enumerable: true,
  72941. configurable: true
  72942. });
  72943. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  72944. get: function () {
  72945. return this._expensiveBlur;
  72946. },
  72947. set: function (b) {
  72948. 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"]);
  72949. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  72950. this._expensiveBlur = b;
  72951. this._firstUpdate = true;
  72952. },
  72953. enumerable: true,
  72954. configurable: true
  72955. });
  72956. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  72957. /**
  72958. * Support test.
  72959. */
  72960. get: function () {
  72961. var engine = BABYLON.Engine.LastCreatedEngine;
  72962. if (!engine) {
  72963. return false;
  72964. }
  72965. return engine.getCaps().drawBuffersExtension;
  72966. },
  72967. enumerable: true,
  72968. configurable: true
  72969. });
  72970. // Public Methods
  72971. /**
  72972. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  72973. */
  72974. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  72975. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  72976. for (var i = 0; i < this._scene.cameras.length; i++) {
  72977. var camera = this._scene.cameras[i];
  72978. this._originalColorPostProcess.dispose(camera);
  72979. this._ssaoPostProcess.dispose(camera);
  72980. this._blurHPostProcess.dispose(camera);
  72981. this._blurVPostProcess.dispose(camera);
  72982. this._ssaoCombinePostProcess.dispose(camera);
  72983. }
  72984. this._randomTexture.dispose();
  72985. if (disableGeometryBufferRenderer)
  72986. this._scene.disableGeometryBufferRenderer();
  72987. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  72988. _super.prototype.dispose.call(this);
  72989. };
  72990. // Private Methods
  72991. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  72992. var _this = this;
  72993. this._samplerOffsets = [];
  72994. var expensive = this.expensiveBlur;
  72995. for (var i = -8; i < 8; i++) {
  72996. this._samplerOffsets.push(i * 2 + 0.5);
  72997. }
  72998. 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");
  72999. this._blurHPostProcess.onApply = function (effect) {
  73000. if (!_this._scene.activeCamera) {
  73001. return;
  73002. }
  73003. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  73004. effect.setFloat("near", _this._scene.activeCamera.minZ);
  73005. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  73006. effect.setFloat("radius", _this.radius);
  73007. effect.setTexture("depthSampler", _this._depthTexture);
  73008. if (_this._firstUpdate) {
  73009. effect.setArray("samplerOffsets", _this._samplerOffsets);
  73010. }
  73011. };
  73012. 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");
  73013. this._blurVPostProcess.onApply = function (effect) {
  73014. if (!_this._scene.activeCamera) {
  73015. return;
  73016. }
  73017. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  73018. effect.setFloat("near", _this._scene.activeCamera.minZ);
  73019. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  73020. effect.setFloat("radius", _this.radius);
  73021. effect.setTexture("depthSampler", _this._depthTexture);
  73022. if (_this._firstUpdate) {
  73023. effect.setArray("samplerOffsets", _this._samplerOffsets);
  73024. _this._firstUpdate = false;
  73025. }
  73026. };
  73027. };
  73028. SSAO2RenderingPipeline.prototype._rebuild = function () {
  73029. this._firstUpdate = true;
  73030. _super.prototype._rebuild.call(this);
  73031. };
  73032. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  73033. var numSamples = this.samples;
  73034. var result = [];
  73035. var vector, scale;
  73036. var rand = function (min, max) {
  73037. return Math.random() * (max - min) + min;
  73038. };
  73039. var i = 0;
  73040. while (i < numSamples) {
  73041. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  73042. vector.normalize();
  73043. scale = i / numSamples;
  73044. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  73045. vector.scaleInPlace(scale);
  73046. result.push(vector.x, vector.y, vector.z);
  73047. i++;
  73048. }
  73049. return result;
  73050. };
  73051. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  73052. var _this = this;
  73053. var numSamples = this.samples;
  73054. this._sampleSphere = this._generateHemisphere();
  73055. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  73056. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  73057. "base", "range", "projection", "near", "far", "texelSize",
  73058. "xViewport", "yViewport", "maxZ", "minZAspect"
  73059. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  73060. this._ssaoPostProcess.onApply = function (effect) {
  73061. if (_this._firstUpdate) {
  73062. effect.setArray3("sampleSphere", _this._sampleSphere);
  73063. effect.setFloat("randTextureTiles", 4.0);
  73064. }
  73065. if (!_this._scene.activeCamera) {
  73066. return;
  73067. }
  73068. effect.setFloat("samplesFactor", 1 / _this.samples);
  73069. effect.setFloat("totalStrength", _this.totalStrength);
  73070. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  73071. effect.setFloat("radius", _this.radius);
  73072. effect.setFloat("maxZ", _this.maxZ);
  73073. effect.setFloat("minZAspect", _this.minZAspect);
  73074. effect.setFloat("base", _this.base);
  73075. effect.setFloat("near", _this._scene.activeCamera.minZ);
  73076. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  73077. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  73078. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  73079. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  73080. effect.setTexture("textureSampler", _this._depthTexture);
  73081. effect.setTexture("normalSampler", _this._normalTexture);
  73082. effect.setTexture("randomSampler", _this._randomTexture);
  73083. };
  73084. };
  73085. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  73086. var _this = this;
  73087. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73088. this._ssaoCombinePostProcess.onApply = function (effect) {
  73089. var viewport = _this._scene.activeCamera.viewport;
  73090. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(viewport.x, viewport.y, viewport.width, viewport.height));
  73091. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  73092. };
  73093. };
  73094. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  73095. var size = 512;
  73096. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  73097. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  73098. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  73099. var context = this._randomTexture.getContext();
  73100. var rand = function (min, max) {
  73101. return Math.random() * (max - min) + min;
  73102. };
  73103. var randVector = BABYLON.Vector3.Zero();
  73104. for (var x = 0; x < size; x++) {
  73105. for (var y = 0; y < size; y++) {
  73106. randVector.x = rand(0.0, 1.0);
  73107. randVector.y = rand(0.0, 1.0);
  73108. randVector.z = 0.0;
  73109. randVector.normalize();
  73110. randVector.scaleInPlace(255);
  73111. randVector.x = Math.floor(randVector.x);
  73112. randVector.y = Math.floor(randVector.y);
  73113. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  73114. context.fillRect(x, y, 1, 1);
  73115. }
  73116. }
  73117. this._randomTexture.update(false);
  73118. };
  73119. /**
  73120. * Serialize the rendering pipeline (Used when exporting)
  73121. * @returns the serialized object
  73122. */
  73123. SSAO2RenderingPipeline.prototype.serialize = function () {
  73124. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  73125. serializationObject.customType = "SSAO2RenderingPipeline";
  73126. return serializationObject;
  73127. };
  73128. /**
  73129. * Parse the serialized pipeline
  73130. * @param source Source pipeline.
  73131. * @param scene The scene to load the pipeline to.
  73132. * @param rootUrl The URL of the serialized pipeline.
  73133. * @returns An instantiated pipeline from the serialized object.
  73134. */
  73135. SSAO2RenderingPipeline.Parse = function (source, scene, rootUrl) {
  73136. return BABYLON.SerializationHelper.Parse(function () { return new SSAO2RenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  73137. };
  73138. __decorate([
  73139. BABYLON.serialize()
  73140. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  73141. __decorate([
  73142. BABYLON.serialize()
  73143. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  73144. __decorate([
  73145. BABYLON.serialize()
  73146. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  73147. __decorate([
  73148. BABYLON.serialize("samples")
  73149. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  73150. __decorate([
  73151. BABYLON.serialize()
  73152. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  73153. __decorate([
  73154. BABYLON.serialize("expensiveBlur")
  73155. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  73156. __decorate([
  73157. BABYLON.serialize()
  73158. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  73159. __decorate([
  73160. BABYLON.serialize()
  73161. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  73162. return SSAO2RenderingPipeline;
  73163. }(BABYLON.PostProcessRenderPipeline));
  73164. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  73165. })(BABYLON || (BABYLON = {}));
  73166. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  73167. // BABYLON.JS Chromatic Aberration GLSL Shader
  73168. // Author: Olivier Guyot
  73169. // Separates very slightly R, G and B colors on the edges of the screen
  73170. // Inspired by Francois Tarlier & Martins Upitis
  73171. var BABYLON;
  73172. (function (BABYLON) {
  73173. var LensRenderingPipeline = /** @class */ (function (_super) {
  73174. __extends(LensRenderingPipeline, _super);
  73175. /**
  73176. * @constructor
  73177. *
  73178. * Effect parameters are as follow:
  73179. * {
  73180. * chromatic_aberration: number; // from 0 to x (1 for realism)
  73181. * edge_blur: number; // from 0 to x (1 for realism)
  73182. * distortion: number; // from 0 to x (1 for realism)
  73183. * grain_amount: number; // from 0 to 1
  73184. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  73185. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  73186. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  73187. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  73188. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  73189. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  73190. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  73191. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  73192. * }
  73193. * Note: if an effect parameter is unset, effect is disabled
  73194. *
  73195. * @param {string} name - The rendering pipeline name
  73196. * @param {object} parameters - An object containing all parameters (see above)
  73197. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73198. * @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)
  73199. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73200. */
  73201. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  73202. if (ratio === void 0) { ratio = 1.0; }
  73203. var _this = _super.call(this, scene.getEngine(), name) || this;
  73204. // Lens effects can be of the following:
  73205. // - chromatic aberration (slight shift of RGB colors)
  73206. // - blur on the edge of the lens
  73207. // - lens distortion
  73208. // - depth-of-field blur & highlights enhancing
  73209. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  73210. // - grain effect (noise or custom texture)
  73211. // Two additional texture samplers are needed:
  73212. // - depth map (for depth-of-field)
  73213. // - grain texture
  73214. /**
  73215. * The chromatic aberration PostProcess id in the pipeline
  73216. */
  73217. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  73218. /**
  73219. * The highlights enhancing PostProcess id in the pipeline
  73220. */
  73221. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  73222. /**
  73223. * The depth-of-field PostProcess id in the pipeline
  73224. */
  73225. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  73226. _this._scene = scene;
  73227. // Fetch texture samplers
  73228. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  73229. if (parameters.grain_texture) {
  73230. _this._grainTexture = parameters.grain_texture;
  73231. }
  73232. else {
  73233. _this._createGrainTexture();
  73234. }
  73235. // save parameters
  73236. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  73237. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  73238. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  73239. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  73240. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  73241. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  73242. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  73243. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  73244. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  73245. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  73246. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  73247. // Create effects
  73248. _this._createChromaticAberrationPostProcess(ratio);
  73249. _this._createHighlightsPostProcess(ratio);
  73250. _this._createDepthOfFieldPostProcess(ratio / 4);
  73251. // Set up pipeline
  73252. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  73253. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  73254. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  73255. if (_this._highlightsGain === -1) {
  73256. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  73257. }
  73258. // Finish
  73259. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73260. if (cameras) {
  73261. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  73262. }
  73263. return _this;
  73264. }
  73265. // public methods (self explanatory)
  73266. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  73267. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  73268. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  73269. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  73270. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  73271. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  73272. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  73273. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  73274. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  73275. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  73276. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  73277. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  73278. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  73279. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  73280. };
  73281. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  73282. this._highlightsPostProcess.updateEffect();
  73283. };
  73284. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  73285. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  73286. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  73287. this._highlightsGain = amount;
  73288. };
  73289. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  73290. if (this._highlightsGain === -1) {
  73291. this._highlightsGain = 1.0;
  73292. }
  73293. this._highlightsThreshold = amount;
  73294. };
  73295. LensRenderingPipeline.prototype.disableHighlights = function () {
  73296. this._highlightsGain = -1;
  73297. };
  73298. /**
  73299. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  73300. */
  73301. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  73302. if (disableDepthRender === void 0) { disableDepthRender = false; }
  73303. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  73304. this._chromaticAberrationPostProcess = null;
  73305. this._highlightsPostProcess = null;
  73306. this._depthOfFieldPostProcess = null;
  73307. this._grainTexture.dispose();
  73308. if (disableDepthRender)
  73309. this._scene.disableDepthRenderer();
  73310. };
  73311. // colors shifting and distortion
  73312. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  73313. var _this = this;
  73314. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  73315. [], // samplers
  73316. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73317. this._chromaticAberrationPostProcess.onApply = function (effect) {
  73318. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  73319. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  73320. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  73321. effect.setFloat('radialIntensity', 1);
  73322. effect.setFloat2('direction', 17, 17);
  73323. effect.setFloat2('centerPosition', 0.5, 0.5);
  73324. };
  73325. };
  73326. // highlights enhancing
  73327. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  73328. var _this = this;
  73329. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  73330. [], // samplers
  73331. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  73332. this._highlightsPostProcess.onApply = function (effect) {
  73333. effect.setFloat('gain', _this._highlightsGain);
  73334. effect.setFloat('threshold', _this._highlightsThreshold);
  73335. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  73336. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  73337. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  73338. };
  73339. };
  73340. // colors shifting and distortion
  73341. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  73342. var _this = this;
  73343. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  73344. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  73345. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  73346. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73347. this._depthOfFieldPostProcess.onApply = function (effect) {
  73348. effect.setTexture("depthSampler", _this._depthTexture);
  73349. effect.setTexture("grainSampler", _this._grainTexture);
  73350. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  73351. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  73352. effect.setFloat('grain_amount', _this._grainAmount);
  73353. effect.setBool('blur_noise', _this._blurNoise);
  73354. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  73355. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  73356. effect.setFloat('distortion', _this._distortion);
  73357. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  73358. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  73359. effect.setFloat('aperture', _this._dofAperture);
  73360. effect.setFloat('darken', _this._dofDarken);
  73361. effect.setFloat('edge_blur', _this._edgeBlur);
  73362. effect.setBool('highlights', (_this._highlightsGain !== -1));
  73363. if (_this._scene.activeCamera) {
  73364. effect.setFloat('near', _this._scene.activeCamera.minZ);
  73365. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  73366. }
  73367. };
  73368. };
  73369. // creates a black and white random noise texture, 512x512
  73370. LensRenderingPipeline.prototype._createGrainTexture = function () {
  73371. var size = 512;
  73372. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  73373. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  73374. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  73375. var context = this._grainTexture.getContext();
  73376. var rand = function (min, max) {
  73377. return Math.random() * (max - min) + min;
  73378. };
  73379. var value;
  73380. for (var x = 0; x < size; x++) {
  73381. for (var y = 0; y < size; y++) {
  73382. value = Math.floor(rand(0.42, 0.58) * 255);
  73383. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  73384. context.fillRect(x, y, 1, 1);
  73385. }
  73386. }
  73387. this._grainTexture.update(false);
  73388. };
  73389. return LensRenderingPipeline;
  73390. }(BABYLON.PostProcessRenderPipeline));
  73391. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  73392. })(BABYLON || (BABYLON = {}));
  73393. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  73394. var BABYLON;
  73395. (function (BABYLON) {
  73396. var StandardRenderingPipeline = /** @class */ (function (_super) {
  73397. __extends(StandardRenderingPipeline, _super);
  73398. /**
  73399. * @constructor
  73400. * @param {string} name - The rendering pipeline name
  73401. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73402. * @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)
  73403. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  73404. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73405. */
  73406. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  73407. if (originalPostProcess === void 0) { originalPostProcess = null; }
  73408. var _this = _super.call(this, scene.getEngine(), name) || this;
  73409. _this.downSampleX4PostProcess = null;
  73410. _this.brightPassPostProcess = null;
  73411. _this.blurHPostProcesses = [];
  73412. _this.blurVPostProcesses = [];
  73413. _this.textureAdderPostProcess = null;
  73414. _this.volumetricLightPostProcess = null;
  73415. _this.volumetricLightSmoothXPostProcess = null;
  73416. _this.volumetricLightSmoothYPostProcess = null;
  73417. _this.volumetricLightMergePostProces = null;
  73418. _this.volumetricLightFinalPostProcess = null;
  73419. _this.luminancePostProcess = null;
  73420. _this.luminanceDownSamplePostProcesses = [];
  73421. _this.hdrPostProcess = null;
  73422. _this.textureAdderFinalPostProcess = null;
  73423. _this.lensFlareFinalPostProcess = null;
  73424. _this.hdrFinalPostProcess = null;
  73425. _this.lensFlarePostProcess = null;
  73426. _this.lensFlareComposePostProcess = null;
  73427. _this.motionBlurPostProcess = null;
  73428. _this.depthOfFieldPostProcess = null;
  73429. // Values
  73430. _this.brightThreshold = 1.0;
  73431. _this.blurWidth = 512.0;
  73432. _this.horizontalBlur = false;
  73433. _this.exposure = 1.0;
  73434. _this.lensTexture = null;
  73435. _this.volumetricLightCoefficient = 0.2;
  73436. _this.volumetricLightPower = 4.0;
  73437. _this.volumetricLightBlurScale = 64.0;
  73438. _this.sourceLight = null;
  73439. _this.hdrMinimumLuminance = 1.0;
  73440. _this.hdrDecreaseRate = 0.5;
  73441. _this.hdrIncreaseRate = 0.5;
  73442. _this.lensColorTexture = null;
  73443. _this.lensFlareStrength = 20.0;
  73444. _this.lensFlareGhostDispersal = 1.4;
  73445. _this.lensFlareHaloWidth = 0.7;
  73446. _this.lensFlareDistortionStrength = 16.0;
  73447. _this.lensStarTexture = null;
  73448. _this.lensFlareDirtTexture = null;
  73449. _this.depthOfFieldDistance = 10.0;
  73450. _this.depthOfFieldBlurWidth = 64.0;
  73451. _this.motionStrength = 1.0;
  73452. // IAnimatable
  73453. _this.animations = [];
  73454. _this._currentDepthOfFieldSource = null;
  73455. _this._hdrCurrentLuminance = 1.0;
  73456. // Getters and setters
  73457. _this._bloomEnabled = true;
  73458. _this._depthOfFieldEnabled = false;
  73459. _this._vlsEnabled = false;
  73460. _this._lensFlareEnabled = false;
  73461. _this._hdrEnabled = false;
  73462. _this._motionBlurEnabled = false;
  73463. _this._motionBlurSamples = 64.0;
  73464. _this._volumetricLightStepsCount = 50.0;
  73465. _this._cameras = cameras || [];
  73466. // Initialize
  73467. _this._scene = scene;
  73468. _this._basePostProcess = originalPostProcess;
  73469. _this._ratio = ratio;
  73470. // Misc
  73471. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  73472. // Finish
  73473. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73474. _this._buildPipeline();
  73475. return _this;
  73476. }
  73477. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  73478. get: function () {
  73479. return this._bloomEnabled;
  73480. },
  73481. set: function (enabled) {
  73482. if (this._bloomEnabled === enabled) {
  73483. return;
  73484. }
  73485. this._bloomEnabled = enabled;
  73486. this._buildPipeline();
  73487. },
  73488. enumerable: true,
  73489. configurable: true
  73490. });
  73491. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  73492. get: function () {
  73493. return this._depthOfFieldEnabled;
  73494. },
  73495. set: function (enabled) {
  73496. if (this._depthOfFieldEnabled === enabled) {
  73497. return;
  73498. }
  73499. this._depthOfFieldEnabled = enabled;
  73500. this._buildPipeline();
  73501. },
  73502. enumerable: true,
  73503. configurable: true
  73504. });
  73505. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  73506. get: function () {
  73507. return this._lensFlareEnabled;
  73508. },
  73509. set: function (enabled) {
  73510. if (this._lensFlareEnabled === enabled) {
  73511. return;
  73512. }
  73513. this._lensFlareEnabled = enabled;
  73514. this._buildPipeline();
  73515. },
  73516. enumerable: true,
  73517. configurable: true
  73518. });
  73519. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  73520. get: function () {
  73521. return this._hdrEnabled;
  73522. },
  73523. set: function (enabled) {
  73524. if (this._hdrEnabled === enabled) {
  73525. return;
  73526. }
  73527. this._hdrEnabled = enabled;
  73528. this._buildPipeline();
  73529. },
  73530. enumerable: true,
  73531. configurable: true
  73532. });
  73533. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  73534. get: function () {
  73535. return this._vlsEnabled;
  73536. },
  73537. set: function (enabled) {
  73538. if (this._vlsEnabled === enabled) {
  73539. return;
  73540. }
  73541. if (enabled) {
  73542. var geometry = this._scene.enableGeometryBufferRenderer();
  73543. if (!geometry) {
  73544. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  73545. return;
  73546. }
  73547. }
  73548. this._vlsEnabled = enabled;
  73549. this._buildPipeline();
  73550. },
  73551. enumerable: true,
  73552. configurable: true
  73553. });
  73554. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  73555. get: function () {
  73556. return this._motionBlurEnabled;
  73557. },
  73558. set: function (enabled) {
  73559. if (this._motionBlurEnabled === enabled) {
  73560. return;
  73561. }
  73562. this._motionBlurEnabled = enabled;
  73563. this._buildPipeline();
  73564. },
  73565. enumerable: true,
  73566. configurable: true
  73567. });
  73568. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  73569. get: function () {
  73570. return this._volumetricLightStepsCount;
  73571. },
  73572. set: function (count) {
  73573. if (this.volumetricLightPostProcess) {
  73574. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  73575. }
  73576. this._volumetricLightStepsCount = count;
  73577. },
  73578. enumerable: true,
  73579. configurable: true
  73580. });
  73581. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  73582. get: function () {
  73583. return this._motionBlurSamples;
  73584. },
  73585. set: function (samples) {
  73586. if (this.motionBlurPostProcess) {
  73587. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  73588. }
  73589. this._motionBlurSamples = samples;
  73590. },
  73591. enumerable: true,
  73592. configurable: true
  73593. });
  73594. StandardRenderingPipeline.prototype._buildPipeline = function () {
  73595. var _this = this;
  73596. var ratio = this._ratio;
  73597. var scene = this._scene;
  73598. this._disposePostProcesses();
  73599. this._reset();
  73600. // Create pass post-process
  73601. if (!this._basePostProcess) {
  73602. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  73603. this.originalPostProcess.onApply = function (effect) {
  73604. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  73605. };
  73606. }
  73607. else {
  73608. this.originalPostProcess = this._basePostProcess;
  73609. }
  73610. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  73611. this._currentDepthOfFieldSource = this.originalPostProcess;
  73612. if (this._bloomEnabled) {
  73613. // Create down sample X4 post-process
  73614. this._createDownSampleX4PostProcess(scene, ratio / 2);
  73615. // Create bright pass post-process
  73616. this._createBrightPassPostProcess(scene, ratio / 2);
  73617. // Create gaussian blur post-processes (down sampling blurs)
  73618. this._createBlurPostProcesses(scene, ratio / 4, 1);
  73619. // Create texture adder post-process
  73620. this._createTextureAdderPostProcess(scene, ratio);
  73621. // Create depth-of-field source post-process
  73622. 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);
  73623. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  73624. }
  73625. if (this._vlsEnabled) {
  73626. // Create volumetric light
  73627. this._createVolumetricLightPostProcess(scene, ratio);
  73628. // Create volumetric light final post-process
  73629. 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);
  73630. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  73631. }
  73632. if (this._lensFlareEnabled) {
  73633. // Create lens flare post-process
  73634. this._createLensFlarePostProcess(scene, ratio);
  73635. // Create depth-of-field source post-process post lens-flare and disable it now
  73636. 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);
  73637. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  73638. }
  73639. if (this._hdrEnabled) {
  73640. // Create luminance
  73641. this._createLuminancePostProcesses(scene, this._floatTextureType);
  73642. // Create HDR
  73643. this._createHdrPostProcess(scene, ratio);
  73644. // Create depth-of-field source post-process post hdr and disable it now
  73645. 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);
  73646. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  73647. }
  73648. if (this._depthOfFieldEnabled) {
  73649. // Create gaussian blur used by depth-of-field
  73650. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  73651. // Create depth-of-field post-process
  73652. this._createDepthOfFieldPostProcess(scene, ratio);
  73653. }
  73654. if (this._motionBlurEnabled) {
  73655. // Create motion blur post-process
  73656. this._createMotionBlurPostProcess(scene, ratio);
  73657. }
  73658. if (this._cameras !== null) {
  73659. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  73660. }
  73661. };
  73662. // Down Sample X4 Post-Processs
  73663. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  73664. var _this = this;
  73665. var downSampleX4Offsets = new Array(32);
  73666. 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);
  73667. this.downSampleX4PostProcess.onApply = function (effect) {
  73668. var id = 0;
  73669. var width = _this.downSampleX4PostProcess.width;
  73670. var height = _this.downSampleX4PostProcess.height;
  73671. for (var i = -2; i < 2; i++) {
  73672. for (var j = -2; j < 2; j++) {
  73673. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  73674. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  73675. id += 2;
  73676. }
  73677. }
  73678. effect.setArray2("dsOffsets", downSampleX4Offsets);
  73679. };
  73680. // Add to pipeline
  73681. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  73682. };
  73683. // Brightpass Post-Process
  73684. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  73685. var _this = this;
  73686. var brightOffsets = new Array(8);
  73687. 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);
  73688. this.brightPassPostProcess.onApply = function (effect) {
  73689. var sU = (1.0 / _this.brightPassPostProcess.width);
  73690. var sV = (1.0 / _this.brightPassPostProcess.height);
  73691. brightOffsets[0] = -0.5 * sU;
  73692. brightOffsets[1] = 0.5 * sV;
  73693. brightOffsets[2] = 0.5 * sU;
  73694. brightOffsets[3] = 0.5 * sV;
  73695. brightOffsets[4] = -0.5 * sU;
  73696. brightOffsets[5] = -0.5 * sV;
  73697. brightOffsets[6] = 0.5 * sU;
  73698. brightOffsets[7] = -0.5 * sV;
  73699. effect.setArray2("dsOffsets", brightOffsets);
  73700. effect.setFloat("brightThreshold", _this.brightThreshold);
  73701. };
  73702. // Add to pipeline
  73703. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  73704. };
  73705. // Create blur H&V post-processes
  73706. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  73707. var _this = this;
  73708. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  73709. var engine = scene.getEngine();
  73710. 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);
  73711. 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);
  73712. blurX.onActivateObservable.add(function () {
  73713. var dw = blurX.width / engine.getRenderWidth();
  73714. blurX.kernel = _this[blurWidthKey] * dw;
  73715. });
  73716. blurY.onActivateObservable.add(function () {
  73717. var dw = blurY.height / engine.getRenderHeight();
  73718. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  73719. });
  73720. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  73721. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  73722. this.blurHPostProcesses.push(blurX);
  73723. this.blurVPostProcesses.push(blurY);
  73724. };
  73725. // Create texture adder post-process
  73726. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  73727. var _this = this;
  73728. 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);
  73729. this.textureAdderPostProcess.onApply = function (effect) {
  73730. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  73731. effect.setTexture("lensSampler", _this.lensTexture);
  73732. effect.setFloat("exposure", _this.exposure);
  73733. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  73734. };
  73735. // Add to pipeline
  73736. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  73737. };
  73738. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  73739. var _this = this;
  73740. var geometryRenderer = scene.enableGeometryBufferRenderer();
  73741. geometryRenderer.enablePosition = true;
  73742. var geometry = geometryRenderer.getGBuffer();
  73743. // Base post-process
  73744. 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));
  73745. var depthValues = BABYLON.Vector2.Zero();
  73746. this.volumetricLightPostProcess.onApply = function (effect) {
  73747. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  73748. var generator = _this.sourceLight.getShadowGenerator();
  73749. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  73750. effect.setTexture("positionSampler", geometry.textures[2]);
  73751. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  73752. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  73753. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  73754. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  73755. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  73756. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  73757. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  73758. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  73759. effect.setVector2("depthValues", depthValues);
  73760. }
  73761. };
  73762. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  73763. // Smooth
  73764. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  73765. // Merge
  73766. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  73767. this.volumetricLightMergePostProces.onApply = function (effect) {
  73768. effect.setTextureFromPostProcess("originalSampler", _this._bloomEnabled ? _this.textureAdderFinalPostProcess : _this.originalPostProcess);
  73769. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  73770. };
  73771. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  73772. };
  73773. // Create luminance
  73774. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  73775. var _this = this;
  73776. // Create luminance
  73777. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  73778. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  73779. var offsets = [];
  73780. this.luminancePostProcess.onApply = function (effect) {
  73781. var sU = (1.0 / _this.luminancePostProcess.width);
  73782. var sV = (1.0 / _this.luminancePostProcess.height);
  73783. offsets[0] = -0.5 * sU;
  73784. offsets[1] = 0.5 * sV;
  73785. offsets[2] = 0.5 * sU;
  73786. offsets[3] = 0.5 * sV;
  73787. offsets[4] = -0.5 * sU;
  73788. offsets[5] = -0.5 * sV;
  73789. offsets[6] = 0.5 * sU;
  73790. offsets[7] = -0.5 * sV;
  73791. effect.setArray2("lumOffsets", offsets);
  73792. };
  73793. // Add to pipeline
  73794. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  73795. // Create down sample luminance
  73796. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  73797. var size = Math.pow(3, i);
  73798. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  73799. if (i === 0) {
  73800. defines += "#define FINAL_DOWN_SAMPLER";
  73801. }
  73802. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  73803. this.luminanceDownSamplePostProcesses.push(postProcess);
  73804. }
  73805. // Create callbacks and add effects
  73806. var lastLuminance = this.luminancePostProcess;
  73807. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  73808. var downSampleOffsets = new Array(18);
  73809. pp.onApply = function (effect) {
  73810. if (!lastLuminance) {
  73811. return;
  73812. }
  73813. var id = 0;
  73814. for (var x = -1; x < 2; x++) {
  73815. for (var y = -1; y < 2; y++) {
  73816. downSampleOffsets[id] = x / lastLuminance.width;
  73817. downSampleOffsets[id + 1] = y / lastLuminance.height;
  73818. id += 2;
  73819. }
  73820. }
  73821. effect.setArray2("dsOffsets", downSampleOffsets);
  73822. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  73823. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  73824. lastLuminance = _this.luminancePostProcess;
  73825. }
  73826. else {
  73827. lastLuminance = pp;
  73828. }
  73829. };
  73830. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  73831. pp.onAfterRender = function (effect) {
  73832. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  73833. 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);
  73834. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  73835. };
  73836. }
  73837. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  73838. });
  73839. };
  73840. // Create HDR post-process
  73841. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  73842. var _this = this;
  73843. 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);
  73844. var outputLiminance = 1;
  73845. var time = 0;
  73846. var lastTime = 0;
  73847. this.hdrPostProcess.onApply = function (effect) {
  73848. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  73849. time += scene.getEngine().getDeltaTime();
  73850. if (outputLiminance < 0) {
  73851. outputLiminance = _this._hdrCurrentLuminance;
  73852. }
  73853. else {
  73854. var dt = (lastTime - time) / 1000.0;
  73855. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  73856. outputLiminance += _this.hdrDecreaseRate * dt;
  73857. }
  73858. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  73859. outputLiminance -= _this.hdrIncreaseRate * dt;
  73860. }
  73861. else {
  73862. outputLiminance = _this._hdrCurrentLuminance;
  73863. }
  73864. }
  73865. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  73866. effect.setFloat("averageLuminance", outputLiminance);
  73867. lastTime = time;
  73868. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  73869. };
  73870. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  73871. };
  73872. // Create lens flare post-process
  73873. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  73874. var _this = this;
  73875. 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);
  73876. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  73877. this._createBlurPostProcesses(scene, ratio / 4, 2);
  73878. 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);
  73879. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  73880. var resolution = new BABYLON.Vector2(0, 0);
  73881. // Lens flare
  73882. this.lensFlarePostProcess.onApply = function (effect) {
  73883. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  73884. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  73885. effect.setFloat("strength", _this.lensFlareStrength);
  73886. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  73887. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  73888. // Shift
  73889. resolution.x = _this.lensFlarePostProcess.width;
  73890. resolution.y = _this.lensFlarePostProcess.height;
  73891. effect.setVector2("resolution", resolution);
  73892. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  73893. };
  73894. // Compose
  73895. 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);
  73896. 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);
  73897. this.lensFlareComposePostProcess.onApply = function (effect) {
  73898. if (!_this._scene.activeCamera) {
  73899. return;
  73900. }
  73901. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  73902. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  73903. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  73904. // Lens start rotation matrix
  73905. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  73906. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  73907. 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));
  73908. camRot *= 4.0;
  73909. 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);
  73910. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  73911. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  73912. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  73913. };
  73914. };
  73915. // Create depth-of-field post-process
  73916. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  73917. var _this = this;
  73918. 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);
  73919. this.depthOfFieldPostProcess.onApply = function (effect) {
  73920. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  73921. effect.setTexture("depthSampler", _this._getDepthTexture());
  73922. effect.setFloat("distance", _this.depthOfFieldDistance);
  73923. };
  73924. // Add to pipeline
  73925. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  73926. };
  73927. // Create motion blur post-process
  73928. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  73929. var _this = this;
  73930. 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);
  73931. var motionScale = 0;
  73932. var prevViewProjection = BABYLON.Matrix.Identity();
  73933. var invViewProjection = BABYLON.Matrix.Identity();
  73934. var viewProjection = BABYLON.Matrix.Identity();
  73935. var screenSize = BABYLON.Vector2.Zero();
  73936. this.motionBlurPostProcess.onApply = function (effect) {
  73937. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  73938. viewProjection.invertToRef(invViewProjection);
  73939. effect.setMatrix("inverseViewProjection", invViewProjection);
  73940. effect.setMatrix("prevViewProjection", prevViewProjection);
  73941. prevViewProjection = viewProjection;
  73942. screenSize.x = _this.motionBlurPostProcess.width;
  73943. screenSize.y = _this.motionBlurPostProcess.height;
  73944. effect.setVector2("screenSize", screenSize);
  73945. motionScale = scene.getEngine().getFps() / 60.0;
  73946. effect.setFloat("motionScale", motionScale);
  73947. effect.setFloat("motionStrength", _this.motionStrength);
  73948. effect.setTexture("depthSampler", _this._getDepthTexture());
  73949. };
  73950. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  73951. };
  73952. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  73953. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  73954. var renderer = this._scene.enableGeometryBufferRenderer();
  73955. return renderer.getGBuffer().textures[0];
  73956. }
  73957. return this._scene.enableDepthRenderer().getDepthMap();
  73958. };
  73959. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  73960. for (var i = 0; i < this._cameras.length; i++) {
  73961. var camera = this._cameras[i];
  73962. if (this.originalPostProcess) {
  73963. this.originalPostProcess.dispose(camera);
  73964. }
  73965. if (this.downSampleX4PostProcess) {
  73966. this.downSampleX4PostProcess.dispose(camera);
  73967. }
  73968. if (this.brightPassPostProcess) {
  73969. this.brightPassPostProcess.dispose(camera);
  73970. }
  73971. if (this.textureAdderPostProcess) {
  73972. this.textureAdderPostProcess.dispose(camera);
  73973. }
  73974. if (this.textureAdderFinalPostProcess) {
  73975. this.textureAdderFinalPostProcess.dispose(camera);
  73976. }
  73977. if (this.volumetricLightPostProcess) {
  73978. this.volumetricLightPostProcess.dispose(camera);
  73979. }
  73980. if (this.volumetricLightSmoothXPostProcess) {
  73981. this.volumetricLightSmoothXPostProcess.dispose(camera);
  73982. }
  73983. if (this.volumetricLightSmoothYPostProcess) {
  73984. this.volumetricLightSmoothYPostProcess.dispose(camera);
  73985. }
  73986. if (this.volumetricLightMergePostProces) {
  73987. this.volumetricLightMergePostProces.dispose(camera);
  73988. }
  73989. if (this.volumetricLightFinalPostProcess) {
  73990. this.volumetricLightFinalPostProcess.dispose(camera);
  73991. }
  73992. if (this.lensFlarePostProcess) {
  73993. this.lensFlarePostProcess.dispose(camera);
  73994. }
  73995. if (this.lensFlareComposePostProcess) {
  73996. this.lensFlareComposePostProcess.dispose(camera);
  73997. }
  73998. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  73999. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  74000. }
  74001. if (this.luminancePostProcess) {
  74002. this.luminancePostProcess.dispose(camera);
  74003. }
  74004. if (this.hdrPostProcess) {
  74005. this.hdrPostProcess.dispose(camera);
  74006. }
  74007. if (this.hdrFinalPostProcess) {
  74008. this.hdrFinalPostProcess.dispose(camera);
  74009. }
  74010. if (this.depthOfFieldPostProcess) {
  74011. this.depthOfFieldPostProcess.dispose(camera);
  74012. }
  74013. if (this.motionBlurPostProcess) {
  74014. this.motionBlurPostProcess.dispose(camera);
  74015. }
  74016. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  74017. this.blurHPostProcesses[j].dispose(camera);
  74018. }
  74019. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  74020. this.blurVPostProcesses[j].dispose(camera);
  74021. }
  74022. }
  74023. this.originalPostProcess = null;
  74024. this.downSampleX4PostProcess = null;
  74025. this.brightPassPostProcess = null;
  74026. this.textureAdderPostProcess = null;
  74027. this.textureAdderFinalPostProcess = null;
  74028. this.volumetricLightPostProcess = null;
  74029. this.volumetricLightSmoothXPostProcess = null;
  74030. this.volumetricLightSmoothYPostProcess = null;
  74031. this.volumetricLightMergePostProces = null;
  74032. this.volumetricLightFinalPostProcess = null;
  74033. this.lensFlarePostProcess = null;
  74034. this.lensFlareComposePostProcess = null;
  74035. this.luminancePostProcess = null;
  74036. this.hdrPostProcess = null;
  74037. this.hdrFinalPostProcess = null;
  74038. this.depthOfFieldPostProcess = null;
  74039. this.motionBlurPostProcess = null;
  74040. this.luminanceDownSamplePostProcesses = [];
  74041. this.blurHPostProcesses = [];
  74042. this.blurVPostProcesses = [];
  74043. };
  74044. /**
  74045. * Dispose of the pipeline and stop all post processes
  74046. */
  74047. StandardRenderingPipeline.prototype.dispose = function () {
  74048. this._disposePostProcesses();
  74049. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  74050. _super.prototype.dispose.call(this);
  74051. };
  74052. /**
  74053. * Serialize the rendering pipeline (Used when exporting)
  74054. * @returns the serialized object
  74055. */
  74056. StandardRenderingPipeline.prototype.serialize = function () {
  74057. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  74058. if (this.sourceLight) {
  74059. serializationObject.sourceLightId = this.sourceLight.id;
  74060. }
  74061. serializationObject.customType = "StandardRenderingPipeline";
  74062. return serializationObject;
  74063. };
  74064. /**
  74065. * Parse the serialized pipeline
  74066. * @param source Source pipeline.
  74067. * @param scene The scene to load the pipeline to.
  74068. * @param rootUrl The URL of the serialized pipeline.
  74069. * @returns An instantiated pipeline from the serialized object.
  74070. */
  74071. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  74072. var p = BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  74073. if (source.sourceLightId) {
  74074. p.sourceLight = scene.getLightByID(source.sourceLightId);
  74075. }
  74076. return p;
  74077. };
  74078. // Luminance steps
  74079. StandardRenderingPipeline.LuminanceSteps = 6;
  74080. __decorate([
  74081. BABYLON.serialize()
  74082. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  74083. __decorate([
  74084. BABYLON.serialize()
  74085. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  74086. __decorate([
  74087. BABYLON.serialize()
  74088. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  74089. __decorate([
  74090. BABYLON.serialize()
  74091. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  74092. __decorate([
  74093. BABYLON.serializeAsTexture("lensTexture")
  74094. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  74095. __decorate([
  74096. BABYLON.serialize()
  74097. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  74098. __decorate([
  74099. BABYLON.serialize()
  74100. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  74101. __decorate([
  74102. BABYLON.serialize()
  74103. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  74104. __decorate([
  74105. BABYLON.serialize()
  74106. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  74107. __decorate([
  74108. BABYLON.serialize()
  74109. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  74110. __decorate([
  74111. BABYLON.serialize()
  74112. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  74113. __decorate([
  74114. BABYLON.serializeAsTexture("lensColorTexture")
  74115. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  74116. __decorate([
  74117. BABYLON.serialize()
  74118. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  74119. __decorate([
  74120. BABYLON.serialize()
  74121. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  74122. __decorate([
  74123. BABYLON.serialize()
  74124. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  74125. __decorate([
  74126. BABYLON.serialize()
  74127. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  74128. __decorate([
  74129. BABYLON.serializeAsTexture("lensStarTexture")
  74130. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  74131. __decorate([
  74132. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  74133. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  74134. __decorate([
  74135. BABYLON.serialize()
  74136. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  74137. __decorate([
  74138. BABYLON.serialize()
  74139. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  74140. __decorate([
  74141. BABYLON.serialize()
  74142. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  74143. __decorate([
  74144. BABYLON.serialize()
  74145. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  74146. __decorate([
  74147. BABYLON.serialize()
  74148. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  74149. __decorate([
  74150. BABYLON.serialize()
  74151. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  74152. __decorate([
  74153. BABYLON.serialize()
  74154. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  74155. __decorate([
  74156. BABYLON.serialize()
  74157. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  74158. __decorate([
  74159. BABYLON.serialize()
  74160. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  74161. __decorate([
  74162. BABYLON.serialize()
  74163. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  74164. __decorate([
  74165. BABYLON.serialize()
  74166. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  74167. __decorate([
  74168. BABYLON.serialize()
  74169. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  74170. return StandardRenderingPipeline;
  74171. }(BABYLON.PostProcessRenderPipeline));
  74172. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  74173. })(BABYLON || (BABYLON = {}));
  74174. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  74175. var BABYLON;
  74176. (function (BABYLON) {
  74177. var FxaaPostProcess = /** @class */ (function (_super) {
  74178. __extends(FxaaPostProcess, _super);
  74179. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  74180. if (camera === void 0) { camera = null; }
  74181. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74182. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa", undefined, true) || this;
  74183. var defines = _this._getDefines();
  74184. _this.updateEffect(defines);
  74185. _this.onApplyObservable.add(function (effect) {
  74186. var texelSize = _this.texelSize;
  74187. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  74188. });
  74189. return _this;
  74190. }
  74191. FxaaPostProcess.prototype._getDefines = function () {
  74192. var engine = this.getEngine();
  74193. if (!engine) {
  74194. return null;
  74195. }
  74196. var glInfo = engine.getGlInfo();
  74197. if (glInfo && glInfo.renderer && glInfo.renderer.toLowerCase().indexOf("mali") > -1) {
  74198. return "#define MALI 1\n";
  74199. }
  74200. return null;
  74201. };
  74202. return FxaaPostProcess;
  74203. }(BABYLON.PostProcess));
  74204. BABYLON.FxaaPostProcess = FxaaPostProcess;
  74205. })(BABYLON || (BABYLON = {}));
  74206. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  74207. var BABYLON;
  74208. (function (BABYLON) {
  74209. /**
  74210. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  74211. */
  74212. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  74213. __extends(ChromaticAberrationPostProcess, _super);
  74214. /**
  74215. * Creates a new instance ChromaticAberrationPostProcess
  74216. * @param name The name of the effect.
  74217. * @param screenWidth The width of the screen to apply the effect on.
  74218. * @param screenHeight The height of the screen to apply the effect on.
  74219. * @param options The required width/height ratio to downsize to before computing the render pass.
  74220. * @param camera The camera to apply the render pass to.
  74221. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74222. * @param engine The engine which the post process will be applied. (default: current engine)
  74223. * @param reusable If the post process can be reused on the same frame. (default: false)
  74224. * @param textureType Type of textures used when performing the post process. (default: 0)
  74225. * @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)
  74226. */
  74227. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74228. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74229. if (blockCompilation === void 0) { blockCompilation = false; }
  74230. 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;
  74231. /**
  74232. * The amount of seperation of rgb channels (default: 30)
  74233. */
  74234. _this.aberrationAmount = 30;
  74235. /**
  74236. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  74237. */
  74238. _this.radialIntensity = 0;
  74239. /**
  74240. * 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))
  74241. */
  74242. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  74243. /**
  74244. * 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))
  74245. */
  74246. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  74247. _this.onApplyObservable.add(function (effect) {
  74248. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  74249. effect.setFloat('screen_width', screenWidth);
  74250. effect.setFloat('screen_height', screenHeight);
  74251. effect.setFloat('radialIntensity', _this.radialIntensity);
  74252. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  74253. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  74254. });
  74255. return _this;
  74256. }
  74257. return ChromaticAberrationPostProcess;
  74258. }(BABYLON.PostProcess));
  74259. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  74260. })(BABYLON || (BABYLON = {}));
  74261. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  74262. var BABYLON;
  74263. (function (BABYLON) {
  74264. /**
  74265. * The GrainPostProcess adds noise to the image at mid luminance levels
  74266. */
  74267. var GrainPostProcess = /** @class */ (function (_super) {
  74268. __extends(GrainPostProcess, _super);
  74269. /**
  74270. * Creates a new instance of @see GrainPostProcess
  74271. * @param name The name of the effect.
  74272. * @param options The required width/height ratio to downsize to before computing the render pass.
  74273. * @param camera The camera to apply the render pass to.
  74274. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74275. * @param engine The engine which the post process will be applied. (default: current engine)
  74276. * @param reusable If the post process can be reused on the same frame. (default: false)
  74277. * @param textureType Type of textures used when performing the post process. (default: 0)
  74278. * @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)
  74279. */
  74280. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74281. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74282. if (blockCompilation === void 0) { blockCompilation = false; }
  74283. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  74284. /**
  74285. * The intensity of the grain added (default: 30)
  74286. */
  74287. _this.intensity = 30;
  74288. /**
  74289. * If the grain should be randomized on every frame
  74290. */
  74291. _this.animated = false;
  74292. _this.onApplyObservable.add(function (effect) {
  74293. effect.setFloat('intensity', _this.intensity);
  74294. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  74295. });
  74296. return _this;
  74297. }
  74298. return GrainPostProcess;
  74299. }(BABYLON.PostProcess));
  74300. BABYLON.GrainPostProcess = GrainPostProcess;
  74301. })(BABYLON || (BABYLON = {}));
  74302. //# sourceMappingURL=babylon.grainPostProcess.js.map
  74303. var BABYLON;
  74304. (function (BABYLON) {
  74305. /**
  74306. * The SharpenPostProcess applies a sharpen kernel to every pixel
  74307. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  74308. */
  74309. var SharpenPostProcess = /** @class */ (function (_super) {
  74310. __extends(SharpenPostProcess, _super);
  74311. /**
  74312. * Creates a new instance ConvolutionPostProcess
  74313. * @param name The name of the effect.
  74314. * @param options The required width/height ratio to downsize to before computing the render pass.
  74315. * @param camera The camera to apply the render pass to.
  74316. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74317. * @param engine The engine which the post process will be applied. (default: current engine)
  74318. * @param reusable If the post process can be reused on the same frame. (default: false)
  74319. * @param textureType Type of textures used when performing the post process. (default: 0)
  74320. * @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)
  74321. */
  74322. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74323. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74324. if (blockCompilation === void 0) { blockCompilation = false; }
  74325. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  74326. /**
  74327. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  74328. */
  74329. _this.colorAmount = 1.0;
  74330. /**
  74331. * How much sharpness should be applied (default: 0.3)
  74332. */
  74333. _this.edgeAmount = 0.3;
  74334. _this.onApply = function (effect) {
  74335. effect.setFloat2("screenSize", _this.width, _this.height);
  74336. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  74337. };
  74338. return _this;
  74339. }
  74340. return SharpenPostProcess;
  74341. }(BABYLON.PostProcess));
  74342. BABYLON.SharpenPostProcess = SharpenPostProcess;
  74343. })(BABYLON || (BABYLON = {}));
  74344. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  74345. var BABYLON;
  74346. (function (BABYLON) {
  74347. /**
  74348. * The Blur Post Process which blurs an image based on a kernel and direction.
  74349. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  74350. */
  74351. var BlurPostProcess = /** @class */ (function (_super) {
  74352. __extends(BlurPostProcess, _super);
  74353. /**
  74354. * Creates a new instance BlurPostProcess
  74355. * @param name The name of the effect.
  74356. * @param direction The direction in which to blur the image.
  74357. * @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.
  74358. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  74359. * @param camera The camera to apply the render pass to.
  74360. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74361. * @param engine The engine which the post process will be applied. (default: current engine)
  74362. * @param reusable If the post process can be reused on the same frame. (default: false)
  74363. * @param textureType Type of textures used when performing the post process. (default: 0)
  74364. * @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)
  74365. */
  74366. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  74367. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  74368. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74369. if (defines === void 0) { defines = ""; }
  74370. if (blockCompilation === void 0) { blockCompilation = false; }
  74371. 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;
  74372. _this.direction = direction;
  74373. _this.blockCompilation = blockCompilation;
  74374. _this._packedFloat = false;
  74375. _this._staticDefines = "";
  74376. _this._staticDefines = defines;
  74377. _this.onApplyObservable.add(function (effect) {
  74378. if (_this._outputTexture) {
  74379. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  74380. }
  74381. else {
  74382. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  74383. }
  74384. });
  74385. _this.kernel = kernel;
  74386. return _this;
  74387. }
  74388. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  74389. /**
  74390. * Gets the length in pixels of the blur sample region
  74391. */
  74392. get: function () {
  74393. return this._idealKernel;
  74394. },
  74395. /**
  74396. * Sets the length in pixels of the blur sample region
  74397. */
  74398. set: function (v) {
  74399. if (this._idealKernel === v) {
  74400. return;
  74401. }
  74402. v = Math.max(v, 1);
  74403. this._idealKernel = v;
  74404. this._kernel = this._nearestBestKernel(v);
  74405. if (!this.blockCompilation) {
  74406. this._updateParameters();
  74407. }
  74408. },
  74409. enumerable: true,
  74410. configurable: true
  74411. });
  74412. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  74413. /**
  74414. * Gets wether or not the blur is unpacking/repacking floats
  74415. */
  74416. get: function () {
  74417. return this._packedFloat;
  74418. },
  74419. /**
  74420. * Sets wether or not the blur needs to unpack/repack floats
  74421. */
  74422. set: function (v) {
  74423. if (this._packedFloat === v) {
  74424. return;
  74425. }
  74426. this._packedFloat = v;
  74427. if (!this.blockCompilation) {
  74428. this._updateParameters();
  74429. }
  74430. },
  74431. enumerable: true,
  74432. configurable: true
  74433. });
  74434. /**
  74435. * Updates the effect with the current post process compile time values and recompiles the shader.
  74436. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  74437. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  74438. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  74439. * @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
  74440. * @param onCompiled Called when the shader has been compiled.
  74441. * @param onError Called if there is an error when compiling a shader.
  74442. */
  74443. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  74444. if (defines === void 0) { defines = null; }
  74445. if (uniforms === void 0) { uniforms = null; }
  74446. if (samplers === void 0) { samplers = null; }
  74447. this._updateParameters(onCompiled, onError);
  74448. };
  74449. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  74450. // Generate sampling offsets and weights
  74451. var N = this._kernel;
  74452. var centerIndex = (N - 1) / 2;
  74453. // Generate Gaussian sampling weights over kernel
  74454. var offsets = [];
  74455. var weights = [];
  74456. var totalWeight = 0;
  74457. for (var i = 0; i < N; i++) {
  74458. var u = i / (N - 1);
  74459. var w = this._gaussianWeight(u * 2.0 - 1);
  74460. offsets[i] = (i - centerIndex);
  74461. weights[i] = w;
  74462. totalWeight += w;
  74463. }
  74464. // Normalize weights
  74465. for (var i = 0; i < weights.length; i++) {
  74466. weights[i] /= totalWeight;
  74467. }
  74468. // Optimize: combine samples to take advantage of hardware linear sampling
  74469. // Walk from left to center, combining pairs (symmetrically)
  74470. var linearSamplingWeights = [];
  74471. var linearSamplingOffsets = [];
  74472. var linearSamplingMap = [];
  74473. for (var i = 0; i <= centerIndex; i += 2) {
  74474. var j = Math.min(i + 1, Math.floor(centerIndex));
  74475. var singleCenterSample = i === j;
  74476. if (singleCenterSample) {
  74477. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  74478. }
  74479. else {
  74480. var sharedCell = j === centerIndex;
  74481. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  74482. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  74483. if (offsetLinear === 0) {
  74484. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  74485. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  74486. }
  74487. else {
  74488. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  74489. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  74490. }
  74491. }
  74492. }
  74493. for (var i = 0; i < linearSamplingMap.length; i++) {
  74494. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  74495. linearSamplingWeights[i] = linearSamplingMap[i].w;
  74496. }
  74497. // Replace with optimized
  74498. offsets = linearSamplingOffsets;
  74499. weights = linearSamplingWeights;
  74500. // Generate shaders
  74501. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  74502. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  74503. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  74504. var defines = "";
  74505. defines += this._staticDefines;
  74506. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  74507. if (this._staticDefines.indexOf("DOF") != -1) {
  74508. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  74509. varyingCount--;
  74510. }
  74511. for (var i = 0; i < varyingCount; i++) {
  74512. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  74513. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  74514. }
  74515. var depCount = 0;
  74516. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  74517. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  74518. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  74519. depCount++;
  74520. }
  74521. if (this.packedFloat) {
  74522. defines += "#define PACKEDFLOAT 1";
  74523. }
  74524. this.blockCompilation = false;
  74525. _super.prototype.updateEffect.call(this, defines, null, null, {
  74526. varyingCount: varyingCount,
  74527. depCount: depCount
  74528. }, onCompiled, onError);
  74529. };
  74530. /**
  74531. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  74532. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  74533. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  74534. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  74535. * The gaps between physical kernels are compensated for in the weighting of the samples
  74536. * @param idealKernel Ideal blur kernel.
  74537. * @return Nearest best kernel.
  74538. */
  74539. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  74540. var v = Math.round(idealKernel);
  74541. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  74542. var k = _a[_i];
  74543. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  74544. return Math.max(k, 3);
  74545. }
  74546. }
  74547. return Math.max(v, 3);
  74548. };
  74549. /**
  74550. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  74551. * @param x The point on the Gaussian distribution to sample.
  74552. * @return the value of the Gaussian function at x.
  74553. */
  74554. BlurPostProcess.prototype._gaussianWeight = function (x) {
  74555. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  74556. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  74557. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  74558. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  74559. // truncated at around 1.3% of peak strength.
  74560. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  74561. var sigma = (1 / 3);
  74562. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  74563. var exponent = -((x * x) / (2.0 * sigma * sigma));
  74564. var weight = (1.0 / denominator) * Math.exp(exponent);
  74565. return weight;
  74566. };
  74567. /**
  74568. * Generates a string that can be used as a floating point number in GLSL.
  74569. * @param x Value to print.
  74570. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  74571. * @return GLSL float string.
  74572. */
  74573. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  74574. if (decimalFigures === void 0) { decimalFigures = 8; }
  74575. return x.toFixed(decimalFigures).replace(/0+$/, '');
  74576. };
  74577. return BlurPostProcess;
  74578. }(BABYLON.PostProcess));
  74579. BABYLON.BlurPostProcess = BlurPostProcess;
  74580. })(BABYLON || (BABYLON = {}));
  74581. //# sourceMappingURL=babylon.blurPostProcess.js.map
  74582. var BABYLON;
  74583. (function (BABYLON) {
  74584. /**
  74585. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  74586. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  74587. * based on samples that have a large difference in distance than the center pixel.
  74588. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  74589. */
  74590. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  74591. __extends(DepthOfFieldBlurPostProcess, _super);
  74592. /**
  74593. * Creates a new instance CircleOfConfusionPostProcess
  74594. * @param name The name of the effect.
  74595. * @param scene The scene the effect belongs to.
  74596. * @param direction The direction the blur should be applied.
  74597. * @param kernel The size of the kernel used to blur.
  74598. * @param options The required width/height ratio to downsize to before computing the render pass.
  74599. * @param camera The camera to apply the render pass to.
  74600. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  74601. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  74602. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74603. * @param engine The engine which the post process will be applied. (default: current engine)
  74604. * @param reusable If the post process can be reused on the same frame. (default: false)
  74605. * @param textureType Type of textures used when performing the post process. (default: 0)
  74606. * @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)
  74607. */
  74608. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  74609. if (imageToBlur === void 0) { imageToBlur = null; }
  74610. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  74611. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74612. if (blockCompilation === void 0) { blockCompilation = false; }
  74613. 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;
  74614. _this.direction = direction;
  74615. _this.onApplyObservable.add(function (effect) {
  74616. if (imageToBlur != null) {
  74617. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  74618. }
  74619. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  74620. if (scene.activeCamera) {
  74621. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  74622. }
  74623. });
  74624. return _this;
  74625. }
  74626. return DepthOfFieldBlurPostProcess;
  74627. }(BABYLON.BlurPostProcess));
  74628. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  74629. })(BABYLON || (BABYLON = {}));
  74630. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  74631. var BABYLON;
  74632. (function (BABYLON) {
  74633. /**
  74634. * Options to be set when merging outputs from the default pipeline.
  74635. */
  74636. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  74637. function DepthOfFieldMergePostProcessOptions() {
  74638. }
  74639. return DepthOfFieldMergePostProcessOptions;
  74640. }());
  74641. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  74642. /**
  74643. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  74644. */
  74645. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  74646. __extends(DepthOfFieldMergePostProcess, _super);
  74647. /**
  74648. * Creates a new instance of DepthOfFieldMergePostProcess
  74649. * @param name The name of the effect.
  74650. * @param originalFromInput Post process which's input will be used for the merge.
  74651. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  74652. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  74653. * @param options The required width/height ratio to downsize to before computing the render pass.
  74654. * @param camera The camera to apply the render pass to.
  74655. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74656. * @param engine The engine which the post process will be applied. (default: current engine)
  74657. * @param reusable If the post process can be reused on the same frame. (default: false)
  74658. * @param textureType Type of textures used when performing the post process. (default: 0)
  74659. * @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)
  74660. */
  74661. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74662. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74663. if (blockCompilation === void 0) { blockCompilation = false; }
  74664. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  74665. _this.blurSteps = blurSteps;
  74666. _this.onApplyObservable.add(function (effect) {
  74667. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  74668. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  74669. blurSteps.forEach(function (step, index) {
  74670. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  74671. });
  74672. });
  74673. if (!blockCompilation) {
  74674. _this.updateEffect();
  74675. }
  74676. return _this;
  74677. }
  74678. /**
  74679. * Updates the effect with the current post process compile time values and recompiles the shader.
  74680. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  74681. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  74682. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  74683. * @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
  74684. * @param onCompiled Called when the shader has been compiled.
  74685. * @param onError Called if there is an error when compiling a shader.
  74686. */
  74687. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  74688. if (defines === void 0) { defines = null; }
  74689. if (uniforms === void 0) { uniforms = null; }
  74690. if (samplers === void 0) { samplers = null; }
  74691. if (!defines) {
  74692. defines = "";
  74693. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  74694. }
  74695. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  74696. };
  74697. return DepthOfFieldMergePostProcess;
  74698. }(BABYLON.PostProcess));
  74699. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  74700. })(BABYLON || (BABYLON = {}));
  74701. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  74702. var BABYLON;
  74703. (function (BABYLON) {
  74704. /**
  74705. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  74706. */
  74707. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  74708. __extends(CircleOfConfusionPostProcess, _super);
  74709. /**
  74710. * Creates a new instance CircleOfConfusionPostProcess
  74711. * @param name The name of the effect.
  74712. * @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.
  74713. * @param options The required width/height ratio to downsize to before computing the render pass.
  74714. * @param camera The camera to apply the render pass to.
  74715. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74716. * @param engine The engine which the post process will be applied. (default: current engine)
  74717. * @param reusable If the post process can be reused on the same frame. (default: false)
  74718. * @param textureType Type of textures used when performing the post process. (default: 0)
  74719. * @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)
  74720. */
  74721. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74722. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74723. if (blockCompilation === void 0) { blockCompilation = false; }
  74724. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  74725. /**
  74726. * 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.
  74727. */
  74728. _this.lensSize = 50;
  74729. /**
  74730. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  74731. */
  74732. _this.fStop = 1.4;
  74733. /**
  74734. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  74735. */
  74736. _this.focusDistance = 2000;
  74737. /**
  74738. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  74739. */
  74740. _this.focalLength = 50;
  74741. _this._depthTexture = null;
  74742. _this._depthTexture = depthTexture;
  74743. _this.onApplyObservable.add(function (effect) {
  74744. if (!_this._depthTexture) {
  74745. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  74746. return;
  74747. }
  74748. effect.setTexture("depthSampler", _this._depthTexture);
  74749. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  74750. var aperture = _this.lensSize / _this.fStop;
  74751. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  74752. effect.setFloat('focusDistance', _this.focusDistance);
  74753. effect.setFloat('cocPrecalculation', cocPrecalculation);
  74754. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  74755. });
  74756. return _this;
  74757. }
  74758. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  74759. /**
  74760. * 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.
  74761. */
  74762. set: function (value) {
  74763. this._depthTexture = value;
  74764. },
  74765. enumerable: true,
  74766. configurable: true
  74767. });
  74768. return CircleOfConfusionPostProcess;
  74769. }(BABYLON.PostProcess));
  74770. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  74771. })(BABYLON || (BABYLON = {}));
  74772. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  74773. var BABYLON;
  74774. (function (BABYLON) {
  74775. /**
  74776. * Specifies the level of max blur that should be applied when using the depth of field effect
  74777. */
  74778. var DepthOfFieldEffectBlurLevel;
  74779. (function (DepthOfFieldEffectBlurLevel) {
  74780. /**
  74781. * Subtle blur
  74782. */
  74783. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  74784. /**
  74785. * Medium blur
  74786. */
  74787. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  74788. /**
  74789. * Large blur
  74790. */
  74791. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  74792. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  74793. ;
  74794. /**
  74795. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  74796. */
  74797. var DepthOfFieldEffect = /** @class */ (function (_super) {
  74798. __extends(DepthOfFieldEffect, _super);
  74799. /**
  74800. * Creates a new instance DepthOfFieldEffect
  74801. * @param scene The scene the effect belongs to.
  74802. * @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.
  74803. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  74804. * @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)
  74805. */
  74806. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  74807. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  74808. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  74809. if (blockCompilation === void 0) { blockCompilation = false; }
  74810. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  74811. return _this._effects;
  74812. }, true) || this;
  74813. /**
  74814. * Internal post processes in depth of field effect
  74815. */
  74816. _this._effects = [];
  74817. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  74818. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  74819. // 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)
  74820. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  74821. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  74822. _this._depthOfFieldBlurY = [];
  74823. _this._depthOfFieldBlurX = [];
  74824. var blurCount = 1;
  74825. var kernelSize = 15;
  74826. switch (blurLevel) {
  74827. case DepthOfFieldEffectBlurLevel.High: {
  74828. blurCount = 3;
  74829. kernelSize = 51;
  74830. break;
  74831. }
  74832. case DepthOfFieldEffectBlurLevel.Medium: {
  74833. blurCount = 2;
  74834. kernelSize = 31;
  74835. break;
  74836. }
  74837. default: {
  74838. kernelSize = 15;
  74839. blurCount = 1;
  74840. break;
  74841. }
  74842. }
  74843. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  74844. var ratio = 1.0;
  74845. for (var i = 0; i < blurCount; i++) {
  74846. 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);
  74847. blurY.autoClear = false;
  74848. ratio = 0.75 / Math.pow(2, i);
  74849. 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);
  74850. blurX.autoClear = false;
  74851. _this._depthOfFieldBlurY.push(blurY);
  74852. _this._depthOfFieldBlurX.push(blurX);
  74853. }
  74854. // Set all post processes on the effect.
  74855. _this._effects = [_this._circleOfConfusion];
  74856. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  74857. _this._effects.push(_this._depthOfFieldBlurY[i]);
  74858. _this._effects.push(_this._depthOfFieldBlurX[i]);
  74859. }
  74860. // Merge blurred images with original image based on circleOfConfusion
  74861. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  74862. _this._dofMerge.autoClear = false;
  74863. _this._effects.push(_this._dofMerge);
  74864. return _this;
  74865. }
  74866. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  74867. get: function () {
  74868. return this._circleOfConfusion.focalLength;
  74869. },
  74870. /**
  74871. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  74872. */
  74873. set: function (value) {
  74874. this._circleOfConfusion.focalLength = value;
  74875. },
  74876. enumerable: true,
  74877. configurable: true
  74878. });
  74879. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  74880. get: function () {
  74881. return this._circleOfConfusion.fStop;
  74882. },
  74883. /**
  74884. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  74885. */
  74886. set: function (value) {
  74887. this._circleOfConfusion.fStop = value;
  74888. },
  74889. enumerable: true,
  74890. configurable: true
  74891. });
  74892. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  74893. get: function () {
  74894. return this._circleOfConfusion.focusDistance;
  74895. },
  74896. /**
  74897. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  74898. */
  74899. set: function (value) {
  74900. this._circleOfConfusion.focusDistance = value;
  74901. },
  74902. enumerable: true,
  74903. configurable: true
  74904. });
  74905. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  74906. get: function () {
  74907. return this._circleOfConfusion.lensSize;
  74908. },
  74909. /**
  74910. * 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.
  74911. */
  74912. set: function (value) {
  74913. this._circleOfConfusion.lensSize = value;
  74914. },
  74915. enumerable: true,
  74916. configurable: true
  74917. });
  74918. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  74919. /**
  74920. * 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.
  74921. */
  74922. set: function (value) {
  74923. this._circleOfConfusion.depthTexture = value;
  74924. },
  74925. enumerable: true,
  74926. configurable: true
  74927. });
  74928. /**
  74929. * Disposes each of the internal effects for a given camera.
  74930. * @param camera The camera to dispose the effect on.
  74931. */
  74932. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  74933. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  74934. this._effects[effectIndex].dispose(camera);
  74935. }
  74936. };
  74937. /**
  74938. * Internal
  74939. */
  74940. DepthOfFieldEffect.prototype._updateEffects = function () {
  74941. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  74942. this._effects[effectIndex].updateEffect();
  74943. }
  74944. };
  74945. /**
  74946. * Internal
  74947. * @returns if all the contained post processes are ready.
  74948. */
  74949. DepthOfFieldEffect.prototype._isReady = function () {
  74950. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  74951. if (!this._effects[effectIndex].isReady()) {
  74952. return false;
  74953. }
  74954. }
  74955. return true;
  74956. };
  74957. return DepthOfFieldEffect;
  74958. }(BABYLON.PostProcessRenderEffect));
  74959. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  74960. })(BABYLON || (BABYLON = {}));
  74961. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  74962. var BABYLON;
  74963. (function (BABYLON) {
  74964. /**
  74965. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  74966. */
  74967. var BloomMergePostProcess = /** @class */ (function (_super) {
  74968. __extends(BloomMergePostProcess, _super);
  74969. /**
  74970. * Creates a new instance of @see BloomMergePostProcess
  74971. * @param name The name of the effect.
  74972. * @param originalFromInput Post process which's input will be used for the merge.
  74973. * @param blurred Blurred highlights post process which's output will be used.
  74974. * @param weight Weight of the bloom to be added to the original input.
  74975. * @param options The required width/height ratio to downsize to before computing the render pass.
  74976. * @param camera The camera to apply the render pass to.
  74977. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74978. * @param engine The engine which the post process will be applied. (default: current engine)
  74979. * @param reusable If the post process can be reused on the same frame. (default: false)
  74980. * @param textureType Type of textures used when performing the post process. (default: 0)
  74981. * @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)
  74982. */
  74983. function BloomMergePostProcess(name, originalFromInput, blurred, /** Weight of the bloom to be added to the original input. */ weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74984. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74985. if (blockCompilation === void 0) { blockCompilation = false; }
  74986. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  74987. _this.weight = weight;
  74988. _this.onApplyObservable.add(function (effect) {
  74989. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  74990. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  74991. effect.setFloat("bloomWeight", _this.weight);
  74992. });
  74993. if (!blockCompilation) {
  74994. _this.updateEffect();
  74995. }
  74996. return _this;
  74997. }
  74998. return BloomMergePostProcess;
  74999. }(BABYLON.PostProcess));
  75000. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  75001. })(BABYLON || (BABYLON = {}));
  75002. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  75003. var BABYLON;
  75004. (function (BABYLON) {
  75005. /**
  75006. * 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.
  75007. */
  75008. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  75009. __extends(ExtractHighlightsPostProcess, _super);
  75010. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75011. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75012. if (blockCompilation === void 0) { blockCompilation = false; }
  75013. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75014. /**
  75015. * The luminance threshold, pixels below this value will be set to black.
  75016. */
  75017. _this.threshold = 0.9;
  75018. /**
  75019. * Internal
  75020. */
  75021. _this._exposure = 1;
  75022. /**
  75023. * Post process which has the input texture to be used when performing highlight extraction
  75024. */
  75025. _this._inputPostProcess = null;
  75026. _this.onApplyObservable.add(function (effect) {
  75027. if (_this._inputPostProcess) {
  75028. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  75029. }
  75030. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  75031. effect.setFloat('exposure', _this._exposure);
  75032. });
  75033. return _this;
  75034. }
  75035. return ExtractHighlightsPostProcess;
  75036. }(BABYLON.PostProcess));
  75037. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  75038. })(BABYLON || (BABYLON = {}));
  75039. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  75040. var BABYLON;
  75041. (function (BABYLON) {
  75042. /**
  75043. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  75044. */
  75045. var BloomEffect = /** @class */ (function (_super) {
  75046. __extends(BloomEffect, _super);
  75047. /**
  75048. * Creates a new instance of @see BloomEffect
  75049. * @param scene The scene the effect belongs to.
  75050. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  75051. * @param bloomKernel The size of the kernel to be used when applying the blur.
  75052. * @param bloomWeight The the strength of bloom.
  75053. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  75054. * @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)
  75055. */
  75056. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  75057. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  75058. if (blockCompilation === void 0) { blockCompilation = false; }
  75059. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  75060. return _this._effects;
  75061. }, true) || this;
  75062. _this.bloomScale = bloomScale;
  75063. /**
  75064. * Internal
  75065. */
  75066. _this._effects = [];
  75067. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75068. _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);
  75069. _this._blurX.alwaysForcePOT = true;
  75070. _this._blurX.autoClear = false;
  75071. _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);
  75072. _this._blurY.alwaysForcePOT = true;
  75073. _this._blurY.autoClear = false;
  75074. _this.kernel = bloomKernel;
  75075. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  75076. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75077. _this._merge.autoClear = false;
  75078. _this._effects.push(_this._merge);
  75079. return _this;
  75080. }
  75081. Object.defineProperty(BloomEffect.prototype, "threshold", {
  75082. /**
  75083. * The luminance threshold to find bright areas of the image to bloom.
  75084. */
  75085. get: function () {
  75086. return this._downscale.threshold;
  75087. },
  75088. set: function (value) {
  75089. this._downscale.threshold = value;
  75090. },
  75091. enumerable: true,
  75092. configurable: true
  75093. });
  75094. Object.defineProperty(BloomEffect.prototype, "weight", {
  75095. /**
  75096. * The strength of the bloom.
  75097. */
  75098. get: function () {
  75099. return this._merge.weight;
  75100. },
  75101. set: function (value) {
  75102. this._merge.weight = value;
  75103. },
  75104. enumerable: true,
  75105. configurable: true
  75106. });
  75107. Object.defineProperty(BloomEffect.prototype, "kernel", {
  75108. /**
  75109. * Specifies the size of the bloom blur kernel, relative to the final output size
  75110. */
  75111. get: function () {
  75112. return this._blurX.kernel / this.bloomScale;
  75113. },
  75114. set: function (value) {
  75115. this._blurX.kernel = value * this.bloomScale;
  75116. this._blurY.kernel = value * this.bloomScale;
  75117. },
  75118. enumerable: true,
  75119. configurable: true
  75120. });
  75121. /**
  75122. * Disposes each of the internal effects for a given camera.
  75123. * @param camera The camera to dispose the effect on.
  75124. */
  75125. BloomEffect.prototype.disposeEffects = function (camera) {
  75126. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75127. this._effects[effectIndex].dispose(camera);
  75128. }
  75129. };
  75130. /**
  75131. * Internal
  75132. */
  75133. BloomEffect.prototype._updateEffects = function () {
  75134. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75135. this._effects[effectIndex].updateEffect();
  75136. }
  75137. };
  75138. /**
  75139. * Internal
  75140. * @returns if all the contained post processes are ready.
  75141. */
  75142. BloomEffect.prototype._isReady = function () {
  75143. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75144. if (!this._effects[effectIndex].isReady()) {
  75145. return false;
  75146. }
  75147. }
  75148. return true;
  75149. };
  75150. return BloomEffect;
  75151. }(BABYLON.PostProcessRenderEffect));
  75152. BABYLON.BloomEffect = BloomEffect;
  75153. })(BABYLON || (BABYLON = {}));
  75154. //# sourceMappingURL=babylon.bloomEffect.js.map
  75155. var BABYLON;
  75156. (function (BABYLON) {
  75157. /**
  75158. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  75159. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  75160. */
  75161. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  75162. __extends(DefaultRenderingPipeline, _super);
  75163. /**
  75164. * @constructor
  75165. * @param {string} name - The rendering pipeline name (default: "")
  75166. * @param {boolean} hdr - If high dynamic range textures should be used (default: true)
  75167. * @param {BABYLON.Scene} scene - The scene linked to this pipeline (default: the last created scene)
  75168. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to (default: scene.cameras)
  75169. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline (default: true)
  75170. */
  75171. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  75172. if (name === void 0) { name = ""; }
  75173. if (hdr === void 0) { hdr = true; }
  75174. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  75175. if (automaticBuild === void 0) { automaticBuild = true; }
  75176. var _this = _super.call(this, scene.getEngine(), name) || this;
  75177. _this._originalCameras = [];
  75178. /**
  75179. * ID of the sharpen post process,
  75180. */
  75181. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  75182. /**
  75183. * ID of the image processing post process;
  75184. */
  75185. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  75186. /**
  75187. * ID of the Fast Approximate Anti-Aliasing post process;
  75188. */
  75189. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  75190. /**
  75191. * ID of the chromatic aberration post process,
  75192. */
  75193. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  75194. /**
  75195. * ID of the grain post process
  75196. */
  75197. _this.GrainPostProcessId = "GrainPostProcessEffect";
  75198. /**
  75199. * Glow post process which adds a glow to emmisive areas of the image
  75200. */
  75201. _this._glowLayer = null;
  75202. /**
  75203. * Animations which can be used to tweak settings over a period of time
  75204. */
  75205. _this.animations = [];
  75206. _this._imageProcessingConfigurationObserver = null;
  75207. // Values
  75208. _this._sharpenEnabled = false;
  75209. _this._bloomEnabled = false;
  75210. _this._depthOfFieldEnabled = false;
  75211. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  75212. _this._fxaaEnabled = false;
  75213. _this._imageProcessingEnabled = true;
  75214. _this._bloomScale = 0.5;
  75215. _this._chromaticAberrationEnabled = false;
  75216. _this._grainEnabled = false;
  75217. _this._buildAllowed = true;
  75218. _this._resizeObserver = null;
  75219. _this._hardwareScaleLevel = 1.0;
  75220. _this._bloomKernel = 64;
  75221. /**
  75222. * Specifies the weight of the bloom in the final rendering
  75223. */
  75224. _this._bloomWeight = 0.15;
  75225. /**
  75226. * Specifies the luma threshold for the area that will be blurred by the bloom
  75227. */
  75228. _this._bloomThreshold = 0.9;
  75229. _this._samples = 1;
  75230. _this._hasCleared = false;
  75231. _this._prevPostProcess = null;
  75232. _this._prevPrevPostProcess = null;
  75233. _this._cameras = cameras || scene.cameras;
  75234. _this._originalCameras = _this._cameras.slice();
  75235. _this._buildAllowed = automaticBuild;
  75236. // Initialize
  75237. _this._scene = scene;
  75238. var caps = _this._scene.getEngine().getCaps();
  75239. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  75240. // Misc
  75241. if (_this._hdr) {
  75242. if (caps.textureHalfFloatRender) {
  75243. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  75244. }
  75245. else if (caps.textureFloatRender) {
  75246. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  75247. }
  75248. }
  75249. else {
  75250. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  75251. }
  75252. // Attach
  75253. scene.postProcessRenderPipelineManager.addPipeline(_this);
  75254. var engine = _this._scene.getEngine();
  75255. // Create post processes before hand so they can be modified before enabled.
  75256. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  75257. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  75258. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  75259. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  75260. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  75261. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  75262. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  75263. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  75264. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  75265. _this._resizeObserver = engine.onResizeObservable.add(function () {
  75266. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  75267. _this.bloomKernel = _this.bloomKernel;
  75268. });
  75269. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  75270. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  75271. });
  75272. _this._buildPipeline();
  75273. return _this;
  75274. }
  75275. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  75276. get: function () {
  75277. return this._sharpenEnabled;
  75278. },
  75279. /**
  75280. * Enable or disable the sharpen process from the pipeline
  75281. */
  75282. set: function (enabled) {
  75283. if (this._sharpenEnabled === enabled) {
  75284. return;
  75285. }
  75286. this._sharpenEnabled = enabled;
  75287. this._buildPipeline();
  75288. },
  75289. enumerable: true,
  75290. configurable: true
  75291. });
  75292. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  75293. /**
  75294. * Specifies the size of the bloom blur kernel, relative to the final output size
  75295. */
  75296. get: function () {
  75297. return this._bloomKernel;
  75298. },
  75299. set: function (value) {
  75300. this._bloomKernel = value;
  75301. this.bloom.kernel = value / this._hardwareScaleLevel;
  75302. },
  75303. enumerable: true,
  75304. configurable: true
  75305. });
  75306. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  75307. get: function () {
  75308. return this._bloomWeight;
  75309. },
  75310. /**
  75311. * The strength of the bloom.
  75312. */
  75313. set: function (value) {
  75314. if (this._bloomWeight === value) {
  75315. return;
  75316. }
  75317. this.bloom.weight = value;
  75318. this._bloomWeight = value;
  75319. },
  75320. enumerable: true,
  75321. configurable: true
  75322. });
  75323. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  75324. get: function () {
  75325. return this._bloomThreshold;
  75326. },
  75327. /**
  75328. * The strength of the bloom.
  75329. */
  75330. set: function (value) {
  75331. if (this._bloomThreshold === value) {
  75332. return;
  75333. }
  75334. this.bloom.threshold = value;
  75335. this._bloomThreshold = value;
  75336. },
  75337. enumerable: true,
  75338. configurable: true
  75339. });
  75340. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  75341. get: function () {
  75342. return this._bloomScale;
  75343. },
  75344. /**
  75345. * The scale of the bloom, lower value will provide better performance.
  75346. */
  75347. set: function (value) {
  75348. if (this._bloomScale === value) {
  75349. return;
  75350. }
  75351. this._bloomScale = value;
  75352. // recreate bloom and dispose old as this setting is not dynamic
  75353. this._rebuildBloom();
  75354. this._buildPipeline();
  75355. },
  75356. enumerable: true,
  75357. configurable: true
  75358. });
  75359. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  75360. get: function () {
  75361. return this._bloomEnabled;
  75362. },
  75363. /**
  75364. * Enable or disable the bloom from the pipeline
  75365. */
  75366. set: function (enabled) {
  75367. if (this._bloomEnabled === enabled) {
  75368. return;
  75369. }
  75370. this._bloomEnabled = enabled;
  75371. this._buildPipeline();
  75372. },
  75373. enumerable: true,
  75374. configurable: true
  75375. });
  75376. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  75377. // recreate bloom and dispose old as this setting is not dynamic
  75378. var oldBloom = this.bloom;
  75379. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  75380. this.bloom.threshold = oldBloom.threshold;
  75381. for (var i = 0; i < this._cameras.length; i++) {
  75382. oldBloom.disposeEffects(this._cameras[i]);
  75383. }
  75384. };
  75385. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  75386. /**
  75387. * If the depth of field is enabled.
  75388. */
  75389. get: function () {
  75390. return this._depthOfFieldEnabled;
  75391. },
  75392. set: function (enabled) {
  75393. if (this._depthOfFieldEnabled === enabled) {
  75394. return;
  75395. }
  75396. this._depthOfFieldEnabled = enabled;
  75397. this._buildPipeline();
  75398. },
  75399. enumerable: true,
  75400. configurable: true
  75401. });
  75402. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  75403. /**
  75404. * Blur level of the depth of field effect. (Higher blur will effect performance)
  75405. */
  75406. get: function () {
  75407. return this._depthOfFieldBlurLevel;
  75408. },
  75409. set: function (value) {
  75410. if (this._depthOfFieldBlurLevel === value) {
  75411. return;
  75412. }
  75413. this._depthOfFieldBlurLevel = value;
  75414. // recreate dof and dispose old as this setting is not dynamic
  75415. var oldDof = this.depthOfField;
  75416. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  75417. this.depthOfField.focalLength = oldDof.focalLength;
  75418. this.depthOfField.focusDistance = oldDof.focusDistance;
  75419. this.depthOfField.fStop = oldDof.fStop;
  75420. this.depthOfField.lensSize = oldDof.lensSize;
  75421. for (var i = 0; i < this._cameras.length; i++) {
  75422. oldDof.disposeEffects(this._cameras[i]);
  75423. }
  75424. this._buildPipeline();
  75425. },
  75426. enumerable: true,
  75427. configurable: true
  75428. });
  75429. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  75430. get: function () {
  75431. return this._fxaaEnabled;
  75432. },
  75433. /**
  75434. * If the anti aliasing is enabled.
  75435. */
  75436. set: function (enabled) {
  75437. if (this._fxaaEnabled === enabled) {
  75438. return;
  75439. }
  75440. this._fxaaEnabled = enabled;
  75441. this._buildPipeline();
  75442. },
  75443. enumerable: true,
  75444. configurable: true
  75445. });
  75446. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  75447. get: function () {
  75448. return this._samples;
  75449. },
  75450. /**
  75451. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  75452. */
  75453. set: function (sampleCount) {
  75454. if (this._samples === sampleCount) {
  75455. return;
  75456. }
  75457. this._samples = sampleCount;
  75458. this._buildPipeline();
  75459. },
  75460. enumerable: true,
  75461. configurable: true
  75462. });
  75463. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  75464. get: function () {
  75465. return this._imageProcessingEnabled;
  75466. },
  75467. /**
  75468. * If image processing is enabled.
  75469. */
  75470. set: function (enabled) {
  75471. if (this._imageProcessingEnabled === enabled) {
  75472. return;
  75473. }
  75474. this._imageProcessingEnabled = enabled;
  75475. this._buildPipeline();
  75476. },
  75477. enumerable: true,
  75478. configurable: true
  75479. });
  75480. Object.defineProperty(DefaultRenderingPipeline.prototype, "glowLayerEnabled", {
  75481. get: function () {
  75482. return this._glowLayer == null;
  75483. },
  75484. /**
  75485. * If glow layer is enabled. (Adds a glow effect to emmissive materials)
  75486. */
  75487. set: function (enabled) {
  75488. if (enabled && !this._glowLayer) {
  75489. this._glowLayer = new BABYLON.GlowLayer("", this._scene);
  75490. }
  75491. else if (!enabled && this._glowLayer) {
  75492. this._glowLayer.dispose();
  75493. this._glowLayer = null;
  75494. }
  75495. },
  75496. enumerable: true,
  75497. configurable: true
  75498. });
  75499. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  75500. get: function () {
  75501. return this._chromaticAberrationEnabled;
  75502. },
  75503. /**
  75504. * Enable or disable the chromaticAberration process from the pipeline
  75505. */
  75506. set: function (enabled) {
  75507. if (this._chromaticAberrationEnabled === enabled) {
  75508. return;
  75509. }
  75510. this._chromaticAberrationEnabled = enabled;
  75511. this._buildPipeline();
  75512. },
  75513. enumerable: true,
  75514. configurable: true
  75515. });
  75516. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  75517. get: function () {
  75518. return this._grainEnabled;
  75519. },
  75520. /**
  75521. * Enable or disable the grain process from the pipeline
  75522. */
  75523. set: function (enabled) {
  75524. if (this._grainEnabled === enabled) {
  75525. return;
  75526. }
  75527. this._grainEnabled = enabled;
  75528. this._buildPipeline();
  75529. },
  75530. enumerable: true,
  75531. configurable: true
  75532. });
  75533. /**
  75534. * Force the compilation of the entire pipeline.
  75535. */
  75536. DefaultRenderingPipeline.prototype.prepare = function () {
  75537. var previousState = this._buildAllowed;
  75538. this._buildAllowed = true;
  75539. this._buildPipeline();
  75540. this._buildAllowed = previousState;
  75541. };
  75542. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  75543. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  75544. if (this._hasCleared) {
  75545. postProcess.autoClear = false;
  75546. }
  75547. else {
  75548. postProcess.autoClear = true;
  75549. this._scene.autoClear = false;
  75550. this._hasCleared = true;
  75551. }
  75552. if (!skipTextureSharing) {
  75553. if (this._prevPrevPostProcess) {
  75554. postProcess.shareOutputWith(this._prevPrevPostProcess);
  75555. }
  75556. else {
  75557. postProcess.useOwnOutput();
  75558. }
  75559. if (this._prevPostProcess) {
  75560. this._prevPrevPostProcess = this._prevPostProcess;
  75561. }
  75562. this._prevPostProcess = postProcess;
  75563. }
  75564. };
  75565. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  75566. var _this = this;
  75567. if (!this._buildAllowed) {
  75568. return;
  75569. }
  75570. this._scene.autoClear = true;
  75571. var engine = this._scene.getEngine();
  75572. this._disposePostProcesses();
  75573. if (this._cameras !== null) {
  75574. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  75575. // get back cameras to be used to reattach pipeline
  75576. this._cameras = this._originalCameras.slice();
  75577. }
  75578. this._reset();
  75579. this._prevPostProcess = null;
  75580. this._prevPrevPostProcess = null;
  75581. this._hasCleared = false;
  75582. if (this.depthOfFieldEnabled) {
  75583. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  75584. this.depthOfField.depthTexture = depthTexture;
  75585. if (!this.depthOfField._isReady()) {
  75586. this.depthOfField._updateEffects();
  75587. }
  75588. this.addEffect(this.depthOfField);
  75589. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  75590. }
  75591. if (this.bloomEnabled) {
  75592. if (!this.bloom._isReady()) {
  75593. this.bloom._updateEffects();
  75594. }
  75595. this.addEffect(this.bloom);
  75596. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  75597. }
  75598. if (this._imageProcessingEnabled) {
  75599. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  75600. if (this._hdr) {
  75601. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  75602. this._setAutoClearAndTextureSharing(this.imageProcessing);
  75603. }
  75604. else {
  75605. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  75606. }
  75607. }
  75608. if (this.sharpenEnabled) {
  75609. if (!this.sharpen.isReady()) {
  75610. this.sharpen.updateEffect();
  75611. }
  75612. this.addEffect(this._sharpenEffect);
  75613. this._setAutoClearAndTextureSharing(this.sharpen);
  75614. }
  75615. if (this.grainEnabled) {
  75616. if (!this.grain.isReady()) {
  75617. this.grain.updateEffect();
  75618. }
  75619. this.addEffect(this._grainEffect);
  75620. this._setAutoClearAndTextureSharing(this.grain);
  75621. }
  75622. if (this.chromaticAberrationEnabled) {
  75623. if (!this.chromaticAberration.isReady()) {
  75624. this.chromaticAberration.updateEffect();
  75625. }
  75626. this.addEffect(this._chromaticAberrationEffect);
  75627. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  75628. }
  75629. if (this.fxaaEnabled) {
  75630. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  75631. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  75632. this._setAutoClearAndTextureSharing(this.fxaa, true);
  75633. }
  75634. if (this._cameras !== null) {
  75635. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  75636. }
  75637. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  75638. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  75639. }
  75640. };
  75641. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  75642. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  75643. for (var i = 0; i < this._cameras.length; i++) {
  75644. var camera = this._cameras[i];
  75645. if (this.imageProcessing) {
  75646. this.imageProcessing.dispose(camera);
  75647. }
  75648. if (this.fxaa) {
  75649. this.fxaa.dispose(camera);
  75650. }
  75651. // These are created in the constructor and should not be disposed on every pipeline change
  75652. if (disposeNonRecreated) {
  75653. if (this.sharpen) {
  75654. this.sharpen.dispose(camera);
  75655. }
  75656. if (this.depthOfField) {
  75657. this.depthOfField.disposeEffects(camera);
  75658. }
  75659. if (this.bloom) {
  75660. this.bloom.disposeEffects(camera);
  75661. }
  75662. if (this.chromaticAberration) {
  75663. this.chromaticAberration.dispose(camera);
  75664. }
  75665. if (this.grain) {
  75666. this.grain.dispose(camera);
  75667. }
  75668. if (this._glowLayer) {
  75669. this._glowLayer.dispose();
  75670. }
  75671. }
  75672. }
  75673. this.imageProcessing = null;
  75674. this.fxaa = null;
  75675. if (disposeNonRecreated) {
  75676. this.sharpen = null;
  75677. this._sharpenEffect = null;
  75678. this.depthOfField = null;
  75679. this.bloom = null;
  75680. this.chromaticAberration = null;
  75681. this._chromaticAberrationEffect = null;
  75682. this.grain = null;
  75683. this._grainEffect = null;
  75684. this._glowLayer = null;
  75685. }
  75686. };
  75687. /**
  75688. * Dispose of the pipeline and stop all post processes
  75689. */
  75690. DefaultRenderingPipeline.prototype.dispose = function () {
  75691. this._disposePostProcesses(true);
  75692. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  75693. this._scene.autoClear = true;
  75694. if (this._resizeObserver) {
  75695. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  75696. this._resizeObserver = null;
  75697. }
  75698. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  75699. _super.prototype.dispose.call(this);
  75700. };
  75701. /**
  75702. * Serialize the rendering pipeline (Used when exporting)
  75703. * @returns the serialized object
  75704. */
  75705. DefaultRenderingPipeline.prototype.serialize = function () {
  75706. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  75707. serializationObject.customType = "DefaultRenderingPipeline";
  75708. return serializationObject;
  75709. };
  75710. /**
  75711. * Parse the serialized pipeline
  75712. * @param source Source pipeline.
  75713. * @param scene The scene to load the pipeline to.
  75714. * @param rootUrl The URL of the serialized pipeline.
  75715. * @returns An instantiated pipeline from the serialized object.
  75716. */
  75717. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  75718. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  75719. };
  75720. __decorate([
  75721. BABYLON.serialize()
  75722. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  75723. __decorate([
  75724. BABYLON.serialize()
  75725. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  75726. __decorate([
  75727. BABYLON.serialize()
  75728. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  75729. __decorate([
  75730. BABYLON.serialize()
  75731. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  75732. __decorate([
  75733. BABYLON.serialize()
  75734. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  75735. __decorate([
  75736. BABYLON.serialize()
  75737. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  75738. __decorate([
  75739. BABYLON.serialize()
  75740. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  75741. __decorate([
  75742. BABYLON.serialize()
  75743. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  75744. __decorate([
  75745. BABYLON.serialize()
  75746. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  75747. __decorate([
  75748. BABYLON.serialize()
  75749. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  75750. __decorate([
  75751. BABYLON.serialize()
  75752. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  75753. __decorate([
  75754. BABYLON.serialize()
  75755. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  75756. __decorate([
  75757. BABYLON.serialize()
  75758. ], DefaultRenderingPipeline.prototype, "samples", null);
  75759. __decorate([
  75760. BABYLON.serialize()
  75761. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  75762. __decorate([
  75763. BABYLON.serialize()
  75764. ], DefaultRenderingPipeline.prototype, "glowLayerEnabled", null);
  75765. __decorate([
  75766. BABYLON.serialize()
  75767. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  75768. __decorate([
  75769. BABYLON.serialize()
  75770. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  75771. return DefaultRenderingPipeline;
  75772. }(BABYLON.PostProcessRenderPipeline));
  75773. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  75774. })(BABYLON || (BABYLON = {}));
  75775. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  75776. var BABYLON;
  75777. (function (BABYLON) {
  75778. /**
  75779. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  75780. */
  75781. var GeometryBufferRenderer = /** @class */ (function () {
  75782. /**
  75783. * Creates a new G Buffer for the scene
  75784. * @param scene The scene the buffer belongs to
  75785. * @param ratio How big is the buffer related to the main canvas.
  75786. */
  75787. function GeometryBufferRenderer(scene, ratio) {
  75788. if (ratio === void 0) { ratio = 1; }
  75789. this._enablePosition = false;
  75790. this._scene = scene;
  75791. this._ratio = ratio;
  75792. // Render target
  75793. this._createRenderTargets();
  75794. }
  75795. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  75796. /**
  75797. * Set the render list (meshes to be rendered) used in the G buffer.
  75798. */
  75799. set: function (meshes) {
  75800. this._multiRenderTarget.renderList = meshes;
  75801. },
  75802. enumerable: true,
  75803. configurable: true
  75804. });
  75805. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  75806. /**
  75807. * Gets wether or not G buffer are supported by the running hardware.
  75808. * This requires draw buffer supports
  75809. */
  75810. get: function () {
  75811. return this._multiRenderTarget.isSupported;
  75812. },
  75813. enumerable: true,
  75814. configurable: true
  75815. });
  75816. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  75817. /**
  75818. * Gets wether or not position are enabled for the G buffer.
  75819. */
  75820. get: function () {
  75821. return this._enablePosition;
  75822. },
  75823. /**
  75824. * Sets wether or not position are enabled for the G buffer.
  75825. */
  75826. set: function (enable) {
  75827. this._enablePosition = enable;
  75828. this.dispose();
  75829. this._createRenderTargets();
  75830. },
  75831. enumerable: true,
  75832. configurable: true
  75833. });
  75834. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  75835. /**
  75836. * Gets the scene associated with the buffer.
  75837. */
  75838. get: function () {
  75839. return this._scene;
  75840. },
  75841. enumerable: true,
  75842. configurable: true
  75843. });
  75844. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  75845. /**
  75846. * Gets the ratio used by the buffer during its creation.
  75847. * How big is the buffer related to the main canvas.
  75848. */
  75849. get: function () {
  75850. return this._ratio;
  75851. },
  75852. enumerable: true,
  75853. configurable: true
  75854. });
  75855. /**
  75856. * Checks wether everything is ready to render a submesh to the G buffer.
  75857. * @param subMesh the submesh to check readiness for
  75858. * @param useInstances is the mesh drawn using instance or not
  75859. * @returns true if ready otherwise false
  75860. */
  75861. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  75862. var material = subMesh.getMaterial();
  75863. if (material && material.disableDepthWrite) {
  75864. return false;
  75865. }
  75866. var defines = [];
  75867. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  75868. var mesh = subMesh.getMesh();
  75869. // Alpha test
  75870. if (material && material.needAlphaTesting()) {
  75871. defines.push("#define ALPHATEST");
  75872. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  75873. attribs.push(BABYLON.VertexBuffer.UVKind);
  75874. defines.push("#define UV1");
  75875. }
  75876. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  75877. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  75878. defines.push("#define UV2");
  75879. }
  75880. }
  75881. // Buffers
  75882. if (this._enablePosition) {
  75883. defines.push("#define POSITION");
  75884. }
  75885. // Bones
  75886. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  75887. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  75888. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  75889. if (mesh.numBoneInfluencers > 4) {
  75890. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  75891. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  75892. }
  75893. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  75894. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  75895. }
  75896. else {
  75897. defines.push("#define NUM_BONE_INFLUENCERS 0");
  75898. }
  75899. // Instances
  75900. if (useInstances) {
  75901. defines.push("#define INSTANCES");
  75902. attribs.push("world0");
  75903. attribs.push("world1");
  75904. attribs.push("world2");
  75905. attribs.push("world3");
  75906. }
  75907. // Get correct effect
  75908. var join = defines.join("\n");
  75909. if (this._cachedDefines !== join) {
  75910. this._cachedDefines = join;
  75911. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  75912. }
  75913. return this._effect.isReady();
  75914. };
  75915. /**
  75916. * Gets the current underlying G Buffer.
  75917. * @returns the buffer
  75918. */
  75919. GeometryBufferRenderer.prototype.getGBuffer = function () {
  75920. return this._multiRenderTarget;
  75921. };
  75922. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  75923. /**
  75924. * Gets the number of samples used to render the buffer (anti aliasing).
  75925. */
  75926. get: function () {
  75927. return this._multiRenderTarget.samples;
  75928. },
  75929. /**
  75930. * Sets the number of samples used to render the buffer (anti aliasing).
  75931. */
  75932. set: function (value) {
  75933. this._multiRenderTarget.samples = value;
  75934. },
  75935. enumerable: true,
  75936. configurable: true
  75937. });
  75938. /**
  75939. * Disposes the renderer and frees up associated resources.
  75940. */
  75941. GeometryBufferRenderer.prototype.dispose = function () {
  75942. this.getGBuffer().dispose();
  75943. };
  75944. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  75945. var _this = this;
  75946. var engine = this._scene.getEngine();
  75947. var count = this._enablePosition ? 3 : 2;
  75948. 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 });
  75949. if (!this.isSupported) {
  75950. return;
  75951. }
  75952. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75953. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75954. this._multiRenderTarget.refreshRate = 1;
  75955. this._multiRenderTarget.renderParticles = false;
  75956. this._multiRenderTarget.renderList = null;
  75957. // set default depth value to 1.0 (far away)
  75958. this._multiRenderTarget.onClearObservable.add(function (engine) {
  75959. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  75960. });
  75961. // Custom render function
  75962. var renderSubMesh = function (subMesh) {
  75963. var mesh = subMesh.getRenderingMesh();
  75964. var scene = _this._scene;
  75965. var engine = scene.getEngine();
  75966. var material = subMesh.getMaterial();
  75967. if (!material) {
  75968. return;
  75969. }
  75970. // Culling
  75971. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  75972. // Managing instances
  75973. var batch = mesh._getInstancesRenderList(subMesh._id);
  75974. if (batch.mustReturn) {
  75975. return;
  75976. }
  75977. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  75978. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  75979. engine.enableEffect(_this._effect);
  75980. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  75981. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  75982. _this._effect.setMatrix("view", scene.getViewMatrix());
  75983. // Alpha test
  75984. if (material && material.needAlphaTesting()) {
  75985. var alphaTexture = material.getAlphaTestTexture();
  75986. if (alphaTexture) {
  75987. _this._effect.setTexture("diffuseSampler", alphaTexture);
  75988. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  75989. }
  75990. }
  75991. // Bones
  75992. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  75993. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  75994. }
  75995. // Draw
  75996. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  75997. }
  75998. };
  75999. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  76000. var index;
  76001. if (depthOnlySubMeshes.length) {
  76002. engine.setColorWrite(false);
  76003. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  76004. renderSubMesh(depthOnlySubMeshes.data[index]);
  76005. }
  76006. engine.setColorWrite(true);
  76007. }
  76008. for (index = 0; index < opaqueSubMeshes.length; index++) {
  76009. renderSubMesh(opaqueSubMeshes.data[index]);
  76010. }
  76011. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  76012. renderSubMesh(alphaTestSubMeshes.data[index]);
  76013. }
  76014. };
  76015. };
  76016. return GeometryBufferRenderer;
  76017. }());
  76018. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  76019. })(BABYLON || (BABYLON = {}));
  76020. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  76021. var BABYLON;
  76022. (function (BABYLON) {
  76023. /**
  76024. * This groups together the common properties used for image processing either in direct forward pass
  76025. * or through post processing effect depending on the use of the image processing pipeline in your scene
  76026. * or not.
  76027. */
  76028. var ImageProcessingConfiguration = /** @class */ (function () {
  76029. function ImageProcessingConfiguration() {
  76030. /**
  76031. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  76032. */
  76033. this.colorCurves = new BABYLON.ColorCurves();
  76034. this._colorCurvesEnabled = false;
  76035. this._colorGradingEnabled = false;
  76036. this._colorGradingWithGreenDepth = true;
  76037. this._colorGradingBGR = true;
  76038. this._exposure = 1.0;
  76039. this._toneMappingEnabled = false;
  76040. this._contrast = 1.0;
  76041. /**
  76042. * Vignette stretch size.
  76043. */
  76044. this.vignetteStretch = 0;
  76045. /**
  76046. * Vignette centre X Offset.
  76047. */
  76048. this.vignetteCentreX = 0;
  76049. /**
  76050. * Vignette centre Y Offset.
  76051. */
  76052. this.vignetteCentreY = 0;
  76053. /**
  76054. * Vignette weight or intensity of the vignette effect.
  76055. */
  76056. this.vignetteWeight = 1.5;
  76057. /**
  76058. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  76059. * if vignetteEnabled is set to true.
  76060. */
  76061. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  76062. /**
  76063. * Camera field of view used by the Vignette effect.
  76064. */
  76065. this.vignetteCameraFov = 0.5;
  76066. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  76067. this._vignetteEnabled = false;
  76068. this._applyByPostProcess = false;
  76069. this._isEnabled = true;
  76070. /**
  76071. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  76072. */
  76073. this.onUpdateParameters = new BABYLON.Observable();
  76074. }
  76075. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  76076. /**
  76077. * Gets wether the color curves effect is enabled.
  76078. */
  76079. get: function () {
  76080. return this._colorCurvesEnabled;
  76081. },
  76082. /**
  76083. * Sets wether the color curves effect is enabled.
  76084. */
  76085. set: function (value) {
  76086. if (this._colorCurvesEnabled === value) {
  76087. return;
  76088. }
  76089. this._colorCurvesEnabled = value;
  76090. this._updateParameters();
  76091. },
  76092. enumerable: true,
  76093. configurable: true
  76094. });
  76095. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  76096. /**
  76097. * Gets wether the color grading effect is enabled.
  76098. */
  76099. get: function () {
  76100. return this._colorGradingEnabled;
  76101. },
  76102. /**
  76103. * Sets wether the color grading effect is enabled.
  76104. */
  76105. set: function (value) {
  76106. if (this._colorGradingEnabled === value) {
  76107. return;
  76108. }
  76109. this._colorGradingEnabled = value;
  76110. this._updateParameters();
  76111. },
  76112. enumerable: true,
  76113. configurable: true
  76114. });
  76115. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  76116. /**
  76117. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  76118. */
  76119. get: function () {
  76120. return this._colorGradingWithGreenDepth;
  76121. },
  76122. /**
  76123. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  76124. */
  76125. set: function (value) {
  76126. if (this._colorGradingWithGreenDepth === value) {
  76127. return;
  76128. }
  76129. this._colorGradingWithGreenDepth = value;
  76130. this._updateParameters();
  76131. },
  76132. enumerable: true,
  76133. configurable: true
  76134. });
  76135. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  76136. /**
  76137. * Gets wether the color grading texture contains BGR values.
  76138. */
  76139. get: function () {
  76140. return this._colorGradingBGR;
  76141. },
  76142. /**
  76143. * Sets wether the color grading texture contains BGR values.
  76144. */
  76145. set: function (value) {
  76146. if (this._colorGradingBGR === value) {
  76147. return;
  76148. }
  76149. this._colorGradingBGR = value;
  76150. this._updateParameters();
  76151. },
  76152. enumerable: true,
  76153. configurable: true
  76154. });
  76155. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  76156. /**
  76157. * Gets the Exposure used in the effect.
  76158. */
  76159. get: function () {
  76160. return this._exposure;
  76161. },
  76162. /**
  76163. * Sets the Exposure used in the effect.
  76164. */
  76165. set: function (value) {
  76166. if (this._exposure === value) {
  76167. return;
  76168. }
  76169. this._exposure = value;
  76170. this._updateParameters();
  76171. },
  76172. enumerable: true,
  76173. configurable: true
  76174. });
  76175. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  76176. /**
  76177. * Gets wether the tone mapping effect is enabled.
  76178. */
  76179. get: function () {
  76180. return this._toneMappingEnabled;
  76181. },
  76182. /**
  76183. * Sets wether the tone mapping effect is enabled.
  76184. */
  76185. set: function (value) {
  76186. if (this._toneMappingEnabled === value) {
  76187. return;
  76188. }
  76189. this._toneMappingEnabled = value;
  76190. this._updateParameters();
  76191. },
  76192. enumerable: true,
  76193. configurable: true
  76194. });
  76195. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  76196. /**
  76197. * Gets the contrast used in the effect.
  76198. */
  76199. get: function () {
  76200. return this._contrast;
  76201. },
  76202. /**
  76203. * Sets the contrast used in the effect.
  76204. */
  76205. set: function (value) {
  76206. if (this._contrast === value) {
  76207. return;
  76208. }
  76209. this._contrast = value;
  76210. this._updateParameters();
  76211. },
  76212. enumerable: true,
  76213. configurable: true
  76214. });
  76215. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  76216. /**
  76217. * Gets the vignette blend mode allowing different kind of effect.
  76218. */
  76219. get: function () {
  76220. return this._vignetteBlendMode;
  76221. },
  76222. /**
  76223. * Sets the vignette blend mode allowing different kind of effect.
  76224. */
  76225. set: function (value) {
  76226. if (this._vignetteBlendMode === value) {
  76227. return;
  76228. }
  76229. this._vignetteBlendMode = value;
  76230. this._updateParameters();
  76231. },
  76232. enumerable: true,
  76233. configurable: true
  76234. });
  76235. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  76236. /**
  76237. * Gets wether the vignette effect is enabled.
  76238. */
  76239. get: function () {
  76240. return this._vignetteEnabled;
  76241. },
  76242. /**
  76243. * Sets wether the vignette effect is enabled.
  76244. */
  76245. set: function (value) {
  76246. if (this._vignetteEnabled === value) {
  76247. return;
  76248. }
  76249. this._vignetteEnabled = value;
  76250. this._updateParameters();
  76251. },
  76252. enumerable: true,
  76253. configurable: true
  76254. });
  76255. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  76256. /**
  76257. * Gets wether the image processing is applied through a post process or not.
  76258. */
  76259. get: function () {
  76260. return this._applyByPostProcess;
  76261. },
  76262. /**
  76263. * Sets wether the image processing is applied through a post process or not.
  76264. */
  76265. set: function (value) {
  76266. if (this._applyByPostProcess === value) {
  76267. return;
  76268. }
  76269. this._applyByPostProcess = value;
  76270. this._updateParameters();
  76271. },
  76272. enumerable: true,
  76273. configurable: true
  76274. });
  76275. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  76276. /**
  76277. * Gets wether the image processing is enabled or not.
  76278. */
  76279. get: function () {
  76280. return this._isEnabled;
  76281. },
  76282. /**
  76283. * Sets wether the image processing is enabled or not.
  76284. */
  76285. set: function (value) {
  76286. if (this._isEnabled === value) {
  76287. return;
  76288. }
  76289. this._isEnabled = value;
  76290. this._updateParameters();
  76291. },
  76292. enumerable: true,
  76293. configurable: true
  76294. });
  76295. /**
  76296. * Method called each time the image processing information changes requires to recompile the effect.
  76297. */
  76298. ImageProcessingConfiguration.prototype._updateParameters = function () {
  76299. this.onUpdateParameters.notifyObservers(this);
  76300. };
  76301. ImageProcessingConfiguration.prototype.getClassName = function () {
  76302. return "ImageProcessingConfiguration";
  76303. };
  76304. /**
  76305. * Prepare the list of uniforms associated with the Image Processing effects.
  76306. * @param uniformsList The list of uniforms used in the effect
  76307. * @param defines the list of defines currently in use
  76308. */
  76309. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  76310. if (defines.EXPOSURE) {
  76311. uniforms.push("exposureLinear");
  76312. }
  76313. if (defines.CONTRAST) {
  76314. uniforms.push("contrast");
  76315. }
  76316. if (defines.COLORGRADING) {
  76317. uniforms.push("colorTransformSettings");
  76318. }
  76319. if (defines.VIGNETTE) {
  76320. uniforms.push("vInverseScreenSize");
  76321. uniforms.push("vignetteSettings1");
  76322. uniforms.push("vignetteSettings2");
  76323. }
  76324. if (defines.COLORCURVES) {
  76325. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  76326. }
  76327. };
  76328. /**
  76329. * Prepare the list of samplers associated with the Image Processing effects.
  76330. * @param uniformsList The list of uniforms used in the effect
  76331. * @param defines the list of defines currently in use
  76332. */
  76333. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  76334. if (defines.COLORGRADING) {
  76335. samplersList.push("txColorTransform");
  76336. }
  76337. };
  76338. /**
  76339. * Prepare the list of defines associated to the shader.
  76340. * @param defines the list of defines to complete
  76341. */
  76342. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  76343. if (forPostProcess === void 0) { forPostProcess = false; }
  76344. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  76345. defines.VIGNETTE = false;
  76346. defines.TONEMAPPING = false;
  76347. defines.CONTRAST = false;
  76348. defines.EXPOSURE = false;
  76349. defines.COLORCURVES = false;
  76350. defines.COLORGRADING = false;
  76351. defines.COLORGRADING3D = false;
  76352. defines.IMAGEPROCESSING = false;
  76353. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  76354. return;
  76355. }
  76356. defines.VIGNETTE = this.vignetteEnabled;
  76357. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  76358. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  76359. defines.TONEMAPPING = this.toneMappingEnabled;
  76360. defines.CONTRAST = (this.contrast !== 1.0);
  76361. defines.EXPOSURE = (this.exposure !== 1.0);
  76362. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  76363. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  76364. if (defines.COLORGRADING) {
  76365. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  76366. }
  76367. else {
  76368. defines.COLORGRADING3D = false;
  76369. }
  76370. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  76371. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  76372. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  76373. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  76374. };
  76375. /**
  76376. * Returns true if all the image processing information are ready.
  76377. */
  76378. ImageProcessingConfiguration.prototype.isReady = function () {
  76379. // Color Grading texure can not be none blocking.
  76380. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  76381. };
  76382. /**
  76383. * Binds the image processing to the shader.
  76384. * @param effect The effect to bind to
  76385. */
  76386. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  76387. if (aspectRatio === void 0) { aspectRatio = 1; }
  76388. // Color Curves
  76389. if (this._colorCurvesEnabled && this.colorCurves) {
  76390. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  76391. }
  76392. // Vignette
  76393. if (this._vignetteEnabled) {
  76394. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  76395. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  76396. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  76397. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  76398. var vignetteScaleX = vignetteScaleY * aspectRatio;
  76399. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  76400. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  76401. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  76402. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  76403. var vignettePower = -2.0 * this.vignetteWeight;
  76404. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  76405. }
  76406. // Exposure
  76407. effect.setFloat("exposureLinear", this.exposure);
  76408. // Contrast
  76409. effect.setFloat("contrast", this.contrast);
  76410. // Color transform settings
  76411. if (this.colorGradingTexture) {
  76412. effect.setTexture("txColorTransform", this.colorGradingTexture);
  76413. var textureSize = this.colorGradingTexture.getSize().height;
  76414. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  76415. 0.5 / textureSize, // textureOffset
  76416. textureSize, // textureSize
  76417. this.colorGradingTexture.level // weight
  76418. );
  76419. }
  76420. };
  76421. /**
  76422. * Clones the current image processing instance.
  76423. * @return The cloned image processing
  76424. */
  76425. ImageProcessingConfiguration.prototype.clone = function () {
  76426. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  76427. };
  76428. /**
  76429. * Serializes the current image processing instance to a json representation.
  76430. * @return a JSON representation
  76431. */
  76432. ImageProcessingConfiguration.prototype.serialize = function () {
  76433. return BABYLON.SerializationHelper.Serialize(this);
  76434. };
  76435. /**
  76436. * Parses the image processing from a json representation.
  76437. * @param source the JSON source to parse
  76438. * @return The parsed image processing
  76439. */
  76440. ImageProcessingConfiguration.Parse = function (source) {
  76441. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  76442. };
  76443. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  76444. /**
  76445. * Used to apply the vignette as a mix with the pixel color.
  76446. */
  76447. get: function () {
  76448. return this._VIGNETTEMODE_MULTIPLY;
  76449. },
  76450. enumerable: true,
  76451. configurable: true
  76452. });
  76453. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  76454. /**
  76455. * Used to apply the vignette as a replacement of the pixel color.
  76456. */
  76457. get: function () {
  76458. return this._VIGNETTEMODE_OPAQUE;
  76459. },
  76460. enumerable: true,
  76461. configurable: true
  76462. });
  76463. // Static constants associated to the image processing.
  76464. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  76465. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  76466. __decorate([
  76467. BABYLON.serializeAsColorCurves()
  76468. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  76469. __decorate([
  76470. BABYLON.serialize()
  76471. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  76472. __decorate([
  76473. BABYLON.serializeAsTexture()
  76474. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  76475. __decorate([
  76476. BABYLON.serialize()
  76477. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  76478. __decorate([
  76479. BABYLON.serialize()
  76480. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  76481. __decorate([
  76482. BABYLON.serialize()
  76483. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  76484. __decorate([
  76485. BABYLON.serialize()
  76486. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  76487. __decorate([
  76488. BABYLON.serialize()
  76489. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  76490. __decorate([
  76491. BABYLON.serialize()
  76492. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  76493. __decorate([
  76494. BABYLON.serialize()
  76495. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  76496. __decorate([
  76497. BABYLON.serialize()
  76498. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  76499. __decorate([
  76500. BABYLON.serialize()
  76501. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  76502. __decorate([
  76503. BABYLON.serialize()
  76504. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  76505. __decorate([
  76506. BABYLON.serializeAsColor4()
  76507. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  76508. __decorate([
  76509. BABYLON.serialize()
  76510. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  76511. __decorate([
  76512. BABYLON.serialize()
  76513. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  76514. __decorate([
  76515. BABYLON.serialize()
  76516. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  76517. __decorate([
  76518. BABYLON.serialize()
  76519. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  76520. __decorate([
  76521. BABYLON.serialize()
  76522. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  76523. return ImageProcessingConfiguration;
  76524. }());
  76525. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  76526. })(BABYLON || (BABYLON = {}));
  76527. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  76528. var BABYLON;
  76529. (function (BABYLON) {
  76530. /**
  76531. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  76532. * It can help converting any input color in a desired output one. This can then be used to create effects
  76533. * from sepia, black and white to sixties or futuristic rendering...
  76534. *
  76535. * The only supported format is currently 3dl.
  76536. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  76537. */
  76538. var ColorGradingTexture = /** @class */ (function (_super) {
  76539. __extends(ColorGradingTexture, _super);
  76540. /**
  76541. * Instantiates a ColorGradingTexture from the following parameters.
  76542. *
  76543. * @param url The location of the color gradind data (currently only supporting 3dl)
  76544. * @param scene The scene the texture will be used in
  76545. */
  76546. function ColorGradingTexture(url, scene) {
  76547. var _this = _super.call(this, scene) || this;
  76548. if (!url) {
  76549. return _this;
  76550. }
  76551. _this._engine = scene.getEngine();
  76552. _this._textureMatrix = BABYLON.Matrix.Identity();
  76553. _this.name = url;
  76554. _this.url = url;
  76555. _this.hasAlpha = false;
  76556. _this.isCube = false;
  76557. _this.is3D = _this._engine.webGLVersion > 1;
  76558. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76559. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76560. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76561. _this.anisotropicFilteringLevel = 1;
  76562. _this._texture = _this._getFromCache(url, true);
  76563. if (!_this._texture) {
  76564. if (!scene.useDelayedTextureLoading) {
  76565. _this.loadTexture();
  76566. }
  76567. else {
  76568. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  76569. }
  76570. }
  76571. return _this;
  76572. }
  76573. /**
  76574. * Returns the texture matrix used in most of the material.
  76575. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  76576. */
  76577. ColorGradingTexture.prototype.getTextureMatrix = function () {
  76578. return this._textureMatrix;
  76579. };
  76580. /**
  76581. * Occurs when the file being loaded is a .3dl LUT file.
  76582. */
  76583. ColorGradingTexture.prototype.load3dlTexture = function () {
  76584. var engine = this._engine;
  76585. var texture;
  76586. if (engine.webGLVersion === 1) {
  76587. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  76588. }
  76589. else {
  76590. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  76591. }
  76592. this._texture = texture;
  76593. var callback = function (text) {
  76594. if (typeof text !== "string") {
  76595. return;
  76596. }
  76597. var data = null;
  76598. var tempData = null;
  76599. var line;
  76600. var lines = text.split('\n');
  76601. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  76602. var maxColor = 0;
  76603. for (var i = 0; i < lines.length; i++) {
  76604. line = lines[i];
  76605. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  76606. continue;
  76607. if (line.indexOf('#') === 0)
  76608. continue;
  76609. var words = line.split(" ");
  76610. if (size === 0) {
  76611. // Number of space + one
  76612. size = words.length;
  76613. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  76614. tempData = new Float32Array(size * size * size * 4);
  76615. continue;
  76616. }
  76617. if (size != 0) {
  76618. var r = Math.max(parseInt(words[0]), 0);
  76619. var g = Math.max(parseInt(words[1]), 0);
  76620. var b = Math.max(parseInt(words[2]), 0);
  76621. maxColor = Math.max(r, maxColor);
  76622. maxColor = Math.max(g, maxColor);
  76623. maxColor = Math.max(b, maxColor);
  76624. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  76625. if (tempData) {
  76626. tempData[pixelStorageIndex + 0] = r;
  76627. tempData[pixelStorageIndex + 1] = g;
  76628. tempData[pixelStorageIndex + 2] = b;
  76629. }
  76630. pixelIndexSlice++;
  76631. if (pixelIndexSlice % size == 0) {
  76632. pixelIndexH++;
  76633. pixelIndexSlice = 0;
  76634. if (pixelIndexH % size == 0) {
  76635. pixelIndexW++;
  76636. pixelIndexH = 0;
  76637. }
  76638. }
  76639. }
  76640. }
  76641. if (tempData && data) {
  76642. for (var i = 0; i < tempData.length; i++) {
  76643. if (i > 0 && (i + 1) % 4 === 0) {
  76644. data[i] = 255;
  76645. }
  76646. else {
  76647. var value = tempData[i];
  76648. data[i] = (value / maxColor * 255);
  76649. }
  76650. }
  76651. }
  76652. if (texture.is3D) {
  76653. texture.updateSize(size, size, size);
  76654. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  76655. }
  76656. else {
  76657. texture.updateSize(size * size, size);
  76658. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  76659. }
  76660. };
  76661. var scene = this.getScene();
  76662. if (scene) {
  76663. scene._loadFile(this.url, callback);
  76664. }
  76665. else {
  76666. this._engine._loadFile(this.url, callback);
  76667. }
  76668. return this._texture;
  76669. };
  76670. /**
  76671. * Starts the loading process of the texture.
  76672. */
  76673. ColorGradingTexture.prototype.loadTexture = function () {
  76674. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  76675. this.load3dlTexture();
  76676. }
  76677. };
  76678. /**
  76679. * Clones the color gradind texture.
  76680. */
  76681. ColorGradingTexture.prototype.clone = function () {
  76682. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  76683. // Base texture
  76684. newTexture.level = this.level;
  76685. return newTexture;
  76686. };
  76687. /**
  76688. * Called during delayed load for textures.
  76689. */
  76690. ColorGradingTexture.prototype.delayLoad = function () {
  76691. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  76692. return;
  76693. }
  76694. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  76695. this._texture = this._getFromCache(this.url, true);
  76696. if (!this._texture) {
  76697. this.loadTexture();
  76698. }
  76699. };
  76700. /**
  76701. * Parses a color grading texture serialized by Babylon.
  76702. * @param parsedTexture The texture information being parsedTexture
  76703. * @param scene The scene to load the texture in
  76704. * @param rootUrl The root url of the data assets to load
  76705. * @return A color gradind texture
  76706. */
  76707. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  76708. var texture = null;
  76709. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  76710. texture = new ColorGradingTexture(parsedTexture.name, scene);
  76711. texture.name = parsedTexture.name;
  76712. texture.level = parsedTexture.level;
  76713. }
  76714. return texture;
  76715. };
  76716. /**
  76717. * Serializes the LUT texture to json format.
  76718. */
  76719. ColorGradingTexture.prototype.serialize = function () {
  76720. if (!this.name) {
  76721. return null;
  76722. }
  76723. var serializationObject = {};
  76724. serializationObject.name = this.name;
  76725. serializationObject.level = this.level;
  76726. serializationObject.customType = "BABYLON.ColorGradingTexture";
  76727. return serializationObject;
  76728. };
  76729. /**
  76730. * Empty line regex stored for GC.
  76731. */
  76732. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  76733. return ColorGradingTexture;
  76734. }(BABYLON.BaseTexture));
  76735. BABYLON.ColorGradingTexture = ColorGradingTexture;
  76736. })(BABYLON || (BABYLON = {}));
  76737. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  76738. var BABYLON;
  76739. (function (BABYLON) {
  76740. /**
  76741. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  76742. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  76743. * 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;
  76744. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  76745. */
  76746. var ColorCurves = /** @class */ (function () {
  76747. function ColorCurves() {
  76748. this._dirty = true;
  76749. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  76750. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  76751. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  76752. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  76753. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  76754. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  76755. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  76756. this._globalHue = 30;
  76757. this._globalDensity = 0;
  76758. this._globalSaturation = 0;
  76759. this._globalExposure = 0;
  76760. this._highlightsHue = 30;
  76761. this._highlightsDensity = 0;
  76762. this._highlightsSaturation = 0;
  76763. this._highlightsExposure = 0;
  76764. this._midtonesHue = 30;
  76765. this._midtonesDensity = 0;
  76766. this._midtonesSaturation = 0;
  76767. this._midtonesExposure = 0;
  76768. this._shadowsHue = 30;
  76769. this._shadowsDensity = 0;
  76770. this._shadowsSaturation = 0;
  76771. this._shadowsExposure = 0;
  76772. }
  76773. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  76774. /**
  76775. * Gets the global Hue value.
  76776. * 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).
  76777. */
  76778. get: function () {
  76779. return this._globalHue;
  76780. },
  76781. /**
  76782. * Sets the global Hue value.
  76783. * 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).
  76784. */
  76785. set: function (value) {
  76786. this._globalHue = value;
  76787. this._dirty = true;
  76788. },
  76789. enumerable: true,
  76790. configurable: true
  76791. });
  76792. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  76793. /**
  76794. * Gets the global Density value.
  76795. * 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.
  76796. * Values less than zero provide a filter of opposite hue.
  76797. */
  76798. get: function () {
  76799. return this._globalDensity;
  76800. },
  76801. /**
  76802. * Sets the global Density value.
  76803. * 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.
  76804. * Values less than zero provide a filter of opposite hue.
  76805. */
  76806. set: function (value) {
  76807. this._globalDensity = value;
  76808. this._dirty = true;
  76809. },
  76810. enumerable: true,
  76811. configurable: true
  76812. });
  76813. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  76814. /**
  76815. * Gets the global Saturation value.
  76816. * 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.
  76817. */
  76818. get: function () {
  76819. return this._globalSaturation;
  76820. },
  76821. /**
  76822. * Sets the global Saturation value.
  76823. * 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.
  76824. */
  76825. set: function (value) {
  76826. this._globalSaturation = value;
  76827. this._dirty = true;
  76828. },
  76829. enumerable: true,
  76830. configurable: true
  76831. });
  76832. Object.defineProperty(ColorCurves.prototype, "globalExposure", {
  76833. /**
  76834. * Gets the global Exposure value.
  76835. * 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.
  76836. */
  76837. get: function () {
  76838. return this._globalExposure;
  76839. },
  76840. /**
  76841. * Sets the global Exposure value.
  76842. * 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.
  76843. */
  76844. set: function (value) {
  76845. this._globalExposure = value;
  76846. this._dirty = true;
  76847. },
  76848. enumerable: true,
  76849. configurable: true
  76850. });
  76851. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  76852. /**
  76853. * Gets the highlights Hue value.
  76854. * 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).
  76855. */
  76856. get: function () {
  76857. return this._highlightsHue;
  76858. },
  76859. /**
  76860. * Sets the highlights Hue value.
  76861. * 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).
  76862. */
  76863. set: function (value) {
  76864. this._highlightsHue = value;
  76865. this._dirty = true;
  76866. },
  76867. enumerable: true,
  76868. configurable: true
  76869. });
  76870. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  76871. /**
  76872. * Gets the highlights Density value.
  76873. * 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.
  76874. * Values less than zero provide a filter of opposite hue.
  76875. */
  76876. get: function () {
  76877. return this._highlightsDensity;
  76878. },
  76879. /**
  76880. * Sets the highlights Density value.
  76881. * 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.
  76882. * Values less than zero provide a filter of opposite hue.
  76883. */
  76884. set: function (value) {
  76885. this._highlightsDensity = value;
  76886. this._dirty = true;
  76887. },
  76888. enumerable: true,
  76889. configurable: true
  76890. });
  76891. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  76892. /**
  76893. * Gets the highlights Saturation value.
  76894. * 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.
  76895. */
  76896. get: function () {
  76897. return this._highlightsSaturation;
  76898. },
  76899. /**
  76900. * Sets the highlights Saturation value.
  76901. * 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.
  76902. */
  76903. set: function (value) {
  76904. this._highlightsSaturation = value;
  76905. this._dirty = true;
  76906. },
  76907. enumerable: true,
  76908. configurable: true
  76909. });
  76910. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  76911. /**
  76912. * Gets the highlights Exposure value.
  76913. * 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.
  76914. */
  76915. get: function () {
  76916. return this._highlightsExposure;
  76917. },
  76918. /**
  76919. * Sets the highlights Exposure value.
  76920. * 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.
  76921. */
  76922. set: function (value) {
  76923. this._highlightsExposure = value;
  76924. this._dirty = true;
  76925. },
  76926. enumerable: true,
  76927. configurable: true
  76928. });
  76929. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  76930. /**
  76931. * Gets the midtones Hue value.
  76932. * 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).
  76933. */
  76934. get: function () {
  76935. return this._midtonesHue;
  76936. },
  76937. /**
  76938. * Sets the midtones Hue value.
  76939. * 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).
  76940. */
  76941. set: function (value) {
  76942. this._midtonesHue = value;
  76943. this._dirty = true;
  76944. },
  76945. enumerable: true,
  76946. configurable: true
  76947. });
  76948. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  76949. /**
  76950. * Gets the midtones Density value.
  76951. * 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.
  76952. * Values less than zero provide a filter of opposite hue.
  76953. */
  76954. get: function () {
  76955. return this._midtonesDensity;
  76956. },
  76957. /**
  76958. * Sets the midtones Density value.
  76959. * 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.
  76960. * Values less than zero provide a filter of opposite hue.
  76961. */
  76962. set: function (value) {
  76963. this._midtonesDensity = value;
  76964. this._dirty = true;
  76965. },
  76966. enumerable: true,
  76967. configurable: true
  76968. });
  76969. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  76970. /**
  76971. * Gets the midtones Saturation value.
  76972. * 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.
  76973. */
  76974. get: function () {
  76975. return this._midtonesSaturation;
  76976. },
  76977. /**
  76978. * Sets the midtones Saturation value.
  76979. * 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.
  76980. */
  76981. set: function (value) {
  76982. this._midtonesSaturation = value;
  76983. this._dirty = true;
  76984. },
  76985. enumerable: true,
  76986. configurable: true
  76987. });
  76988. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  76989. /**
  76990. * Gets the midtones Exposure value.
  76991. * 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.
  76992. */
  76993. get: function () {
  76994. return this._midtonesExposure;
  76995. },
  76996. /**
  76997. * Sets the midtones Exposure value.
  76998. * 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.
  76999. */
  77000. set: function (value) {
  77001. this._midtonesExposure = value;
  77002. this._dirty = true;
  77003. },
  77004. enumerable: true,
  77005. configurable: true
  77006. });
  77007. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  77008. /**
  77009. * Gets the shadows Hue value.
  77010. * 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).
  77011. */
  77012. get: function () {
  77013. return this._shadowsHue;
  77014. },
  77015. /**
  77016. * Sets the shadows Hue value.
  77017. * 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).
  77018. */
  77019. set: function (value) {
  77020. this._shadowsHue = value;
  77021. this._dirty = true;
  77022. },
  77023. enumerable: true,
  77024. configurable: true
  77025. });
  77026. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  77027. /**
  77028. * Gets the shadows Density value.
  77029. * 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.
  77030. * Values less than zero provide a filter of opposite hue.
  77031. */
  77032. get: function () {
  77033. return this._shadowsDensity;
  77034. },
  77035. /**
  77036. * Sets the shadows Density value.
  77037. * 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.
  77038. * Values less than zero provide a filter of opposite hue.
  77039. */
  77040. set: function (value) {
  77041. this._shadowsDensity = value;
  77042. this._dirty = true;
  77043. },
  77044. enumerable: true,
  77045. configurable: true
  77046. });
  77047. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  77048. /**
  77049. * Gets the shadows Saturation value.
  77050. * 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.
  77051. */
  77052. get: function () {
  77053. return this._shadowsSaturation;
  77054. },
  77055. /**
  77056. * Sets the shadows Saturation value.
  77057. * 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.
  77058. */
  77059. set: function (value) {
  77060. this._shadowsSaturation = value;
  77061. this._dirty = true;
  77062. },
  77063. enumerable: true,
  77064. configurable: true
  77065. });
  77066. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  77067. /**
  77068. * Gets the shadows Exposure value.
  77069. * 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.
  77070. */
  77071. get: function () {
  77072. return this._shadowsExposure;
  77073. },
  77074. /**
  77075. * Sets the shadows Exposure value.
  77076. * 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.
  77077. */
  77078. set: function (value) {
  77079. this._shadowsExposure = value;
  77080. this._dirty = true;
  77081. },
  77082. enumerable: true,
  77083. configurable: true
  77084. });
  77085. ColorCurves.prototype.getClassName = function () {
  77086. return "ColorCurves";
  77087. };
  77088. /**
  77089. * Binds the color curves to the shader.
  77090. * @param colorCurves The color curve to bind
  77091. * @param effect The effect to bind to
  77092. */
  77093. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  77094. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  77095. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  77096. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  77097. if (colorCurves._dirty) {
  77098. colorCurves._dirty = false;
  77099. // Fill in global info.
  77100. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  77101. // Compute highlights info.
  77102. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  77103. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  77104. // Compute midtones info.
  77105. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  77106. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  77107. // Compute shadows info.
  77108. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  77109. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  77110. // Compute deltas (neutral is midtones).
  77111. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  77112. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  77113. }
  77114. if (effect) {
  77115. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  77116. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  77117. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  77118. }
  77119. };
  77120. /**
  77121. * Prepare the list of uniforms associated with the ColorCurves effects.
  77122. * @param uniformsList The list of uniforms used in the effect
  77123. */
  77124. ColorCurves.PrepareUniforms = function (uniformsList) {
  77125. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  77126. };
  77127. /**
  77128. * Returns color grading data based on a hue, density, saturation and exposure value.
  77129. * @param filterHue The hue of the color filter.
  77130. * @param filterDensity The density of the color filter.
  77131. * @param saturation The saturation.
  77132. * @param exposure The exposure.
  77133. * @param result The result data container.
  77134. */
  77135. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  77136. if (hue == null) {
  77137. return;
  77138. }
  77139. hue = ColorCurves.clamp(hue, 0, 360);
  77140. density = ColorCurves.clamp(density, -100, 100);
  77141. saturation = ColorCurves.clamp(saturation, -100, 100);
  77142. exposure = ColorCurves.clamp(exposure, -100, 100);
  77143. // Remap the slider/config filter density with non-linear mapping and also scale by half
  77144. // so that the maximum filter density is only 50% control. This provides fine control
  77145. // for small values and reasonable range.
  77146. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  77147. density *= 0.5;
  77148. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  77149. if (density < 0) {
  77150. density *= -1;
  77151. hue = (hue + 180) % 360;
  77152. }
  77153. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  77154. result.scaleToRef(2, result);
  77155. result.a = 1 + 0.01 * saturation;
  77156. };
  77157. /**
  77158. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  77159. * @param value The input slider value in range [-100,100].
  77160. * @returns Adjusted value.
  77161. */
  77162. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  77163. value /= 100;
  77164. var x = Math.abs(value);
  77165. x = Math.pow(x, 2);
  77166. if (value < 0) {
  77167. x *= -1;
  77168. }
  77169. x *= 100;
  77170. return x;
  77171. };
  77172. /**
  77173. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  77174. * @param hue The hue (H) input.
  77175. * @param saturation The saturation (S) input.
  77176. * @param brightness The brightness (B) input.
  77177. * @result An RGBA color represented as Vector4.
  77178. */
  77179. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  77180. var h = ColorCurves.clamp(hue, 0, 360);
  77181. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  77182. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  77183. if (s === 0) {
  77184. result.r = v;
  77185. result.g = v;
  77186. result.b = v;
  77187. }
  77188. else {
  77189. // sector 0 to 5
  77190. h /= 60;
  77191. var i = Math.floor(h);
  77192. // fractional part of h
  77193. var f = h - i;
  77194. var p = v * (1 - s);
  77195. var q = v * (1 - s * f);
  77196. var t = v * (1 - s * (1 - f));
  77197. switch (i) {
  77198. case 0:
  77199. result.r = v;
  77200. result.g = t;
  77201. result.b = p;
  77202. break;
  77203. case 1:
  77204. result.r = q;
  77205. result.g = v;
  77206. result.b = p;
  77207. break;
  77208. case 2:
  77209. result.r = p;
  77210. result.g = v;
  77211. result.b = t;
  77212. break;
  77213. case 3:
  77214. result.r = p;
  77215. result.g = q;
  77216. result.b = v;
  77217. break;
  77218. case 4:
  77219. result.r = t;
  77220. result.g = p;
  77221. result.b = v;
  77222. break;
  77223. default: // case 5:
  77224. result.r = v;
  77225. result.g = p;
  77226. result.b = q;
  77227. break;
  77228. }
  77229. }
  77230. result.a = 1;
  77231. };
  77232. /**
  77233. * Returns a value clamped between min and max
  77234. * @param value The value to clamp
  77235. * @param min The minimum of value
  77236. * @param max The maximum of value
  77237. * @returns The clamped value.
  77238. */
  77239. ColorCurves.clamp = function (value, min, max) {
  77240. return Math.min(Math.max(value, min), max);
  77241. };
  77242. /**
  77243. * Clones the current color curve instance.
  77244. * @return The cloned curves
  77245. */
  77246. ColorCurves.prototype.clone = function () {
  77247. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  77248. };
  77249. /**
  77250. * Serializes the current color curve instance to a json representation.
  77251. * @return a JSON representation
  77252. */
  77253. ColorCurves.prototype.serialize = function () {
  77254. return BABYLON.SerializationHelper.Serialize(this);
  77255. };
  77256. /**
  77257. * Parses the color curve from a json representation.
  77258. * @param source the JSON source to parse
  77259. * @return The parsed curves
  77260. */
  77261. ColorCurves.Parse = function (source) {
  77262. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  77263. };
  77264. __decorate([
  77265. BABYLON.serialize()
  77266. ], ColorCurves.prototype, "_globalHue", void 0);
  77267. __decorate([
  77268. BABYLON.serialize()
  77269. ], ColorCurves.prototype, "_globalDensity", void 0);
  77270. __decorate([
  77271. BABYLON.serialize()
  77272. ], ColorCurves.prototype, "_globalSaturation", void 0);
  77273. __decorate([
  77274. BABYLON.serialize()
  77275. ], ColorCurves.prototype, "_globalExposure", void 0);
  77276. __decorate([
  77277. BABYLON.serialize()
  77278. ], ColorCurves.prototype, "_highlightsHue", void 0);
  77279. __decorate([
  77280. BABYLON.serialize()
  77281. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  77282. __decorate([
  77283. BABYLON.serialize()
  77284. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  77285. __decorate([
  77286. BABYLON.serialize()
  77287. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  77288. __decorate([
  77289. BABYLON.serialize()
  77290. ], ColorCurves.prototype, "_midtonesHue", void 0);
  77291. __decorate([
  77292. BABYLON.serialize()
  77293. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  77294. __decorate([
  77295. BABYLON.serialize()
  77296. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  77297. __decorate([
  77298. BABYLON.serialize()
  77299. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  77300. return ColorCurves;
  77301. }());
  77302. BABYLON.ColorCurves = ColorCurves;
  77303. })(BABYLON || (BABYLON = {}));
  77304. //# sourceMappingURL=babylon.colorCurves.js.map
  77305. var BABYLON;
  77306. (function (BABYLON) {
  77307. var RefractionPostProcess = /** @class */ (function (_super) {
  77308. __extends(RefractionPostProcess, _super);
  77309. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  77310. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  77311. _this.color = color;
  77312. _this.depth = depth;
  77313. _this.colorLevel = colorLevel;
  77314. _this._ownRefractionTexture = true;
  77315. _this.onActivateObservable.add(function (cam) {
  77316. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  77317. });
  77318. _this.onApplyObservable.add(function (effect) {
  77319. effect.setColor3("baseColor", _this.color);
  77320. effect.setFloat("depth", _this.depth);
  77321. effect.setFloat("colorLevel", _this.colorLevel);
  77322. effect.setTexture("refractionSampler", _this._refTexture);
  77323. });
  77324. return _this;
  77325. }
  77326. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  77327. /**
  77328. * Gets or sets the refraction texture
  77329. * Please note that you are responsible for disposing the texture if you set it manually
  77330. */
  77331. get: function () {
  77332. return this._refTexture;
  77333. },
  77334. set: function (value) {
  77335. if (this._refTexture && this._ownRefractionTexture) {
  77336. this._refTexture.dispose();
  77337. }
  77338. this._refTexture = value;
  77339. this._ownRefractionTexture = false;
  77340. },
  77341. enumerable: true,
  77342. configurable: true
  77343. });
  77344. // Methods
  77345. RefractionPostProcess.prototype.dispose = function (camera) {
  77346. if (this._refTexture && this._ownRefractionTexture) {
  77347. this._refTexture.dispose();
  77348. this._refTexture = null;
  77349. }
  77350. _super.prototype.dispose.call(this, camera);
  77351. };
  77352. return RefractionPostProcess;
  77353. }(BABYLON.PostProcess));
  77354. BABYLON.RefractionPostProcess = RefractionPostProcess;
  77355. })(BABYLON || (BABYLON = {}));
  77356. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  77357. var BABYLON;
  77358. (function (BABYLON) {
  77359. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  77360. __extends(BlackAndWhitePostProcess, _super);
  77361. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  77362. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  77363. _this.degree = 1;
  77364. _this.onApplyObservable.add(function (effect) {
  77365. effect.setFloat("degree", _this.degree);
  77366. });
  77367. return _this;
  77368. }
  77369. return BlackAndWhitePostProcess;
  77370. }(BABYLON.PostProcess));
  77371. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  77372. })(BABYLON || (BABYLON = {}));
  77373. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  77374. var BABYLON;
  77375. (function (BABYLON) {
  77376. /**
  77377. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  77378. * input texture to perform effects such as edge detection or sharpening
  77379. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  77380. */
  77381. var ConvolutionPostProcess = /** @class */ (function (_super) {
  77382. __extends(ConvolutionPostProcess, _super);
  77383. /**
  77384. * Creates a new instance ConvolutionPostProcess
  77385. * @param name The name of the effect.
  77386. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  77387. * @param options The required width/height ratio to downsize to before computing the render pass.
  77388. * @param camera The camera to apply the render pass to.
  77389. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  77390. * @param engine The engine which the post process will be applied. (default: current engine)
  77391. * @param reusable If the post process can be reused on the same frame. (default: false)
  77392. * @param textureType Type of textures used when performing the post process. (default: 0)
  77393. */
  77394. function ConvolutionPostProcess(name, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel, options, camera, samplingMode, engine, reusable, textureType) {
  77395. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77396. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  77397. _this.kernel = kernel;
  77398. _this.onApply = function (effect) {
  77399. effect.setFloat2("screenSize", _this.width, _this.height);
  77400. effect.setArray("kernel", _this.kernel);
  77401. };
  77402. return _this;
  77403. }
  77404. // Statics
  77405. /**
  77406. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  77407. */
  77408. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  77409. /**
  77410. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  77411. */
  77412. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  77413. /**
  77414. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  77415. */
  77416. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  77417. /**
  77418. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  77419. */
  77420. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  77421. /**
  77422. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  77423. */
  77424. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  77425. /**
  77426. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  77427. */
  77428. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  77429. return ConvolutionPostProcess;
  77430. }(BABYLON.PostProcess));
  77431. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  77432. })(BABYLON || (BABYLON = {}));
  77433. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  77434. var BABYLON;
  77435. (function (BABYLON) {
  77436. var FilterPostProcess = /** @class */ (function (_super) {
  77437. __extends(FilterPostProcess, _super);
  77438. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  77439. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  77440. _this.kernelMatrix = kernelMatrix;
  77441. _this.onApply = function (effect) {
  77442. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  77443. };
  77444. return _this;
  77445. }
  77446. return FilterPostProcess;
  77447. }(BABYLON.PostProcess));
  77448. BABYLON.FilterPostProcess = FilterPostProcess;
  77449. })(BABYLON || (BABYLON = {}));
  77450. //# sourceMappingURL=babylon.filterPostProcess.js.map
  77451. var BABYLON;
  77452. (function (BABYLON) {
  77453. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  77454. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  77455. __extends(VolumetricLightScatteringPostProcess, _super);
  77456. /**
  77457. * @constructor
  77458. * @param {string} name - The post-process name
  77459. * @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)
  77460. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  77461. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  77462. * @param {number} samples - The post-process quality, default 100
  77463. * @param {number} samplingMode - The post-process filtering mode
  77464. * @param {BABYLON.Engine} engine - The babylon engine
  77465. * @param {boolean} reusable - If the post-process is reusable
  77466. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  77467. */
  77468. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  77469. if (samples === void 0) { samples = 100; }
  77470. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  77471. 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;
  77472. _this._screenCoordinates = BABYLON.Vector2.Zero();
  77473. /**
  77474. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  77475. */
  77476. _this.customMeshPosition = BABYLON.Vector3.Zero();
  77477. /**
  77478. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  77479. */
  77480. _this.useCustomMeshPosition = false;
  77481. /**
  77482. * If the post-process should inverse the light scattering direction
  77483. */
  77484. _this.invert = true;
  77485. /**
  77486. * Array containing the excluded meshes not rendered in the internal pass
  77487. */
  77488. _this.excludedMeshes = new Array();
  77489. /**
  77490. * Controls the overall intensity of the post-process
  77491. */
  77492. _this.exposure = 0.3;
  77493. /**
  77494. * Dissipates each sample's contribution in range [0, 1]
  77495. */
  77496. _this.decay = 0.96815;
  77497. /**
  77498. * Controls the overall intensity of each sample
  77499. */
  77500. _this.weight = 0.58767;
  77501. /**
  77502. * Controls the density of each sample
  77503. */
  77504. _this.density = 0.926;
  77505. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  77506. engine = scene.getEngine();
  77507. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  77508. // Configure mesh
  77509. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  77510. // Configure
  77511. _this._createPass(scene, ratio.passRatio || ratio);
  77512. _this.onActivate = function (camera) {
  77513. if (!_this.isSupported) {
  77514. _this.dispose(camera);
  77515. }
  77516. _this.onActivate = null;
  77517. };
  77518. _this.onApplyObservable.add(function (effect) {
  77519. _this._updateMeshScreenCoordinates(scene);
  77520. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  77521. effect.setFloat("exposure", _this.exposure);
  77522. effect.setFloat("decay", _this.decay);
  77523. effect.setFloat("weight", _this.weight);
  77524. effect.setFloat("density", _this.density);
  77525. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  77526. });
  77527. return _this;
  77528. }
  77529. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  77530. get: function () {
  77531. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  77532. return false;
  77533. },
  77534. set: function (useDiffuseColor) {
  77535. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  77536. },
  77537. enumerable: true,
  77538. configurable: true
  77539. });
  77540. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  77541. return "VolumetricLightScatteringPostProcess";
  77542. };
  77543. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  77544. var mesh = subMesh.getMesh();
  77545. // Render this.mesh as default
  77546. if (mesh === this.mesh && mesh.material) {
  77547. return mesh.material.isReady(mesh);
  77548. }
  77549. var defines = [];
  77550. var attribs = [BABYLON.VertexBuffer.PositionKind];
  77551. var material = subMesh.getMaterial();
  77552. // Alpha test
  77553. if (material) {
  77554. if (material.needAlphaTesting()) {
  77555. defines.push("#define ALPHATEST");
  77556. }
  77557. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  77558. attribs.push(BABYLON.VertexBuffer.UVKind);
  77559. defines.push("#define UV1");
  77560. }
  77561. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  77562. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  77563. defines.push("#define UV2");
  77564. }
  77565. }
  77566. // Bones
  77567. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  77568. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  77569. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  77570. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  77571. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  77572. }
  77573. else {
  77574. defines.push("#define NUM_BONE_INFLUENCERS 0");
  77575. }
  77576. // Instances
  77577. if (useInstances) {
  77578. defines.push("#define INSTANCES");
  77579. attribs.push("world0");
  77580. attribs.push("world1");
  77581. attribs.push("world2");
  77582. attribs.push("world3");
  77583. }
  77584. // Get correct effect
  77585. var join = defines.join("\n");
  77586. if (this._cachedDefines !== join) {
  77587. this._cachedDefines = join;
  77588. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  77589. }
  77590. return this._volumetricLightScatteringPass.isReady();
  77591. };
  77592. /**
  77593. * Sets the new light position for light scattering effect
  77594. * @param {BABYLON.Vector3} The new custom light position
  77595. */
  77596. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  77597. this.customMeshPosition = position;
  77598. };
  77599. /**
  77600. * Returns the light position for light scattering effect
  77601. * @return {BABYLON.Vector3} The custom light position
  77602. */
  77603. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  77604. return this.customMeshPosition;
  77605. };
  77606. /**
  77607. * Disposes the internal assets and detaches the post-process from the camera
  77608. */
  77609. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  77610. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  77611. if (rttIndex !== -1) {
  77612. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  77613. }
  77614. this._volumetricLightScatteringRTT.dispose();
  77615. _super.prototype.dispose.call(this, camera);
  77616. };
  77617. /**
  77618. * Returns the render target texture used by the post-process
  77619. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  77620. */
  77621. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  77622. return this._volumetricLightScatteringRTT;
  77623. };
  77624. // Private methods
  77625. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  77626. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  77627. return true;
  77628. }
  77629. return false;
  77630. };
  77631. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  77632. var _this = this;
  77633. var engine = scene.getEngine();
  77634. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  77635. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77636. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77637. this._volumetricLightScatteringRTT.renderList = null;
  77638. this._volumetricLightScatteringRTT.renderParticles = false;
  77639. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  77640. var camera = this.getCamera();
  77641. if (camera) {
  77642. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  77643. }
  77644. else {
  77645. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  77646. }
  77647. // Custom render function for submeshes
  77648. var renderSubMesh = function (subMesh) {
  77649. var mesh = subMesh.getRenderingMesh();
  77650. if (_this._meshExcluded(mesh)) {
  77651. return;
  77652. }
  77653. var material = subMesh.getMaterial();
  77654. if (!material) {
  77655. return;
  77656. }
  77657. var scene = mesh.getScene();
  77658. var engine = scene.getEngine();
  77659. // Culling
  77660. engine.setState(material.backFaceCulling);
  77661. // Managing instances
  77662. var batch = mesh._getInstancesRenderList(subMesh._id);
  77663. if (batch.mustReturn) {
  77664. return;
  77665. }
  77666. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  77667. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  77668. var effect = _this._volumetricLightScatteringPass;
  77669. if (mesh === _this.mesh) {
  77670. if (subMesh.effect) {
  77671. effect = subMesh.effect;
  77672. }
  77673. else {
  77674. effect = material.getEffect();
  77675. }
  77676. }
  77677. engine.enableEffect(effect);
  77678. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  77679. if (mesh === _this.mesh) {
  77680. material.bind(mesh.getWorldMatrix(), mesh);
  77681. }
  77682. else {
  77683. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  77684. // Alpha test
  77685. if (material && material.needAlphaTesting()) {
  77686. var alphaTexture = material.getAlphaTestTexture();
  77687. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  77688. if (alphaTexture) {
  77689. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  77690. }
  77691. }
  77692. // Bones
  77693. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  77694. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  77695. }
  77696. }
  77697. // Draw
  77698. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  77699. }
  77700. };
  77701. // Render target texture callbacks
  77702. var savedSceneClearColor;
  77703. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  77704. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  77705. savedSceneClearColor = scene.clearColor;
  77706. scene.clearColor = sceneClearColor;
  77707. });
  77708. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  77709. scene.clearColor = savedSceneClearColor;
  77710. });
  77711. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  77712. var engine = scene.getEngine();
  77713. var index;
  77714. if (depthOnlySubMeshes.length) {
  77715. engine.setColorWrite(false);
  77716. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  77717. renderSubMesh(depthOnlySubMeshes.data[index]);
  77718. }
  77719. engine.setColorWrite(true);
  77720. }
  77721. for (index = 0; index < opaqueSubMeshes.length; index++) {
  77722. renderSubMesh(opaqueSubMeshes.data[index]);
  77723. }
  77724. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  77725. renderSubMesh(alphaTestSubMeshes.data[index]);
  77726. }
  77727. if (transparentSubMeshes.length) {
  77728. // Sort sub meshes
  77729. for (index = 0; index < transparentSubMeshes.length; index++) {
  77730. var submesh = transparentSubMeshes.data[index];
  77731. var boundingInfo = submesh.getBoundingInfo();
  77732. if (boundingInfo && scene.activeCamera) {
  77733. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  77734. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  77735. }
  77736. }
  77737. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  77738. sortedArray.sort(function (a, b) {
  77739. // Alpha index first
  77740. if (a._alphaIndex > b._alphaIndex) {
  77741. return 1;
  77742. }
  77743. if (a._alphaIndex < b._alphaIndex) {
  77744. return -1;
  77745. }
  77746. // Then distance to camera
  77747. if (a._distanceToCamera < b._distanceToCamera) {
  77748. return 1;
  77749. }
  77750. if (a._distanceToCamera > b._distanceToCamera) {
  77751. return -1;
  77752. }
  77753. return 0;
  77754. });
  77755. // Render sub meshes
  77756. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  77757. for (index = 0; index < sortedArray.length; index++) {
  77758. renderSubMesh(sortedArray[index]);
  77759. }
  77760. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  77761. }
  77762. };
  77763. };
  77764. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  77765. var transform = scene.getTransformMatrix();
  77766. var meshPosition;
  77767. if (this.useCustomMeshPosition) {
  77768. meshPosition = this.customMeshPosition;
  77769. }
  77770. else if (this.attachedNode) {
  77771. meshPosition = this.attachedNode.position;
  77772. }
  77773. else {
  77774. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  77775. }
  77776. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  77777. this._screenCoordinates.x = pos.x / this._viewPort.width;
  77778. this._screenCoordinates.y = pos.y / this._viewPort.height;
  77779. if (this.invert)
  77780. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  77781. };
  77782. // Static methods
  77783. /**
  77784. * Creates a default mesh for the Volumeric Light Scattering post-process
  77785. * @param {string} The mesh name
  77786. * @param {BABYLON.Scene} The scene where to create the mesh
  77787. * @return {BABYLON.Mesh} the default mesh
  77788. */
  77789. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  77790. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  77791. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  77792. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  77793. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  77794. mesh.material = material;
  77795. return mesh;
  77796. };
  77797. __decorate([
  77798. BABYLON.serializeAsVector3()
  77799. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  77800. __decorate([
  77801. BABYLON.serialize()
  77802. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  77803. __decorate([
  77804. BABYLON.serialize()
  77805. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  77806. __decorate([
  77807. BABYLON.serializeAsMeshReference()
  77808. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  77809. __decorate([
  77810. BABYLON.serialize()
  77811. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  77812. __decorate([
  77813. BABYLON.serialize()
  77814. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  77815. __decorate([
  77816. BABYLON.serialize()
  77817. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  77818. __decorate([
  77819. BABYLON.serialize()
  77820. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  77821. __decorate([
  77822. BABYLON.serialize()
  77823. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  77824. return VolumetricLightScatteringPostProcess;
  77825. }(BABYLON.PostProcess));
  77826. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  77827. })(BABYLON || (BABYLON = {}));
  77828. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  77829. //
  77830. // This post-process allows the modification of rendered colors by using
  77831. // a 'look-up table' (LUT). This effect is also called Color Grading.
  77832. //
  77833. // The object needs to be provided an url to a texture containing the color
  77834. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  77835. // Use an image editing software to tweak the LUT to match your needs.
  77836. //
  77837. // For an example of a color LUT, see here:
  77838. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  77839. // For explanations on color grading, see here:
  77840. // http://udn.epicgames.com/Three/ColorGrading.html
  77841. //
  77842. var BABYLON;
  77843. (function (BABYLON) {
  77844. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  77845. __extends(ColorCorrectionPostProcess, _super);
  77846. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  77847. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  77848. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  77849. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  77850. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77851. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77852. _this.onApply = function (effect) {
  77853. effect.setTexture("colorTable", _this._colorTableTexture);
  77854. };
  77855. return _this;
  77856. }
  77857. return ColorCorrectionPostProcess;
  77858. }(BABYLON.PostProcess));
  77859. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  77860. })(BABYLON || (BABYLON = {}));
  77861. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  77862. var BABYLON;
  77863. (function (BABYLON) {
  77864. /** Defines operator used for tonemapping */
  77865. var TonemappingOperator;
  77866. (function (TonemappingOperator) {
  77867. /** Hable */
  77868. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  77869. /** Reinhard */
  77870. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  77871. /** HejiDawson */
  77872. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  77873. /** Photographic */
  77874. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  77875. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  77876. ;
  77877. /**
  77878. * Defines a post process to apply tone mapping
  77879. */
  77880. var TonemapPostProcess = /** @class */ (function (_super) {
  77881. __extends(TonemapPostProcess, _super);
  77882. /**
  77883. * Creates a new TonemapPostProcess
  77884. * @param name defines the name of the postprocess
  77885. * @param _operator defines the operator to use
  77886. * @param exposureAdjustment defines the required exposure adjustement
  77887. * @param camera defines the camera to use (can be null)
  77888. * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)
  77889. * @param engine defines the hosting engine (can be ignore if camera is set)
  77890. * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  77891. */
  77892. function TonemapPostProcess(name, _operator,
  77893. /** Defines the required exposure adjustement */
  77894. exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  77895. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  77896. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77897. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  77898. _this._operator = _operator;
  77899. _this.exposureAdjustment = exposureAdjustment;
  77900. var defines = "#define ";
  77901. if (_this._operator === TonemappingOperator.Hable)
  77902. defines += "HABLE_TONEMAPPING";
  77903. else if (_this._operator === TonemappingOperator.Reinhard)
  77904. defines += "REINHARD_TONEMAPPING";
  77905. else if (_this._operator === TonemappingOperator.HejiDawson)
  77906. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  77907. else if (_this._operator === TonemappingOperator.Photographic)
  77908. defines += "PHOTOGRAPHIC_TONEMAPPING";
  77909. //sadly a second call to create the effect.
  77910. _this.updateEffect(defines);
  77911. _this.onApply = function (effect) {
  77912. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  77913. };
  77914. return _this;
  77915. }
  77916. return TonemapPostProcess;
  77917. }(BABYLON.PostProcess));
  77918. BABYLON.TonemapPostProcess = TonemapPostProcess;
  77919. })(BABYLON || (BABYLON = {}));
  77920. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  77921. var BABYLON;
  77922. (function (BABYLON) {
  77923. var DisplayPassPostProcess = /** @class */ (function (_super) {
  77924. __extends(DisplayPassPostProcess, _super);
  77925. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  77926. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  77927. }
  77928. return DisplayPassPostProcess;
  77929. }(BABYLON.PostProcess));
  77930. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  77931. })(BABYLON || (BABYLON = {}));
  77932. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  77933. var BABYLON;
  77934. (function (BABYLON) {
  77935. var HighlightsPostProcess = /** @class */ (function (_super) {
  77936. __extends(HighlightsPostProcess, _super);
  77937. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  77938. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77939. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  77940. }
  77941. return HighlightsPostProcess;
  77942. }(BABYLON.PostProcess));
  77943. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  77944. })(BABYLON || (BABYLON = {}));
  77945. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  77946. var BABYLON;
  77947. (function (BABYLON) {
  77948. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  77949. __extends(ImageProcessingPostProcess, _super);
  77950. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  77951. if (camera === void 0) { camera = null; }
  77952. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77953. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  77954. _this._fromLinearSpace = true;
  77955. /**
  77956. * Defines cache preventing GC.
  77957. */
  77958. _this._defines = {
  77959. IMAGEPROCESSING: false,
  77960. VIGNETTE: false,
  77961. VIGNETTEBLENDMODEMULTIPLY: false,
  77962. VIGNETTEBLENDMODEOPAQUE: false,
  77963. TONEMAPPING: false,
  77964. CONTRAST: false,
  77965. COLORCURVES: false,
  77966. COLORGRADING: false,
  77967. COLORGRADING3D: false,
  77968. FROMLINEARSPACE: false,
  77969. SAMPLER3DGREENDEPTH: false,
  77970. SAMPLER3DBGRMAP: false,
  77971. IMAGEPROCESSINGPOSTPROCESS: false,
  77972. EXPOSURE: false,
  77973. };
  77974. // Setup the configuration as forced by the constructor. This would then not force the
  77975. // scene materials output in linear space and let untouched the default forward pass.
  77976. if (imageProcessingConfiguration) {
  77977. imageProcessingConfiguration.applyByPostProcess = true;
  77978. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  77979. // This will cause the shader to be compiled
  77980. _this.fromLinearSpace = false;
  77981. }
  77982. // Setup the default processing configuration to the scene.
  77983. else {
  77984. _this._attachImageProcessingConfiguration(null, true);
  77985. _this.imageProcessingConfiguration.applyByPostProcess = true;
  77986. }
  77987. _this.onApply = function (effect) {
  77988. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  77989. };
  77990. return _this;
  77991. }
  77992. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  77993. /**
  77994. * Gets the image processing configuration used either in this material.
  77995. */
  77996. get: function () {
  77997. return this._imageProcessingConfiguration;
  77998. },
  77999. /**
  78000. * Sets the Default image processing configuration used either in the this material.
  78001. *
  78002. * If sets to null, the scene one is in use.
  78003. */
  78004. set: function (value) {
  78005. this._attachImageProcessingConfiguration(value);
  78006. },
  78007. enumerable: true,
  78008. configurable: true
  78009. });
  78010. /**
  78011. * Attaches a new image processing configuration to the PBR Material.
  78012. * @param configuration
  78013. */
  78014. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  78015. var _this = this;
  78016. if (doNotBuild === void 0) { doNotBuild = false; }
  78017. if (configuration === this._imageProcessingConfiguration) {
  78018. return;
  78019. }
  78020. // Detaches observer.
  78021. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  78022. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  78023. }
  78024. // Pick the scene configuration if needed.
  78025. if (!configuration) {
  78026. var scene = null;
  78027. var engine = this.getEngine();
  78028. var camera = this.getCamera();
  78029. if (camera) {
  78030. scene = camera.getScene();
  78031. }
  78032. else if (engine && engine.scenes) {
  78033. var scenes = engine.scenes;
  78034. scene = scenes[scenes.length - 1];
  78035. }
  78036. else {
  78037. scene = BABYLON.Engine.LastCreatedScene;
  78038. }
  78039. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  78040. }
  78041. else {
  78042. this._imageProcessingConfiguration = configuration;
  78043. }
  78044. // Attaches observer.
  78045. if (this._imageProcessingConfiguration) {
  78046. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  78047. _this._updateParameters();
  78048. });
  78049. }
  78050. // Ensure the effect will be rebuilt.
  78051. if (!doNotBuild) {
  78052. this._updateParameters();
  78053. }
  78054. };
  78055. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  78056. /**
  78057. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  78058. */
  78059. get: function () {
  78060. return this.imageProcessingConfiguration.colorCurves;
  78061. },
  78062. /**
  78063. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  78064. */
  78065. set: function (value) {
  78066. this.imageProcessingConfiguration.colorCurves = value;
  78067. },
  78068. enumerable: true,
  78069. configurable: true
  78070. });
  78071. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  78072. /**
  78073. * Gets wether the color curves effect is enabled.
  78074. */
  78075. get: function () {
  78076. return this.imageProcessingConfiguration.colorCurvesEnabled;
  78077. },
  78078. /**
  78079. * Sets wether the color curves effect is enabled.
  78080. */
  78081. set: function (value) {
  78082. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  78083. },
  78084. enumerable: true,
  78085. configurable: true
  78086. });
  78087. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  78088. /**
  78089. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  78090. */
  78091. get: function () {
  78092. return this.imageProcessingConfiguration.colorGradingTexture;
  78093. },
  78094. /**
  78095. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  78096. */
  78097. set: function (value) {
  78098. this.imageProcessingConfiguration.colorGradingTexture = value;
  78099. },
  78100. enumerable: true,
  78101. configurable: true
  78102. });
  78103. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  78104. /**
  78105. * Gets wether the color grading effect is enabled.
  78106. */
  78107. get: function () {
  78108. return this.imageProcessingConfiguration.colorGradingEnabled;
  78109. },
  78110. /**
  78111. * Gets wether the color grading effect is enabled.
  78112. */
  78113. set: function (value) {
  78114. this.imageProcessingConfiguration.colorGradingEnabled = value;
  78115. },
  78116. enumerable: true,
  78117. configurable: true
  78118. });
  78119. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  78120. /**
  78121. * Gets exposure used in the effect.
  78122. */
  78123. get: function () {
  78124. return this.imageProcessingConfiguration.exposure;
  78125. },
  78126. /**
  78127. * Sets exposure used in the effect.
  78128. */
  78129. set: function (value) {
  78130. this.imageProcessingConfiguration.exposure = value;
  78131. },
  78132. enumerable: true,
  78133. configurable: true
  78134. });
  78135. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  78136. /**
  78137. * Gets wether tonemapping is enabled or not.
  78138. */
  78139. get: function () {
  78140. return this._imageProcessingConfiguration.toneMappingEnabled;
  78141. },
  78142. /**
  78143. * Sets wether tonemapping is enabled or not
  78144. */
  78145. set: function (value) {
  78146. this._imageProcessingConfiguration.toneMappingEnabled = value;
  78147. },
  78148. enumerable: true,
  78149. configurable: true
  78150. });
  78151. ;
  78152. ;
  78153. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  78154. /**
  78155. * Gets contrast used in the effect.
  78156. */
  78157. get: function () {
  78158. return this.imageProcessingConfiguration.contrast;
  78159. },
  78160. /**
  78161. * Sets contrast used in the effect.
  78162. */
  78163. set: function (value) {
  78164. this.imageProcessingConfiguration.contrast = value;
  78165. },
  78166. enumerable: true,
  78167. configurable: true
  78168. });
  78169. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  78170. /**
  78171. * Gets Vignette stretch size.
  78172. */
  78173. get: function () {
  78174. return this.imageProcessingConfiguration.vignetteStretch;
  78175. },
  78176. /**
  78177. * Sets Vignette stretch size.
  78178. */
  78179. set: function (value) {
  78180. this.imageProcessingConfiguration.vignetteStretch = value;
  78181. },
  78182. enumerable: true,
  78183. configurable: true
  78184. });
  78185. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  78186. /**
  78187. * Gets Vignette centre X Offset.
  78188. */
  78189. get: function () {
  78190. return this.imageProcessingConfiguration.vignetteCentreX;
  78191. },
  78192. /**
  78193. * Sets Vignette centre X Offset.
  78194. */
  78195. set: function (value) {
  78196. this.imageProcessingConfiguration.vignetteCentreX = value;
  78197. },
  78198. enumerable: true,
  78199. configurable: true
  78200. });
  78201. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  78202. /**
  78203. * Gets Vignette centre Y Offset.
  78204. */
  78205. get: function () {
  78206. return this.imageProcessingConfiguration.vignetteCentreY;
  78207. },
  78208. /**
  78209. * Sets Vignette centre Y Offset.
  78210. */
  78211. set: function (value) {
  78212. this.imageProcessingConfiguration.vignetteCentreY = value;
  78213. },
  78214. enumerable: true,
  78215. configurable: true
  78216. });
  78217. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  78218. /**
  78219. * Gets Vignette weight or intensity of the vignette effect.
  78220. */
  78221. get: function () {
  78222. return this.imageProcessingConfiguration.vignetteWeight;
  78223. },
  78224. /**
  78225. * Sets Vignette weight or intensity of the vignette effect.
  78226. */
  78227. set: function (value) {
  78228. this.imageProcessingConfiguration.vignetteWeight = value;
  78229. },
  78230. enumerable: true,
  78231. configurable: true
  78232. });
  78233. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  78234. /**
  78235. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  78236. * if vignetteEnabled is set to true.
  78237. */
  78238. get: function () {
  78239. return this.imageProcessingConfiguration.vignetteColor;
  78240. },
  78241. /**
  78242. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  78243. * if vignetteEnabled is set to true.
  78244. */
  78245. set: function (value) {
  78246. this.imageProcessingConfiguration.vignetteColor = value;
  78247. },
  78248. enumerable: true,
  78249. configurable: true
  78250. });
  78251. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  78252. /**
  78253. * Gets Camera field of view used by the Vignette effect.
  78254. */
  78255. get: function () {
  78256. return this.imageProcessingConfiguration.vignetteCameraFov;
  78257. },
  78258. /**
  78259. * Sets Camera field of view used by the Vignette effect.
  78260. */
  78261. set: function (value) {
  78262. this.imageProcessingConfiguration.vignetteCameraFov = value;
  78263. },
  78264. enumerable: true,
  78265. configurable: true
  78266. });
  78267. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  78268. /**
  78269. * Gets the vignette blend mode allowing different kind of effect.
  78270. */
  78271. get: function () {
  78272. return this.imageProcessingConfiguration.vignetteBlendMode;
  78273. },
  78274. /**
  78275. * Sets the vignette blend mode allowing different kind of effect.
  78276. */
  78277. set: function (value) {
  78278. this.imageProcessingConfiguration.vignetteBlendMode = value;
  78279. },
  78280. enumerable: true,
  78281. configurable: true
  78282. });
  78283. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  78284. /**
  78285. * Gets wether the vignette effect is enabled.
  78286. */
  78287. get: function () {
  78288. return this.imageProcessingConfiguration.vignetteEnabled;
  78289. },
  78290. /**
  78291. * Sets wether the vignette effect is enabled.
  78292. */
  78293. set: function (value) {
  78294. this.imageProcessingConfiguration.vignetteEnabled = value;
  78295. },
  78296. enumerable: true,
  78297. configurable: true
  78298. });
  78299. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  78300. /**
  78301. * Gets wether the input of the processing is in Gamma or Linear Space.
  78302. */
  78303. get: function () {
  78304. return this._fromLinearSpace;
  78305. },
  78306. /**
  78307. * Sets wether the input of the processing is in Gamma or Linear Space.
  78308. */
  78309. set: function (value) {
  78310. if (this._fromLinearSpace === value) {
  78311. return;
  78312. }
  78313. this._fromLinearSpace = value;
  78314. this._updateParameters();
  78315. },
  78316. enumerable: true,
  78317. configurable: true
  78318. });
  78319. ImageProcessingPostProcess.prototype.getClassName = function () {
  78320. return "ImageProcessingPostProcess";
  78321. };
  78322. ImageProcessingPostProcess.prototype._updateParameters = function () {
  78323. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  78324. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  78325. var defines = "";
  78326. for (var define in this._defines) {
  78327. if (this._defines[define]) {
  78328. defines += "#define " + define + ";\r\n";
  78329. }
  78330. }
  78331. var samplers = ["textureSampler"];
  78332. var uniforms = ["scale"];
  78333. if (BABYLON.ImageProcessingConfiguration) {
  78334. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  78335. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  78336. }
  78337. this.updateEffect(defines, uniforms, samplers);
  78338. };
  78339. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  78340. _super.prototype.dispose.call(this, camera);
  78341. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  78342. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  78343. }
  78344. if (this._imageProcessingConfiguration) {
  78345. this.imageProcessingConfiguration.applyByPostProcess = false;
  78346. }
  78347. };
  78348. __decorate([
  78349. BABYLON.serialize()
  78350. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  78351. return ImageProcessingPostProcess;
  78352. }(BABYLON.PostProcess));
  78353. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  78354. })(BABYLON || (BABYLON = {}));
  78355. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  78356. var BABYLON;
  78357. (function (BABYLON) {
  78358. /**
  78359. * Class used to store bone information
  78360. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  78361. */
  78362. var Bone = /** @class */ (function (_super) {
  78363. __extends(Bone, _super);
  78364. /**
  78365. * Create a new bone
  78366. * @param name defines the bone name
  78367. * @param skeleton defines the parent skeleton
  78368. * @param parentBone defines the parent (can be null if the bone is the root)
  78369. * @param localMatrix defines the local matrix
  78370. * @param restPose defines the rest pose matrix
  78371. * @param baseMatrix defines the base matrix
  78372. * @param index defines index of the bone in the hiearchy
  78373. */
  78374. function Bone(
  78375. /**
  78376. * defines the bone name
  78377. */
  78378. name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  78379. if (parentBone === void 0) { parentBone = null; }
  78380. if (localMatrix === void 0) { localMatrix = null; }
  78381. if (restPose === void 0) { restPose = null; }
  78382. if (baseMatrix === void 0) { baseMatrix = null; }
  78383. if (index === void 0) { index = null; }
  78384. var _this = _super.call(this, name, skeleton.getScene()) || this;
  78385. _this.name = name;
  78386. /**
  78387. * Gets the list of child bones
  78388. */
  78389. _this.children = new Array();
  78390. /** Gets the animations associated with this bone */
  78391. _this.animations = new Array();
  78392. /**
  78393. * @hidden Internal only
  78394. * Set this value to map this bone to a different index in the transform matrices
  78395. * Set this value to -1 to exclude the bone from the transform matrices
  78396. */
  78397. _this._index = null;
  78398. _this._absoluteTransform = new BABYLON.Matrix();
  78399. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  78400. _this._scalingDeterminant = 1;
  78401. _this._worldTransform = new BABYLON.Matrix();
  78402. _this._needToDecompose = true;
  78403. _this._needToCompose = false;
  78404. _this._skeleton = skeleton;
  78405. _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
  78406. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  78407. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  78408. _this._index = index;
  78409. skeleton.bones.push(_this);
  78410. _this.setParent(parentBone, false);
  78411. if (baseMatrix || localMatrix) {
  78412. _this._updateDifferenceMatrix();
  78413. }
  78414. return _this;
  78415. }
  78416. Object.defineProperty(Bone.prototype, "_matrix", {
  78417. /** @hidden */
  78418. get: function () {
  78419. this._compose();
  78420. return this._localMatrix;
  78421. },
  78422. /** @hidden */
  78423. set: function (value) {
  78424. this._localMatrix.copyFrom(value);
  78425. this._needToDecompose = true;
  78426. },
  78427. enumerable: true,
  78428. configurable: true
  78429. });
  78430. // Members
  78431. /**
  78432. * Gets the parent skeleton
  78433. * @returns a skeleton
  78434. */
  78435. Bone.prototype.getSkeleton = function () {
  78436. return this._skeleton;
  78437. };
  78438. /**
  78439. * Gets parent bone
  78440. * @returns a bone or null if the bone is the root of the bone hierarchy
  78441. */
  78442. Bone.prototype.getParent = function () {
  78443. return this._parent;
  78444. };
  78445. /**
  78446. * Sets the parent bone
  78447. * @param parent defines the parent (can be null if the bone is the root)
  78448. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  78449. */
  78450. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  78451. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  78452. if (this._parent === parent) {
  78453. return;
  78454. }
  78455. if (this._parent) {
  78456. var index = this._parent.children.indexOf(this);
  78457. if (index !== -1) {
  78458. this._parent.children.splice(index, 1);
  78459. }
  78460. }
  78461. this._parent = parent;
  78462. if (this._parent) {
  78463. this._parent.children.push(this);
  78464. }
  78465. if (updateDifferenceMatrix) {
  78466. this._updateDifferenceMatrix();
  78467. }
  78468. this.markAsDirty();
  78469. };
  78470. /**
  78471. * Gets the local matrix
  78472. * @returns a matrix
  78473. */
  78474. Bone.prototype.getLocalMatrix = function () {
  78475. this._compose();
  78476. return this._localMatrix;
  78477. };
  78478. /**
  78479. * Gets the base matrix (initial matrix which remains unchanged)
  78480. * @returns a matrix
  78481. */
  78482. Bone.prototype.getBaseMatrix = function () {
  78483. return this._baseMatrix;
  78484. };
  78485. /**
  78486. * Gets the rest pose matrix
  78487. * @returns a matrix
  78488. */
  78489. Bone.prototype.getRestPose = function () {
  78490. return this._restPose;
  78491. };
  78492. /**
  78493. * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)
  78494. */
  78495. Bone.prototype.getWorldMatrix = function () {
  78496. return this._worldTransform;
  78497. };
  78498. /**
  78499. * Sets the local matrix to rest pose matrix
  78500. */
  78501. Bone.prototype.returnToRest = function () {
  78502. this.updateMatrix(this._restPose.clone());
  78503. };
  78504. /**
  78505. * Gets the inverse of the absolute transform matrix.
  78506. * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)
  78507. * @returns a matrix
  78508. */
  78509. Bone.prototype.getInvertedAbsoluteTransform = function () {
  78510. return this._invertedAbsoluteTransform;
  78511. };
  78512. /**
  78513. * Gets the absolute transform matrix (ie base matrix * parent world matrix)
  78514. * @returns a matrix
  78515. */
  78516. Bone.prototype.getAbsoluteTransform = function () {
  78517. return this._absoluteTransform;
  78518. };
  78519. Object.defineProperty(Bone.prototype, "position", {
  78520. // Properties (matches AbstractMesh properties)
  78521. /** Gets or sets current position (in local space) */
  78522. get: function () {
  78523. this._decompose();
  78524. return this._localPosition;
  78525. },
  78526. set: function (newPosition) {
  78527. this._decompose();
  78528. this._localPosition.copyFrom(newPosition);
  78529. this._markAsDirtyAndCompose();
  78530. },
  78531. enumerable: true,
  78532. configurable: true
  78533. });
  78534. Object.defineProperty(Bone.prototype, "rotation", {
  78535. /** Gets or sets current rotation (in local space) */
  78536. get: function () {
  78537. return this.getRotation();
  78538. },
  78539. set: function (newRotation) {
  78540. this.setRotation(newRotation);
  78541. },
  78542. enumerable: true,
  78543. configurable: true
  78544. });
  78545. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  78546. /** Gets or sets current rotation quaternion (in local space) */
  78547. get: function () {
  78548. this._decompose();
  78549. return this._localRotation;
  78550. },
  78551. set: function (newRotation) {
  78552. this.setRotationQuaternion(newRotation);
  78553. },
  78554. enumerable: true,
  78555. configurable: true
  78556. });
  78557. Object.defineProperty(Bone.prototype, "scaling", {
  78558. /** Gets or sets current scaling (in local space) */
  78559. get: function () {
  78560. return this.getScale();
  78561. },
  78562. set: function (newScaling) {
  78563. this.setScale(newScaling);
  78564. },
  78565. enumerable: true,
  78566. configurable: true
  78567. });
  78568. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  78569. /**
  78570. * Gets the animation properties override
  78571. */
  78572. get: function () {
  78573. return this._skeleton.animationPropertiesOverride;
  78574. },
  78575. enumerable: true,
  78576. configurable: true
  78577. });
  78578. // Methods
  78579. Bone.prototype._decompose = function () {
  78580. if (!this._needToDecompose) {
  78581. return;
  78582. }
  78583. this._needToDecompose = false;
  78584. if (!this._localScaling) {
  78585. this._localScaling = BABYLON.Vector3.Zero();
  78586. this._localRotation = BABYLON.Quaternion.Zero();
  78587. this._localPosition = BABYLON.Vector3.Zero();
  78588. }
  78589. this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
  78590. };
  78591. Bone.prototype._compose = function () {
  78592. if (!this._needToCompose) {
  78593. return;
  78594. }
  78595. this._needToCompose = false;
  78596. BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
  78597. };
  78598. /**
  78599. * Update the base and local matrices
  78600. * @param matrix defines the new base or local matrix
  78601. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  78602. * @param updateLocalMatrix defines if the local matrix should be updated
  78603. */
  78604. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {
  78605. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  78606. if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }
  78607. this._baseMatrix.copyFrom(matrix);
  78608. if (updateDifferenceMatrix) {
  78609. this._updateDifferenceMatrix();
  78610. }
  78611. if (updateLocalMatrix) {
  78612. this._localMatrix.copyFrom(matrix);
  78613. this._markAsDirtyAndDecompose();
  78614. }
  78615. else {
  78616. this.markAsDirty();
  78617. }
  78618. };
  78619. /** @hidden */
  78620. Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {
  78621. if (updateChildren === void 0) { updateChildren = true; }
  78622. if (!rootMatrix) {
  78623. rootMatrix = this._baseMatrix;
  78624. }
  78625. if (this._parent) {
  78626. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  78627. }
  78628. else {
  78629. this._absoluteTransform.copyFrom(rootMatrix);
  78630. }
  78631. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  78632. if (updateChildren) {
  78633. for (var index = 0; index < this.children.length; index++) {
  78634. this.children[index]._updateDifferenceMatrix();
  78635. }
  78636. }
  78637. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  78638. };
  78639. /**
  78640. * Flag the bone as dirty (Forcing it to update everything)
  78641. */
  78642. Bone.prototype.markAsDirty = function () {
  78643. this._currentRenderId++;
  78644. this._childRenderId++;
  78645. this._skeleton._markAsDirty();
  78646. };
  78647. Bone.prototype._markAsDirtyAndCompose = function () {
  78648. this.markAsDirty();
  78649. this._needToCompose = true;
  78650. };
  78651. Bone.prototype._markAsDirtyAndDecompose = function () {
  78652. this.markAsDirty();
  78653. this._needToDecompose = true;
  78654. };
  78655. /**
  78656. * Copy an animation range from another bone
  78657. * @param source defines the source bone
  78658. * @param rangeName defines the range name to copy
  78659. * @param frameOffset defines the frame offset
  78660. * @param rescaleAsRequired defines if rescaling must be applied if required
  78661. * @param skelDimensionsRatio defines the scaling ratio
  78662. * @returns true if operation was successful
  78663. */
  78664. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  78665. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  78666. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  78667. // all animation may be coming from a library skeleton, so may need to create animation
  78668. if (this.animations.length === 0) {
  78669. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  78670. this.animations[0].setKeys([]);
  78671. }
  78672. // get animation info / verify there is such a range from the source bone
  78673. var sourceRange = source.animations[0].getRange(rangeName);
  78674. if (!sourceRange) {
  78675. return false;
  78676. }
  78677. var from = sourceRange.from;
  78678. var to = sourceRange.to;
  78679. var sourceKeys = source.animations[0].getKeys();
  78680. // rescaling prep
  78681. var sourceBoneLength = source.length;
  78682. var sourceParent = source.getParent();
  78683. var parent = this.getParent();
  78684. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  78685. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  78686. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  78687. var destKeys = this.animations[0].getKeys();
  78688. // loop vars declaration
  78689. var orig;
  78690. var origTranslation;
  78691. var mat;
  78692. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  78693. orig = sourceKeys[key];
  78694. if (orig.frame >= from && orig.frame <= to) {
  78695. if (rescaleAsRequired) {
  78696. mat = orig.value.clone();
  78697. // scale based on parent ratio, when bone has parent
  78698. if (parentScalingReqd) {
  78699. origTranslation = mat.getTranslation();
  78700. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  78701. // scale based on skeleton dimension ratio when root bone, and value is passed
  78702. }
  78703. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  78704. origTranslation = mat.getTranslation();
  78705. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  78706. // use original when root bone, and no data for skelDimensionsRatio
  78707. }
  78708. else {
  78709. mat = orig.value;
  78710. }
  78711. }
  78712. else {
  78713. mat = orig.value;
  78714. }
  78715. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  78716. }
  78717. }
  78718. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  78719. return true;
  78720. };
  78721. /**
  78722. * Translate the bone in local or world space
  78723. * @param vec The amount to translate the bone
  78724. * @param space The space that the translation is in
  78725. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78726. */
  78727. Bone.prototype.translate = function (vec, space, mesh) {
  78728. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78729. var lm = this.getLocalMatrix();
  78730. if (space == BABYLON.Space.LOCAL) {
  78731. lm.m[12] += vec.x;
  78732. lm.m[13] += vec.y;
  78733. lm.m[14] += vec.z;
  78734. }
  78735. else {
  78736. var wm = null;
  78737. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78738. if (mesh) {
  78739. wm = mesh.getWorldMatrix();
  78740. }
  78741. this._skeleton.computeAbsoluteTransforms();
  78742. var tmat = Bone._tmpMats[0];
  78743. var tvec = Bone._tmpVecs[0];
  78744. if (this._parent) {
  78745. if (mesh && wm) {
  78746. tmat.copyFrom(this._parent.getAbsoluteTransform());
  78747. tmat.multiplyToRef(wm, tmat);
  78748. }
  78749. else {
  78750. tmat.copyFrom(this._parent.getAbsoluteTransform());
  78751. }
  78752. }
  78753. tmat.m[12] = 0;
  78754. tmat.m[13] = 0;
  78755. tmat.m[14] = 0;
  78756. tmat.invert();
  78757. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  78758. lm.m[12] += tvec.x;
  78759. lm.m[13] += tvec.y;
  78760. lm.m[14] += tvec.z;
  78761. }
  78762. this._markAsDirtyAndDecompose();
  78763. };
  78764. /**
  78765. * Set the postion of the bone in local or world space
  78766. * @param position The position to set the bone
  78767. * @param space The space that the position is in
  78768. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78769. */
  78770. Bone.prototype.setPosition = function (position, space, mesh) {
  78771. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78772. var lm = this.getLocalMatrix();
  78773. if (space == BABYLON.Space.LOCAL) {
  78774. lm.m[12] = position.x;
  78775. lm.m[13] = position.y;
  78776. lm.m[14] = position.z;
  78777. }
  78778. else {
  78779. var wm = null;
  78780. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78781. if (mesh) {
  78782. wm = mesh.getWorldMatrix();
  78783. }
  78784. this._skeleton.computeAbsoluteTransforms();
  78785. var tmat = Bone._tmpMats[0];
  78786. var vec = Bone._tmpVecs[0];
  78787. if (this._parent) {
  78788. if (mesh && wm) {
  78789. tmat.copyFrom(this._parent.getAbsoluteTransform());
  78790. tmat.multiplyToRef(wm, tmat);
  78791. }
  78792. else {
  78793. tmat.copyFrom(this._parent.getAbsoluteTransform());
  78794. }
  78795. }
  78796. tmat.invert();
  78797. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  78798. lm.m[12] = vec.x;
  78799. lm.m[13] = vec.y;
  78800. lm.m[14] = vec.z;
  78801. }
  78802. this._markAsDirtyAndDecompose();
  78803. };
  78804. /**
  78805. * Set the absolute position of the bone (world space)
  78806. * @param position The position to set the bone
  78807. * @param mesh The mesh that this bone is attached to
  78808. */
  78809. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  78810. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  78811. };
  78812. /**
  78813. * Scale the bone on the x, y and z axes (in local space)
  78814. * @param x The amount to scale the bone on the x axis
  78815. * @param y The amount to scale the bone on the y axis
  78816. * @param z The amount to scale the bone on the z axis
  78817. * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)
  78818. */
  78819. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  78820. if (scaleChildren === void 0) { scaleChildren = false; }
  78821. var locMat = this.getLocalMatrix();
  78822. // Apply new scaling on top of current local matrix
  78823. var scaleMat = Bone._tmpMats[0];
  78824. BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
  78825. scaleMat.multiplyToRef(locMat, locMat);
  78826. // Invert scaling matrix and apply the inverse to all children
  78827. scaleMat.invert();
  78828. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  78829. var child = _a[_i];
  78830. var cm = child.getLocalMatrix();
  78831. cm.multiplyToRef(scaleMat, cm);
  78832. cm.m[12] *= x;
  78833. cm.m[13] *= y;
  78834. cm.m[14] *= z;
  78835. child._markAsDirtyAndDecompose();
  78836. }
  78837. this._markAsDirtyAndDecompose();
  78838. if (scaleChildren) {
  78839. for (var _b = 0, _c = this.children; _b < _c.length; _b++) {
  78840. var child = _c[_b];
  78841. child.scale(x, y, z, scaleChildren);
  78842. }
  78843. }
  78844. };
  78845. /**
  78846. * Set the bone scaling in local space
  78847. * @param scale defines the scaling vector
  78848. */
  78849. Bone.prototype.setScale = function (scale) {
  78850. this._decompose();
  78851. this._localScaling.copyFrom(scale);
  78852. this._markAsDirtyAndCompose();
  78853. };
  78854. /**
  78855. * Gets the current scaling in local space
  78856. * @returns the current scaling vector
  78857. */
  78858. Bone.prototype.getScale = function () {
  78859. this._decompose();
  78860. return this._localScaling;
  78861. };
  78862. /**
  78863. * Gets the current scaling in local space and stores it in a target vector
  78864. * @param result defines the target vector
  78865. */
  78866. Bone.prototype.getScaleToRef = function (result) {
  78867. this._decompose();
  78868. result.copyFrom(this._localScaling);
  78869. };
  78870. /**
  78871. * Set the yaw, pitch, and roll of the bone in local or world space
  78872. * @param yaw The rotation of the bone on the y axis
  78873. * @param pitch The rotation of the bone on the x axis
  78874. * @param roll The rotation of the bone on the z axis
  78875. * @param space The space that the axes of rotation are in
  78876. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78877. */
  78878. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  78879. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78880. if (space === BABYLON.Space.LOCAL) {
  78881. var quat = Bone._tmpQuat;
  78882. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
  78883. this.setRotationQuaternion(quat, space, mesh);
  78884. return;
  78885. }
  78886. var rotMatInv = Bone._tmpMats[0];
  78887. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  78888. return;
  78889. }
  78890. var rotMat = Bone._tmpMats[1];
  78891. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  78892. rotMatInv.multiplyToRef(rotMat, rotMat);
  78893. this._rotateWithMatrix(rotMat, space, mesh);
  78894. };
  78895. /**
  78896. * Add a rotation to the bone on an axis in local or world space
  78897. * @param axis The axis to rotate the bone on
  78898. * @param amount The amount to rotate the bone
  78899. * @param space The space that the axis is in
  78900. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78901. */
  78902. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  78903. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78904. var rmat = Bone._tmpMats[0];
  78905. rmat.m[12] = 0;
  78906. rmat.m[13] = 0;
  78907. rmat.m[14] = 0;
  78908. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  78909. this._rotateWithMatrix(rmat, space, mesh);
  78910. };
  78911. /**
  78912. * Set the rotation of the bone to a particular axis angle in local or world space
  78913. * @param axis The axis to rotate the bone on
  78914. * @param angle The angle that the bone should be rotated to
  78915. * @param space The space that the axis is in
  78916. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78917. */
  78918. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  78919. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78920. if (space === BABYLON.Space.LOCAL) {
  78921. var quat = Bone._tmpQuat;
  78922. BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);
  78923. this.setRotationQuaternion(quat, space, mesh);
  78924. return;
  78925. }
  78926. var rotMatInv = Bone._tmpMats[0];
  78927. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  78928. return;
  78929. }
  78930. var rotMat = Bone._tmpMats[1];
  78931. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  78932. rotMatInv.multiplyToRef(rotMat, rotMat);
  78933. this._rotateWithMatrix(rotMat, space, mesh);
  78934. };
  78935. /**
  78936. * Set the euler rotation of the bone in local of world space
  78937. * @param rotation The euler rotation that the bone should be set to
  78938. * @param space The space that the rotation is in
  78939. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78940. */
  78941. Bone.prototype.setRotation = function (rotation, space, mesh) {
  78942. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78943. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  78944. };
  78945. /**
  78946. * Set the quaternion rotation of the bone in local of world space
  78947. * @param quat The quaternion rotation that the bone should be set to
  78948. * @param space The space that the rotation is in
  78949. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78950. */
  78951. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  78952. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78953. if (space === BABYLON.Space.LOCAL) {
  78954. this._decompose();
  78955. this._localRotation.copyFrom(quat);
  78956. this._markAsDirtyAndCompose();
  78957. return;
  78958. }
  78959. var rotMatInv = Bone._tmpMats[0];
  78960. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  78961. return;
  78962. }
  78963. var rotMat = Bone._tmpMats[1];
  78964. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  78965. rotMatInv.multiplyToRef(rotMat, rotMat);
  78966. this._rotateWithMatrix(rotMat, space, mesh);
  78967. };
  78968. /**
  78969. * Set the rotation matrix of the bone in local of world space
  78970. * @param rotMat The rotation matrix that the bone should be set to
  78971. * @param space The space that the rotation is in
  78972. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78973. */
  78974. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  78975. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78976. if (space === BABYLON.Space.LOCAL) {
  78977. var quat = Bone._tmpQuat;
  78978. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);
  78979. this.setRotationQuaternion(quat, space, mesh);
  78980. return;
  78981. }
  78982. var rotMatInv = Bone._tmpMats[0];
  78983. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  78984. return;
  78985. }
  78986. var rotMat2 = Bone._tmpMats[1];
  78987. rotMat2.copyFrom(rotMat);
  78988. rotMatInv.multiplyToRef(rotMat, rotMat2);
  78989. this._rotateWithMatrix(rotMat2, space, mesh);
  78990. };
  78991. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  78992. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78993. var lmat = this.getLocalMatrix();
  78994. var lx = lmat.m[12];
  78995. var ly = lmat.m[13];
  78996. var lz = lmat.m[14];
  78997. var parent = this.getParent();
  78998. var parentScale = Bone._tmpMats[3];
  78999. var parentScaleInv = Bone._tmpMats[4];
  79000. if (parent && space == BABYLON.Space.WORLD) {
  79001. if (mesh) {
  79002. parentScale.copyFrom(mesh.getWorldMatrix());
  79003. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  79004. }
  79005. else {
  79006. parentScale.copyFrom(parent.getAbsoluteTransform());
  79007. }
  79008. parentScaleInv.copyFrom(parentScale);
  79009. parentScaleInv.invert();
  79010. lmat.multiplyToRef(parentScale, lmat);
  79011. lmat.multiplyToRef(rmat, lmat);
  79012. lmat.multiplyToRef(parentScaleInv, lmat);
  79013. }
  79014. else {
  79015. if (space == BABYLON.Space.WORLD && mesh) {
  79016. parentScale.copyFrom(mesh.getWorldMatrix());
  79017. parentScaleInv.copyFrom(parentScale);
  79018. parentScaleInv.invert();
  79019. lmat.multiplyToRef(parentScale, lmat);
  79020. lmat.multiplyToRef(rmat, lmat);
  79021. lmat.multiplyToRef(parentScaleInv, lmat);
  79022. }
  79023. else {
  79024. lmat.multiplyToRef(rmat, lmat);
  79025. }
  79026. }
  79027. lmat.m[12] = lx;
  79028. lmat.m[13] = ly;
  79029. lmat.m[14] = lz;
  79030. this.computeAbsoluteTransforms();
  79031. this._markAsDirtyAndDecompose();
  79032. };
  79033. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {
  79034. var scaleMatrix = Bone._tmpMats[2];
  79035. rotMatInv.copyFrom(this.getAbsoluteTransform());
  79036. if (mesh) {
  79037. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  79038. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);
  79039. }
  79040. rotMatInv.invert();
  79041. if (isNaN(rotMatInv.m[0])) {
  79042. // Matrix failed to invert.
  79043. // This can happen if scale is zero for example.
  79044. return false;
  79045. }
  79046. scaleMatrix.m[0] *= this._scalingDeterminant;
  79047. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  79048. return true;
  79049. };
  79050. /**
  79051. * Get the position of the bone in local or world space
  79052. * @param space The space that the returned position is in
  79053. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79054. * @returns The position of the bone
  79055. */
  79056. Bone.prototype.getPosition = function (space, mesh) {
  79057. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79058. if (mesh === void 0) { mesh = null; }
  79059. var pos = BABYLON.Vector3.Zero();
  79060. this.getPositionToRef(space, mesh, pos);
  79061. return pos;
  79062. };
  79063. /**
  79064. * Copy the position of the bone to a vector3 in local or world space
  79065. * @param space The space that the returned position is in
  79066. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79067. * @param result The vector3 to copy the position to
  79068. */
  79069. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  79070. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79071. if (space == BABYLON.Space.LOCAL) {
  79072. var lm = this.getLocalMatrix();
  79073. result.x = lm.m[12];
  79074. result.y = lm.m[13];
  79075. result.z = lm.m[14];
  79076. }
  79077. else {
  79078. var wm = null;
  79079. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  79080. if (mesh) {
  79081. wm = mesh.getWorldMatrix();
  79082. }
  79083. this._skeleton.computeAbsoluteTransforms();
  79084. var tmat = Bone._tmpMats[0];
  79085. if (mesh && wm) {
  79086. tmat.copyFrom(this.getAbsoluteTransform());
  79087. tmat.multiplyToRef(wm, tmat);
  79088. }
  79089. else {
  79090. tmat = this.getAbsoluteTransform();
  79091. }
  79092. result.x = tmat.m[12];
  79093. result.y = tmat.m[13];
  79094. result.z = tmat.m[14];
  79095. }
  79096. };
  79097. /**
  79098. * Get the absolute position of the bone (world space)
  79099. * @param mesh The mesh that this bone is attached to
  79100. * @returns The absolute position of the bone
  79101. */
  79102. Bone.prototype.getAbsolutePosition = function (mesh) {
  79103. if (mesh === void 0) { mesh = null; }
  79104. var pos = BABYLON.Vector3.Zero();
  79105. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  79106. return pos;
  79107. };
  79108. /**
  79109. * Copy the absolute position of the bone (world space) to the result param
  79110. * @param mesh The mesh that this bone is attached to
  79111. * @param result The vector3 to copy the absolute position to
  79112. */
  79113. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  79114. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  79115. };
  79116. /**
  79117. * Compute the absolute transforms of this bone and its children
  79118. */
  79119. Bone.prototype.computeAbsoluteTransforms = function () {
  79120. this._compose();
  79121. if (this._parent) {
  79122. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  79123. }
  79124. else {
  79125. this._absoluteTransform.copyFrom(this._localMatrix);
  79126. var poseMatrix = this._skeleton.getPoseMatrix();
  79127. if (poseMatrix) {
  79128. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  79129. }
  79130. }
  79131. var children = this.children;
  79132. var len = children.length;
  79133. for (var i = 0; i < len; i++) {
  79134. children[i].computeAbsoluteTransforms();
  79135. }
  79136. };
  79137. /**
  79138. * Get the world direction from an axis that is in the local space of the bone
  79139. * @param localAxis The local direction that is used to compute the world direction
  79140. * @param mesh The mesh that this bone is attached to
  79141. * @returns The world direction
  79142. */
  79143. Bone.prototype.getDirection = function (localAxis, mesh) {
  79144. if (mesh === void 0) { mesh = null; }
  79145. var result = BABYLON.Vector3.Zero();
  79146. this.getDirectionToRef(localAxis, mesh, result);
  79147. return result;
  79148. };
  79149. /**
  79150. * Copy the world direction to a vector3 from an axis that is in the local space of the bone
  79151. * @param localAxis The local direction that is used to compute the world direction
  79152. * @param mesh The mesh that this bone is attached to
  79153. * @param result The vector3 that the world direction will be copied to
  79154. */
  79155. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  79156. if (mesh === void 0) { mesh = null; }
  79157. var wm = null;
  79158. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  79159. if (mesh) {
  79160. wm = mesh.getWorldMatrix();
  79161. }
  79162. this._skeleton.computeAbsoluteTransforms();
  79163. var mat = Bone._tmpMats[0];
  79164. mat.copyFrom(this.getAbsoluteTransform());
  79165. if (mesh && wm) {
  79166. mat.multiplyToRef(wm, mat);
  79167. }
  79168. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  79169. result.normalize();
  79170. };
  79171. /**
  79172. * Get the euler rotation of the bone in local or world space
  79173. * @param space The space that the rotation should be in
  79174. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79175. * @returns The euler rotation
  79176. */
  79177. Bone.prototype.getRotation = function (space, mesh) {
  79178. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79179. if (mesh === void 0) { mesh = null; }
  79180. var result = BABYLON.Vector3.Zero();
  79181. this.getRotationToRef(space, mesh, result);
  79182. return result;
  79183. };
  79184. /**
  79185. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space
  79186. * @param space The space that the rotation should be in
  79187. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79188. * @param result The vector3 that the rotation should be copied to
  79189. */
  79190. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  79191. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79192. if (mesh === void 0) { mesh = null; }
  79193. var quat = Bone._tmpQuat;
  79194. this.getRotationQuaternionToRef(space, mesh, quat);
  79195. quat.toEulerAnglesToRef(result);
  79196. };
  79197. /**
  79198. * Get the quaternion rotation of the bone in either local or world space
  79199. * @param space The space that the rotation should be in
  79200. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79201. * @returns The quaternion rotation
  79202. */
  79203. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  79204. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79205. if (mesh === void 0) { mesh = null; }
  79206. var result = BABYLON.Quaternion.Identity();
  79207. this.getRotationQuaternionToRef(space, mesh, result);
  79208. return result;
  79209. };
  79210. /**
  79211. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space
  79212. * @param space The space that the rotation should be in
  79213. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79214. * @param result The quaternion that the rotation should be copied to
  79215. */
  79216. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  79217. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79218. if (mesh === void 0) { mesh = null; }
  79219. if (space == BABYLON.Space.LOCAL) {
  79220. this._decompose();
  79221. result.copyFrom(this._localRotation);
  79222. }
  79223. else {
  79224. var mat = Bone._tmpMats[0];
  79225. var amat = this.getAbsoluteTransform();
  79226. if (mesh) {
  79227. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  79228. }
  79229. else {
  79230. mat.copyFrom(amat);
  79231. }
  79232. mat.m[0] *= this._scalingDeterminant;
  79233. mat.m[1] *= this._scalingDeterminant;
  79234. mat.m[2] *= this._scalingDeterminant;
  79235. mat.decompose(undefined, result, undefined);
  79236. }
  79237. };
  79238. /**
  79239. * Get the rotation matrix of the bone in local or world space
  79240. * @param space The space that the rotation should be in
  79241. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79242. * @returns The rotation matrix
  79243. */
  79244. Bone.prototype.getRotationMatrix = function (space, mesh) {
  79245. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79246. var result = BABYLON.Matrix.Identity();
  79247. this.getRotationMatrixToRef(space, mesh, result);
  79248. return result;
  79249. };
  79250. /**
  79251. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space
  79252. * @param space The space that the rotation should be in
  79253. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79254. * @param result The quaternion that the rotation should be copied to
  79255. */
  79256. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  79257. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79258. if (space == BABYLON.Space.LOCAL) {
  79259. this.getLocalMatrix().getRotationMatrixToRef(result);
  79260. }
  79261. else {
  79262. var mat = Bone._tmpMats[0];
  79263. var amat = this.getAbsoluteTransform();
  79264. if (mesh) {
  79265. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  79266. }
  79267. else {
  79268. mat.copyFrom(amat);
  79269. }
  79270. mat.m[0] *= this._scalingDeterminant;
  79271. mat.m[1] *= this._scalingDeterminant;
  79272. mat.m[2] *= this._scalingDeterminant;
  79273. mat.getRotationMatrixToRef(result);
  79274. }
  79275. };
  79276. /**
  79277. * Get the world position of a point that is in the local space of the bone
  79278. * @param position The local position
  79279. * @param mesh The mesh that this bone is attached to
  79280. * @returns The world position
  79281. */
  79282. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  79283. if (mesh === void 0) { mesh = null; }
  79284. var result = BABYLON.Vector3.Zero();
  79285. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  79286. return result;
  79287. };
  79288. /**
  79289. * Get the world position of a point that is in the local space of the bone and copy it to the result param
  79290. * @param position The local position
  79291. * @param mesh The mesh that this bone is attached to
  79292. * @param result The vector3 that the world position should be copied to
  79293. */
  79294. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  79295. if (mesh === void 0) { mesh = null; }
  79296. var wm = null;
  79297. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  79298. if (mesh) {
  79299. wm = mesh.getWorldMatrix();
  79300. }
  79301. this._skeleton.computeAbsoluteTransforms();
  79302. var tmat = Bone._tmpMats[0];
  79303. if (mesh && wm) {
  79304. tmat.copyFrom(this.getAbsoluteTransform());
  79305. tmat.multiplyToRef(wm, tmat);
  79306. }
  79307. else {
  79308. tmat = this.getAbsoluteTransform();
  79309. }
  79310. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  79311. };
  79312. /**
  79313. * Get the local position of a point that is in world space
  79314. * @param position The world position
  79315. * @param mesh The mesh that this bone is attached to
  79316. * @returns The local position
  79317. */
  79318. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  79319. if (mesh === void 0) { mesh = null; }
  79320. var result = BABYLON.Vector3.Zero();
  79321. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  79322. return result;
  79323. };
  79324. /**
  79325. * Get the local position of a point that is in world space and copy it to the result param
  79326. * @param position The world position
  79327. * @param mesh The mesh that this bone is attached to
  79328. * @param result The vector3 that the local position should be copied to
  79329. */
  79330. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  79331. if (mesh === void 0) { mesh = null; }
  79332. var wm = null;
  79333. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  79334. if (mesh) {
  79335. wm = mesh.getWorldMatrix();
  79336. }
  79337. this._skeleton.computeAbsoluteTransforms();
  79338. var tmat = Bone._tmpMats[0];
  79339. tmat.copyFrom(this.getAbsoluteTransform());
  79340. if (mesh && wm) {
  79341. tmat.multiplyToRef(wm, tmat);
  79342. }
  79343. tmat.invert();
  79344. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  79345. };
  79346. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  79347. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  79348. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  79349. return Bone;
  79350. }(BABYLON.Node));
  79351. BABYLON.Bone = Bone;
  79352. })(BABYLON || (BABYLON = {}));
  79353. //# sourceMappingURL=babylon.bone.js.map
  79354. var BABYLON;
  79355. (function (BABYLON) {
  79356. /**
  79357. * Class used to apply inverse kinematics to bones
  79358. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller
  79359. */
  79360. var BoneIKController = /** @class */ (function () {
  79361. /**
  79362. * Creates a new BoneIKController
  79363. * @param mesh defines the mesh to control
  79364. * @param bone defines the bone to control
  79365. * @param options defines options to set up the controller
  79366. */
  79367. function BoneIKController(mesh, bone, options) {
  79368. /**
  79369. * Gets or sets the target position
  79370. */
  79371. this.targetPosition = BABYLON.Vector3.Zero();
  79372. /**
  79373. * Gets or sets the pole target position
  79374. */
  79375. this.poleTargetPosition = BABYLON.Vector3.Zero();
  79376. /**
  79377. * Gets or sets the pole target local offset
  79378. */
  79379. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  79380. /**
  79381. * Gets or sets the pole angle
  79382. */
  79383. this.poleAngle = 0;
  79384. /**
  79385. * 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)
  79386. */
  79387. this.slerpAmount = 1;
  79388. this._bone1Quat = BABYLON.Quaternion.Identity();
  79389. this._bone1Mat = BABYLON.Matrix.Identity();
  79390. this._bone2Ang = Math.PI;
  79391. this._maxAngle = Math.PI;
  79392. this._rightHandedSystem = false;
  79393. this._bendAxis = BABYLON.Vector3.Right();
  79394. this._slerping = false;
  79395. this._adjustRoll = 0;
  79396. this._bone2 = bone;
  79397. this._bone1 = bone.getParent();
  79398. if (!this._bone1) {
  79399. return;
  79400. }
  79401. this.mesh = mesh;
  79402. var bonePos = bone.getPosition();
  79403. if (bone.getAbsoluteTransform().determinant() > 0) {
  79404. this._rightHandedSystem = true;
  79405. this._bendAxis.x = 0;
  79406. this._bendAxis.y = 0;
  79407. this._bendAxis.z = -1;
  79408. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  79409. this._adjustRoll = Math.PI * .5;
  79410. this._bendAxis.z = 1;
  79411. }
  79412. }
  79413. if (this._bone1.length) {
  79414. var boneScale1 = this._bone1.getScale();
  79415. var boneScale2 = this._bone2.getScale();
  79416. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  79417. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  79418. }
  79419. else if (this._bone1.children[0]) {
  79420. mesh.computeWorldMatrix(true);
  79421. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  79422. var pos2 = this._bone2.getAbsolutePosition(mesh);
  79423. var pos3 = this._bone1.getAbsolutePosition(mesh);
  79424. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  79425. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  79426. }
  79427. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  79428. this.maxAngle = Math.PI;
  79429. if (options) {
  79430. if (options.targetMesh) {
  79431. this.targetMesh = options.targetMesh;
  79432. this.targetMesh.computeWorldMatrix(true);
  79433. }
  79434. if (options.poleTargetMesh) {
  79435. this.poleTargetMesh = options.poleTargetMesh;
  79436. this.poleTargetMesh.computeWorldMatrix(true);
  79437. }
  79438. else if (options.poleTargetBone) {
  79439. this.poleTargetBone = options.poleTargetBone;
  79440. }
  79441. else if (this._bone1.getParent()) {
  79442. this.poleTargetBone = this._bone1.getParent();
  79443. }
  79444. if (options.poleTargetLocalOffset) {
  79445. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  79446. }
  79447. if (options.poleAngle) {
  79448. this.poleAngle = options.poleAngle;
  79449. }
  79450. if (options.bendAxis) {
  79451. this._bendAxis.copyFrom(options.bendAxis);
  79452. }
  79453. if (options.maxAngle) {
  79454. this.maxAngle = options.maxAngle;
  79455. }
  79456. if (options.slerpAmount) {
  79457. this.slerpAmount = options.slerpAmount;
  79458. }
  79459. }
  79460. }
  79461. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  79462. /**
  79463. * Gets or sets maximum allowed angle
  79464. */
  79465. get: function () {
  79466. return this._maxAngle;
  79467. },
  79468. set: function (value) {
  79469. this._setMaxAngle(value);
  79470. },
  79471. enumerable: true,
  79472. configurable: true
  79473. });
  79474. BoneIKController.prototype._setMaxAngle = function (ang) {
  79475. if (ang < 0) {
  79476. ang = 0;
  79477. }
  79478. if (ang > Math.PI || ang == undefined) {
  79479. ang = Math.PI;
  79480. }
  79481. this._maxAngle = ang;
  79482. var a = this._bone1Length;
  79483. var b = this._bone2Length;
  79484. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  79485. };
  79486. /**
  79487. * Force the controller to update the bones
  79488. */
  79489. BoneIKController.prototype.update = function () {
  79490. var bone1 = this._bone1;
  79491. if (!bone1) {
  79492. return;
  79493. }
  79494. var target = this.targetPosition;
  79495. var poleTarget = this.poleTargetPosition;
  79496. var mat1 = BoneIKController._tmpMats[0];
  79497. var mat2 = BoneIKController._tmpMats[1];
  79498. if (this.targetMesh) {
  79499. target.copyFrom(this.targetMesh.getAbsolutePosition());
  79500. }
  79501. if (this.poleTargetBone) {
  79502. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  79503. }
  79504. else if (this.poleTargetMesh) {
  79505. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  79506. }
  79507. var bonePos = BoneIKController._tmpVecs[0];
  79508. var zaxis = BoneIKController._tmpVecs[1];
  79509. var xaxis = BoneIKController._tmpVecs[2];
  79510. var yaxis = BoneIKController._tmpVecs[3];
  79511. var upAxis = BoneIKController._tmpVecs[4];
  79512. var _tmpQuat = BoneIKController._tmpQuat;
  79513. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  79514. poleTarget.subtractToRef(bonePos, upAxis);
  79515. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  79516. upAxis.y = 1;
  79517. }
  79518. else {
  79519. upAxis.normalize();
  79520. }
  79521. target.subtractToRef(bonePos, yaxis);
  79522. yaxis.normalize();
  79523. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  79524. zaxis.normalize();
  79525. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  79526. xaxis.normalize();
  79527. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  79528. var a = this._bone1Length;
  79529. var b = this._bone2Length;
  79530. var c = BABYLON.Vector3.Distance(bonePos, target);
  79531. if (this._maxReach > 0) {
  79532. c = Math.min(this._maxReach, c);
  79533. }
  79534. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  79535. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  79536. if (acosa > 1) {
  79537. acosa = 1;
  79538. }
  79539. if (acosb > 1) {
  79540. acosb = 1;
  79541. }
  79542. if (acosa < -1) {
  79543. acosa = -1;
  79544. }
  79545. if (acosb < -1) {
  79546. acosb = -1;
  79547. }
  79548. var angA = Math.acos(acosa);
  79549. var angB = Math.acos(acosb);
  79550. var angC = -angA - angB;
  79551. if (this._rightHandedSystem) {
  79552. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  79553. mat2.multiplyToRef(mat1, mat1);
  79554. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  79555. mat2.multiplyToRef(mat1, mat1);
  79556. }
  79557. else {
  79558. var _tmpVec = BoneIKController._tmpVecs[5];
  79559. _tmpVec.copyFrom(this._bendAxis);
  79560. _tmpVec.x *= -1;
  79561. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  79562. mat2.multiplyToRef(mat1, mat1);
  79563. }
  79564. if (this.poleAngle) {
  79565. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  79566. mat1.multiplyToRef(mat2, mat1);
  79567. }
  79568. if (this._bone1) {
  79569. if (this.slerpAmount < 1) {
  79570. if (!this._slerping) {
  79571. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  79572. }
  79573. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  79574. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  79575. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  79576. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  79577. this._slerping = true;
  79578. }
  79579. else {
  79580. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  79581. this._bone1Mat.copyFrom(mat1);
  79582. this._slerping = false;
  79583. }
  79584. }
  79585. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  79586. this._bone2Ang = angC;
  79587. };
  79588. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  79589. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  79590. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  79591. return BoneIKController;
  79592. }());
  79593. BABYLON.BoneIKController = BoneIKController;
  79594. })(BABYLON || (BABYLON = {}));
  79595. //# sourceMappingURL=babylon.boneIKController.js.map
  79596. var BABYLON;
  79597. (function (BABYLON) {
  79598. /**
  79599. * Class used to make a bone look toward a point in space
  79600. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller
  79601. */
  79602. var BoneLookController = /** @class */ (function () {
  79603. /**
  79604. * Create a BoneLookController
  79605. * @param mesh the mesh that the bone belongs to
  79606. * @param bone the bone that will be looking to the target
  79607. * @param target the target Vector3 to look at
  79608. * @param settings optional settings:
  79609. * * maxYaw: the maximum angle the bone will yaw to
  79610. * * minYaw: the minimum angle the bone will yaw to
  79611. * * maxPitch: the maximum angle the bone will pitch to
  79612. * * minPitch: the minimum angle the bone will yaw to
  79613. * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  79614. * * upAxis: the up axis of the coordinate system
  79615. * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  79616. * * yawAxis: set yawAxis if the bone does not yaw on the y axis
  79617. * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  79618. * * adjustYaw: used to make an adjustment to the yaw of the bone
  79619. * * adjustPitch: used to make an adjustment to the pitch of the bone
  79620. * * adjustRoll: used to make an adjustment to the roll of the bone
  79621. **/
  79622. function BoneLookController(mesh, bone, target, options) {
  79623. /**
  79624. * The up axis of the coordinate system that is used when the bone is rotated
  79625. */
  79626. this.upAxis = BABYLON.Vector3.Up();
  79627. /**
  79628. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD
  79629. */
  79630. this.upAxisSpace = BABYLON.Space.LOCAL;
  79631. /**
  79632. * Used to make an adjustment to the yaw of the bone
  79633. */
  79634. this.adjustYaw = 0;
  79635. /**
  79636. * Used to make an adjustment to the pitch of the bone
  79637. */
  79638. this.adjustPitch = 0;
  79639. /**
  79640. * Used to make an adjustment to the roll of the bone
  79641. */
  79642. this.adjustRoll = 0;
  79643. /**
  79644. * 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)
  79645. */
  79646. this.slerpAmount = 1;
  79647. this._boneQuat = BABYLON.Quaternion.Identity();
  79648. this._slerping = false;
  79649. this._firstFrameSkipped = false;
  79650. this._fowardAxis = BABYLON.Vector3.Forward();
  79651. this.mesh = mesh;
  79652. this.bone = bone;
  79653. this.target = target;
  79654. if (options) {
  79655. if (options.adjustYaw) {
  79656. this.adjustYaw = options.adjustYaw;
  79657. }
  79658. if (options.adjustPitch) {
  79659. this.adjustPitch = options.adjustPitch;
  79660. }
  79661. if (options.adjustRoll) {
  79662. this.adjustRoll = options.adjustRoll;
  79663. }
  79664. if (options.maxYaw != null) {
  79665. this.maxYaw = options.maxYaw;
  79666. }
  79667. else {
  79668. this.maxYaw = Math.PI;
  79669. }
  79670. if (options.minYaw != null) {
  79671. this.minYaw = options.minYaw;
  79672. }
  79673. else {
  79674. this.minYaw = -Math.PI;
  79675. }
  79676. if (options.maxPitch != null) {
  79677. this.maxPitch = options.maxPitch;
  79678. }
  79679. else {
  79680. this.maxPitch = Math.PI;
  79681. }
  79682. if (options.minPitch != null) {
  79683. this.minPitch = options.minPitch;
  79684. }
  79685. else {
  79686. this.minPitch = -Math.PI;
  79687. }
  79688. if (options.slerpAmount != null) {
  79689. this.slerpAmount = options.slerpAmount;
  79690. }
  79691. if (options.upAxis != null) {
  79692. this.upAxis = options.upAxis;
  79693. }
  79694. if (options.upAxisSpace != null) {
  79695. this.upAxisSpace = options.upAxisSpace;
  79696. }
  79697. if (options.yawAxis != null || options.pitchAxis != null) {
  79698. var newYawAxis = BABYLON.Axis.Y;
  79699. var newPitchAxis = BABYLON.Axis.X;
  79700. if (options.yawAxis != null) {
  79701. newYawAxis = options.yawAxis.clone();
  79702. newYawAxis.normalize();
  79703. }
  79704. if (options.pitchAxis != null) {
  79705. newPitchAxis = options.pitchAxis.clone();
  79706. newPitchAxis.normalize();
  79707. }
  79708. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  79709. this._transformYawPitch = BABYLON.Matrix.Identity();
  79710. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  79711. this._transformYawPitchInv = this._transformYawPitch.clone();
  79712. this._transformYawPitch.invert();
  79713. }
  79714. }
  79715. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  79716. this.upAxisSpace = BABYLON.Space.LOCAL;
  79717. }
  79718. }
  79719. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  79720. /**
  79721. * Gets or sets the minimum yaw angle that the bone can look to
  79722. */
  79723. get: function () {
  79724. return this._minYaw;
  79725. },
  79726. set: function (value) {
  79727. this._minYaw = value;
  79728. this._minYawSin = Math.sin(value);
  79729. this._minYawCos = Math.cos(value);
  79730. if (this._maxYaw != null) {
  79731. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  79732. this._yawRange = this._maxYaw - this._minYaw;
  79733. }
  79734. },
  79735. enumerable: true,
  79736. configurable: true
  79737. });
  79738. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  79739. /**
  79740. * Gets or sets the maximum yaw angle that the bone can look to
  79741. */
  79742. get: function () {
  79743. return this._maxYaw;
  79744. },
  79745. set: function (value) {
  79746. this._maxYaw = value;
  79747. this._maxYawSin = Math.sin(value);
  79748. this._maxYawCos = Math.cos(value);
  79749. if (this._minYaw != null) {
  79750. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  79751. this._yawRange = this._maxYaw - this._minYaw;
  79752. }
  79753. },
  79754. enumerable: true,
  79755. configurable: true
  79756. });
  79757. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  79758. /**
  79759. * Gets or sets the minimum pitch angle that the bone can look to
  79760. */
  79761. get: function () {
  79762. return this._minPitch;
  79763. },
  79764. set: function (value) {
  79765. this._minPitch = value;
  79766. this._minPitchTan = Math.tan(value);
  79767. },
  79768. enumerable: true,
  79769. configurable: true
  79770. });
  79771. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  79772. /**
  79773. * Gets or sets the maximum pitch angle that the bone can look to
  79774. */
  79775. get: function () {
  79776. return this._maxPitch;
  79777. },
  79778. set: function (value) {
  79779. this._maxPitch = value;
  79780. this._maxPitchTan = Math.tan(value);
  79781. },
  79782. enumerable: true,
  79783. configurable: true
  79784. });
  79785. /**
  79786. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())
  79787. */
  79788. BoneLookController.prototype.update = function () {
  79789. //skip the first frame when slerping so that the mesh rotation is correct
  79790. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  79791. this._firstFrameSkipped = true;
  79792. return;
  79793. }
  79794. var bone = this.bone;
  79795. var bonePos = BoneLookController._tmpVecs[0];
  79796. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  79797. var target = this.target;
  79798. var _tmpMat1 = BoneLookController._tmpMats[0];
  79799. var _tmpMat2 = BoneLookController._tmpMats[1];
  79800. var mesh = this.mesh;
  79801. var parentBone = bone.getParent();
  79802. var upAxis = BoneLookController._tmpVecs[1];
  79803. upAxis.copyFrom(this.upAxis);
  79804. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  79805. if (this._transformYawPitch) {
  79806. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  79807. }
  79808. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  79809. }
  79810. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  79811. mesh.getDirectionToRef(upAxis, upAxis);
  79812. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  79813. upAxis.normalize();
  79814. }
  79815. }
  79816. var checkYaw = false;
  79817. var checkPitch = false;
  79818. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  79819. checkYaw = true;
  79820. }
  79821. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  79822. checkPitch = true;
  79823. }
  79824. if (checkYaw || checkPitch) {
  79825. var spaceMat = BoneLookController._tmpMats[2];
  79826. var spaceMatInv = BoneLookController._tmpMats[3];
  79827. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  79828. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  79829. }
  79830. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  79831. spaceMat.copyFrom(mesh.getWorldMatrix());
  79832. }
  79833. else {
  79834. var forwardAxis = BoneLookController._tmpVecs[2];
  79835. forwardAxis.copyFrom(this._fowardAxis);
  79836. if (this._transformYawPitch) {
  79837. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  79838. }
  79839. if (parentBone) {
  79840. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  79841. }
  79842. else {
  79843. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  79844. }
  79845. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  79846. rightAxis.normalize();
  79847. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  79848. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  79849. }
  79850. spaceMat.invertToRef(spaceMatInv);
  79851. var xzlen = null;
  79852. if (checkPitch) {
  79853. var localTarget = BoneLookController._tmpVecs[3];
  79854. target.subtractToRef(bonePos, localTarget);
  79855. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  79856. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  79857. var pitch = Math.atan2(localTarget.y, xzlen);
  79858. var newPitch = pitch;
  79859. if (pitch > this._maxPitch) {
  79860. localTarget.y = this._maxPitchTan * xzlen;
  79861. newPitch = this._maxPitch;
  79862. }
  79863. else if (pitch < this._minPitch) {
  79864. localTarget.y = this._minPitchTan * xzlen;
  79865. newPitch = this._minPitch;
  79866. }
  79867. if (pitch != newPitch) {
  79868. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  79869. localTarget.addInPlace(bonePos);
  79870. target = localTarget;
  79871. }
  79872. }
  79873. if (checkYaw) {
  79874. var localTarget = BoneLookController._tmpVecs[4];
  79875. target.subtractToRef(bonePos, localTarget);
  79876. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  79877. var yaw = Math.atan2(localTarget.x, localTarget.z);
  79878. var newYaw = yaw;
  79879. if (yaw > this._maxYaw || yaw < this._minYaw) {
  79880. if (xzlen == null) {
  79881. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  79882. }
  79883. if (this._yawRange > Math.PI) {
  79884. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  79885. localTarget.z = this._maxYawCos * xzlen;
  79886. localTarget.x = this._maxYawSin * xzlen;
  79887. newYaw = this._maxYaw;
  79888. }
  79889. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  79890. localTarget.z = this._minYawCos * xzlen;
  79891. localTarget.x = this._minYawSin * xzlen;
  79892. newYaw = this._minYaw;
  79893. }
  79894. }
  79895. else {
  79896. if (yaw > this._maxYaw) {
  79897. localTarget.z = this._maxYawCos * xzlen;
  79898. localTarget.x = this._maxYawSin * xzlen;
  79899. newYaw = this._maxYaw;
  79900. }
  79901. else if (yaw < this._minYaw) {
  79902. localTarget.z = this._minYawCos * xzlen;
  79903. localTarget.x = this._minYawSin * xzlen;
  79904. newYaw = this._minYaw;
  79905. }
  79906. }
  79907. }
  79908. if (this._slerping && this._yawRange > Math.PI) {
  79909. //are we going to be crossing into the min/max region?
  79910. var boneFwd = BoneLookController._tmpVecs[8];
  79911. boneFwd.copyFrom(BABYLON.Axis.Z);
  79912. if (this._transformYawPitch) {
  79913. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  79914. }
  79915. var boneRotMat = BoneLookController._tmpMats[4];
  79916. this._boneQuat.toRotationMatrix(boneRotMat);
  79917. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  79918. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  79919. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  79920. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  79921. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  79922. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  79923. if (angBtwTar > angBtwMidYaw) {
  79924. if (xzlen == null) {
  79925. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  79926. }
  79927. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  79928. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  79929. if (angBtwMin < angBtwMax) {
  79930. newYaw = boneYaw + Math.PI * .75;
  79931. localTarget.z = Math.cos(newYaw) * xzlen;
  79932. localTarget.x = Math.sin(newYaw) * xzlen;
  79933. }
  79934. else {
  79935. newYaw = boneYaw - Math.PI * .75;
  79936. localTarget.z = Math.cos(newYaw) * xzlen;
  79937. localTarget.x = Math.sin(newYaw) * xzlen;
  79938. }
  79939. }
  79940. }
  79941. if (yaw != newYaw) {
  79942. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  79943. localTarget.addInPlace(bonePos);
  79944. target = localTarget;
  79945. }
  79946. }
  79947. }
  79948. var zaxis = BoneLookController._tmpVecs[5];
  79949. var xaxis = BoneLookController._tmpVecs[6];
  79950. var yaxis = BoneLookController._tmpVecs[7];
  79951. var _tmpQuat = BoneLookController._tmpQuat;
  79952. target.subtractToRef(bonePos, zaxis);
  79953. zaxis.normalize();
  79954. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  79955. xaxis.normalize();
  79956. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  79957. yaxis.normalize();
  79958. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  79959. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  79960. return;
  79961. }
  79962. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  79963. return;
  79964. }
  79965. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  79966. return;
  79967. }
  79968. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  79969. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  79970. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  79971. }
  79972. if (this.slerpAmount < 1) {
  79973. if (!this._slerping) {
  79974. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  79975. }
  79976. if (this._transformYawPitch) {
  79977. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  79978. }
  79979. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  79980. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  79981. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  79982. this._slerping = true;
  79983. }
  79984. else {
  79985. if (this._transformYawPitch) {
  79986. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  79987. }
  79988. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  79989. this._slerping = false;
  79990. }
  79991. };
  79992. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  79993. var angDiff = ang2 - ang1;
  79994. angDiff %= Math.PI * 2;
  79995. if (angDiff > Math.PI) {
  79996. angDiff -= Math.PI * 2;
  79997. }
  79998. else if (angDiff < -Math.PI) {
  79999. angDiff += Math.PI * 2;
  80000. }
  80001. return angDiff;
  80002. };
  80003. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  80004. ang1 %= (2 * Math.PI);
  80005. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  80006. ang2 %= (2 * Math.PI);
  80007. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  80008. var ab = 0;
  80009. if (ang1 < ang2) {
  80010. ab = ang2 - ang1;
  80011. }
  80012. else {
  80013. ab = ang1 - ang2;
  80014. }
  80015. if (ab > Math.PI) {
  80016. ab = Math.PI * 2 - ab;
  80017. }
  80018. return ab;
  80019. };
  80020. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  80021. ang %= (2 * Math.PI);
  80022. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  80023. ang1 %= (2 * Math.PI);
  80024. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  80025. ang2 %= (2 * Math.PI);
  80026. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  80027. if (ang1 < ang2) {
  80028. if (ang > ang1 && ang < ang2) {
  80029. return true;
  80030. }
  80031. }
  80032. else {
  80033. if (ang > ang2 && ang < ang1) {
  80034. return true;
  80035. }
  80036. }
  80037. return false;
  80038. };
  80039. 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()];
  80040. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  80041. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  80042. return BoneLookController;
  80043. }());
  80044. BABYLON.BoneLookController = BoneLookController;
  80045. })(BABYLON || (BABYLON = {}));
  80046. //# sourceMappingURL=babylon.boneLookController.js.map
  80047. var BABYLON;
  80048. (function (BABYLON) {
  80049. /**
  80050. * Class used to handle skinning animations
  80051. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  80052. */
  80053. var Skeleton = /** @class */ (function () {
  80054. /**
  80055. * Creates a new skeleton
  80056. * @param name defines the skeleton name
  80057. * @param id defines the skeleton Id
  80058. * @param scene defines the hosting scene
  80059. */
  80060. function Skeleton(
  80061. /** defines the skeleton name */
  80062. name,
  80063. /** defines the skeleton Id */
  80064. id, scene) {
  80065. this.name = name;
  80066. this.id = id;
  80067. /**
  80068. * Gets the list of child bones
  80069. */
  80070. this.bones = new Array();
  80071. /**
  80072. * Gets a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)
  80073. */
  80074. this.needInitialSkinMatrix = false;
  80075. this._isDirty = true;
  80076. this._meshesWithPoseMatrix = new Array();
  80077. this._identity = BABYLON.Matrix.Identity();
  80078. this._ranges = {};
  80079. this._lastAbsoluteTransformsUpdateId = -1;
  80080. /**
  80081. * Specifies if the skeleton should be serialized
  80082. */
  80083. this.doNotSerialize = false;
  80084. this._animationPropertiesOverride = null;
  80085. // Events
  80086. /**
  80087. * An observable triggered before computing the skeleton's matrices
  80088. */
  80089. this.onBeforeComputeObservable = new BABYLON.Observable();
  80090. this.bones = [];
  80091. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  80092. scene.skeletons.push(this);
  80093. //make sure it will recalculate the matrix next time prepare is called.
  80094. this._isDirty = true;
  80095. }
  80096. Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", {
  80097. /**
  80098. * Gets or sets the animation properties override
  80099. */
  80100. get: function () {
  80101. if (!this._animationPropertiesOverride) {
  80102. return this._scene.animationPropertiesOverride;
  80103. }
  80104. return this._animationPropertiesOverride;
  80105. },
  80106. set: function (value) {
  80107. this._animationPropertiesOverride = value;
  80108. },
  80109. enumerable: true,
  80110. configurable: true
  80111. });
  80112. // Members
  80113. /**
  80114. * Gets the list of transform matrices to send to shaders (one matrix per bone)
  80115. * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
  80116. * @returns a Float32Array containing matrices data
  80117. */
  80118. Skeleton.prototype.getTransformMatrices = function (mesh) {
  80119. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  80120. return mesh._bonesTransformMatrices;
  80121. }
  80122. if (!this._transformMatrices) {
  80123. this.prepare();
  80124. }
  80125. return this._transformMatrices;
  80126. };
  80127. /**
  80128. * Gets the current hosting scene
  80129. * @returns a scene object
  80130. */
  80131. Skeleton.prototype.getScene = function () {
  80132. return this._scene;
  80133. };
  80134. // Methods
  80135. /**
  80136. * Gets a string representing the current skeleton data
  80137. * @param fullDetails defines a boolean indicating if we want a verbose version
  80138. * @returns a string representing the current skeleton data
  80139. */
  80140. Skeleton.prototype.toString = function (fullDetails) {
  80141. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  80142. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  80143. if (fullDetails) {
  80144. ret += ", Ranges: {";
  80145. var first = true;
  80146. for (var name_1 in this._ranges) {
  80147. if (first) {
  80148. ret += ", ";
  80149. first = false;
  80150. }
  80151. ret += name_1;
  80152. }
  80153. ret += "}";
  80154. }
  80155. return ret;
  80156. };
  80157. /**
  80158. * Get bone's index searching by name
  80159. * @param name defines bone's name to search for
  80160. * @return the indice of the bone. Returns -1 if not found
  80161. */
  80162. Skeleton.prototype.getBoneIndexByName = function (name) {
  80163. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  80164. if (this.bones[boneIndex].name === name) {
  80165. return boneIndex;
  80166. }
  80167. }
  80168. return -1;
  80169. };
  80170. /**
  80171. * Creater a new animation range
  80172. * @param name defines the name of the range
  80173. * @param from defines the start key
  80174. * @param to defines the end key
  80175. */
  80176. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  80177. // check name not already in use
  80178. if (!this._ranges[name]) {
  80179. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  80180. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  80181. if (this.bones[i].animations[0]) {
  80182. this.bones[i].animations[0].createRange(name, from, to);
  80183. }
  80184. }
  80185. }
  80186. };
  80187. /**
  80188. * Delete a specific animation range
  80189. * @param name defines the name of the range
  80190. * @param deleteFrames defines if frames must be removed as well
  80191. */
  80192. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  80193. if (deleteFrames === void 0) { deleteFrames = true; }
  80194. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  80195. if (this.bones[i].animations[0]) {
  80196. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  80197. }
  80198. }
  80199. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  80200. };
  80201. /**
  80202. * Gets a specific animation range
  80203. * @param name defines the name of the range to look for
  80204. * @returns the requested animation range or null if not found
  80205. */
  80206. Skeleton.prototype.getAnimationRange = function (name) {
  80207. return this._ranges[name];
  80208. };
  80209. /**
  80210. * Gets the list of all animation ranges defined on this skeleton
  80211. * @returns an array
  80212. */
  80213. Skeleton.prototype.getAnimationRanges = function () {
  80214. var animationRanges = [];
  80215. var name;
  80216. var i = 0;
  80217. for (name in this._ranges) {
  80218. animationRanges[i] = this._ranges[name];
  80219. i++;
  80220. }
  80221. return animationRanges;
  80222. };
  80223. /**
  80224. * Copy animation range from a source skeleton.
  80225. * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  80226. * @param source defines the source skeleton
  80227. * @param name defines the name of the range to copy
  80228. * @param rescaleAsRequired defines if rescaling must be applied if required
  80229. * @returns true if operation was successful
  80230. */
  80231. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  80232. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  80233. if (this._ranges[name] || !source.getAnimationRange(name)) {
  80234. return false;
  80235. }
  80236. var ret = true;
  80237. var frameOffset = this._getHighestAnimationFrame() + 1;
  80238. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  80239. var boneDict = {};
  80240. var sourceBones = source.bones;
  80241. var nBones;
  80242. var i;
  80243. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  80244. boneDict[sourceBones[i].name] = sourceBones[i];
  80245. }
  80246. if (this.bones.length !== sourceBones.length) {
  80247. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  80248. ret = false;
  80249. }
  80250. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  80251. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  80252. var boneName = this.bones[i].name;
  80253. var sourceBone = boneDict[boneName];
  80254. if (sourceBone) {
  80255. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  80256. }
  80257. else {
  80258. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  80259. ret = false;
  80260. }
  80261. }
  80262. // do not call createAnimationRange(), since it also is done to bones, which was already done
  80263. var range = source.getAnimationRange(name);
  80264. if (range) {
  80265. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  80266. }
  80267. return ret;
  80268. };
  80269. /**
  80270. * Forces the skeleton to go to rest pose
  80271. */
  80272. Skeleton.prototype.returnToRest = function () {
  80273. for (var index = 0; index < this.bones.length; index++) {
  80274. this.bones[index].returnToRest();
  80275. }
  80276. };
  80277. Skeleton.prototype._getHighestAnimationFrame = function () {
  80278. var ret = 0;
  80279. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  80280. if (this.bones[i].animations[0]) {
  80281. var highest = this.bones[i].animations[0].getHighestFrame();
  80282. if (ret < highest) {
  80283. ret = highest;
  80284. }
  80285. }
  80286. }
  80287. return ret;
  80288. };
  80289. /**
  80290. * Begin a specific animation range
  80291. * @param name defines the name of the range to start
  80292. * @param loop defines if looping must be turned on (false by default)
  80293. * @param speedRatio defines the speed ratio to apply (1 by default)
  80294. * @param onAnimationEnd defines a callback which will be called when animation will end
  80295. * @returns a new animatable
  80296. */
  80297. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  80298. var range = this.getAnimationRange(name);
  80299. if (!range) {
  80300. return null;
  80301. }
  80302. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  80303. };
  80304. /** @hidden */
  80305. Skeleton.prototype._markAsDirty = function () {
  80306. this._isDirty = true;
  80307. };
  80308. /** @hidden */
  80309. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  80310. this._meshesWithPoseMatrix.push(mesh);
  80311. };
  80312. /** @hidden */
  80313. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  80314. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  80315. if (index > -1) {
  80316. this._meshesWithPoseMatrix.splice(index, 1);
  80317. }
  80318. };
  80319. /** @hidden */
  80320. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  80321. this.onBeforeComputeObservable.notifyObservers(this);
  80322. for (var index = 0; index < this.bones.length; index++) {
  80323. var bone = this.bones[index];
  80324. var parentBone = bone.getParent();
  80325. if (parentBone) {
  80326. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  80327. }
  80328. else {
  80329. if (initialSkinMatrix) {
  80330. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  80331. }
  80332. else {
  80333. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  80334. }
  80335. }
  80336. if (bone._index !== -1) {
  80337. var mappedIndex = bone._index === null ? index : bone._index;
  80338. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  80339. }
  80340. }
  80341. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  80342. };
  80343. /**
  80344. * Build all resources required to render a skeleton
  80345. */
  80346. Skeleton.prototype.prepare = function () {
  80347. if (!this._isDirty) {
  80348. return;
  80349. }
  80350. if (this.needInitialSkinMatrix) {
  80351. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  80352. var mesh = this._meshesWithPoseMatrix[index];
  80353. var poseMatrix = mesh.getPoseMatrix();
  80354. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  80355. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  80356. }
  80357. if (this._synchronizedWithMesh !== mesh) {
  80358. this._synchronizedWithMesh = mesh;
  80359. // Prepare bones
  80360. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  80361. var bone = this.bones[boneIndex];
  80362. if (!bone.getParent()) {
  80363. var matrix = bone.getBaseMatrix();
  80364. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  80365. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  80366. }
  80367. }
  80368. }
  80369. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  80370. }
  80371. }
  80372. else {
  80373. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  80374. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  80375. }
  80376. this._computeTransformMatrices(this._transformMatrices, null);
  80377. }
  80378. this._isDirty = false;
  80379. this._scene._activeBones.addCount(this.bones.length, false);
  80380. };
  80381. /**
  80382. * Gets the list of animatables currently running for this skeleton
  80383. * @returns an array of animatables
  80384. */
  80385. Skeleton.prototype.getAnimatables = function () {
  80386. if (!this._animatables || this._animatables.length !== this.bones.length) {
  80387. this._animatables = [];
  80388. for (var index = 0; index < this.bones.length; index++) {
  80389. this._animatables.push(this.bones[index]);
  80390. }
  80391. }
  80392. return this._animatables;
  80393. };
  80394. /**
  80395. * Clone the current skeleton
  80396. * @param name defines the name of the new skeleton
  80397. * @param id defines the id of the enw skeleton
  80398. * @returns the new skeleton
  80399. */
  80400. Skeleton.prototype.clone = function (name, id) {
  80401. var result = new Skeleton(name, id || name, this._scene);
  80402. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  80403. for (var index = 0; index < this.bones.length; index++) {
  80404. var source = this.bones[index];
  80405. var parentBone = null;
  80406. var parent_1 = source.getParent();
  80407. if (parent_1) {
  80408. var parentIndex = this.bones.indexOf(parent_1);
  80409. parentBone = result.bones[parentIndex];
  80410. }
  80411. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  80412. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  80413. }
  80414. if (this._ranges) {
  80415. result._ranges = {};
  80416. for (var rangeName in this._ranges) {
  80417. var range = this._ranges[rangeName];
  80418. if (range) {
  80419. result._ranges[rangeName] = range.clone();
  80420. }
  80421. }
  80422. }
  80423. this._isDirty = true;
  80424. return result;
  80425. };
  80426. /**
  80427. * Enable animation blending for this skeleton
  80428. * @param blendingSpeed defines the blending speed to apply
  80429. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  80430. */
  80431. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  80432. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  80433. this.bones.forEach(function (bone) {
  80434. bone.animations.forEach(function (animation) {
  80435. animation.enableBlending = true;
  80436. animation.blendingSpeed = blendingSpeed;
  80437. });
  80438. });
  80439. };
  80440. /**
  80441. * Releases all resources associated with the current skeleton
  80442. */
  80443. Skeleton.prototype.dispose = function () {
  80444. this._meshesWithPoseMatrix = [];
  80445. // Animations
  80446. this.getScene().stopAnimation(this);
  80447. // Remove from scene
  80448. this.getScene().removeSkeleton(this);
  80449. };
  80450. /**
  80451. * Serialize the skeleton in a JSON object
  80452. * @returns a JSON object
  80453. */
  80454. Skeleton.prototype.serialize = function () {
  80455. var serializationObject = {};
  80456. serializationObject.name = this.name;
  80457. serializationObject.id = this.id;
  80458. if (this.dimensionsAtRest) {
  80459. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  80460. }
  80461. serializationObject.bones = [];
  80462. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  80463. for (var index = 0; index < this.bones.length; index++) {
  80464. var bone = this.bones[index];
  80465. var parent_2 = bone.getParent();
  80466. var serializedBone = {
  80467. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  80468. name: bone.name,
  80469. matrix: bone.getBaseMatrix().toArray(),
  80470. rest: bone.getRestPose().toArray()
  80471. };
  80472. serializationObject.bones.push(serializedBone);
  80473. if (bone.length) {
  80474. serializedBone.length = bone.length;
  80475. }
  80476. if (bone.metadata) {
  80477. serializedBone.metadata = bone.metadata;
  80478. }
  80479. if (bone.animations && bone.animations.length > 0) {
  80480. serializedBone.animation = bone.animations[0].serialize();
  80481. }
  80482. serializationObject.ranges = [];
  80483. for (var name in this._ranges) {
  80484. var source = this._ranges[name];
  80485. if (!source) {
  80486. continue;
  80487. }
  80488. var range = {};
  80489. range.name = name;
  80490. range.from = source.from;
  80491. range.to = source.to;
  80492. serializationObject.ranges.push(range);
  80493. }
  80494. }
  80495. return serializationObject;
  80496. };
  80497. /**
  80498. * Creates a new skeleton from serialized data
  80499. * @param parsedSkeleton defines the serialized data
  80500. * @param scene defines the hosting scene
  80501. * @returns a new skeleton
  80502. */
  80503. Skeleton.Parse = function (parsedSkeleton, scene) {
  80504. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  80505. if (parsedSkeleton.dimensionsAtRest) {
  80506. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  80507. }
  80508. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  80509. var index;
  80510. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  80511. var parsedBone = parsedSkeleton.bones[index];
  80512. var parentBone = null;
  80513. if (parsedBone.parentBoneIndex > -1) {
  80514. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  80515. }
  80516. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  80517. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  80518. if (parsedBone.length) {
  80519. bone.length = parsedBone.length;
  80520. }
  80521. if (parsedBone.metadata) {
  80522. bone.metadata = parsedBone.metadata;
  80523. }
  80524. if (parsedBone.animation) {
  80525. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  80526. }
  80527. }
  80528. // placed after bones, so createAnimationRange can cascade down
  80529. if (parsedSkeleton.ranges) {
  80530. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  80531. var data = parsedSkeleton.ranges[index];
  80532. skeleton.createAnimationRange(data.name, data.from, data.to);
  80533. }
  80534. }
  80535. return skeleton;
  80536. };
  80537. /**
  80538. * Compute all node absolute transforms
  80539. * @param forceUpdate defines if computation must be done even if cache is up to date
  80540. */
  80541. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  80542. if (forceUpdate === void 0) { forceUpdate = false; }
  80543. var renderId = this._scene.getRenderId();
  80544. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  80545. this.bones[0].computeAbsoluteTransforms();
  80546. this._lastAbsoluteTransformsUpdateId = renderId;
  80547. }
  80548. };
  80549. /**
  80550. * Gets the root pose matrix
  80551. * @returns a matrix
  80552. */
  80553. Skeleton.prototype.getPoseMatrix = function () {
  80554. var poseMatrix = null;
  80555. if (this._meshesWithPoseMatrix.length > 0) {
  80556. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  80557. }
  80558. return poseMatrix;
  80559. };
  80560. /**
  80561. * Sorts bones per internal index
  80562. */
  80563. Skeleton.prototype.sortBones = function () {
  80564. var bones = new Array();
  80565. var visited = new Array(this.bones.length);
  80566. for (var index = 0; index < this.bones.length; index++) {
  80567. this._sortBones(index, bones, visited);
  80568. }
  80569. this.bones = bones;
  80570. };
  80571. Skeleton.prototype._sortBones = function (index, bones, visited) {
  80572. if (visited[index]) {
  80573. return;
  80574. }
  80575. visited[index] = true;
  80576. var bone = this.bones[index];
  80577. if (bone._index === undefined) {
  80578. bone._index = index;
  80579. }
  80580. var parentBone = bone.getParent();
  80581. if (parentBone) {
  80582. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  80583. }
  80584. bones.push(bone);
  80585. };
  80586. return Skeleton;
  80587. }());
  80588. BABYLON.Skeleton = Skeleton;
  80589. })(BABYLON || (BABYLON = {}));
  80590. //# sourceMappingURL=babylon.skeleton.js.map
  80591. var BABYLON;
  80592. (function (BABYLON) {
  80593. var SphericalPolynomial = /** @class */ (function () {
  80594. function SphericalPolynomial() {
  80595. this.x = BABYLON.Vector3.Zero();
  80596. this.y = BABYLON.Vector3.Zero();
  80597. this.z = BABYLON.Vector3.Zero();
  80598. this.xx = BABYLON.Vector3.Zero();
  80599. this.yy = BABYLON.Vector3.Zero();
  80600. this.zz = BABYLON.Vector3.Zero();
  80601. this.xy = BABYLON.Vector3.Zero();
  80602. this.yz = BABYLON.Vector3.Zero();
  80603. this.zx = BABYLON.Vector3.Zero();
  80604. }
  80605. SphericalPolynomial.prototype.addAmbient = function (color) {
  80606. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  80607. this.xx = this.xx.add(colorVector);
  80608. this.yy = this.yy.add(colorVector);
  80609. this.zz = this.zz.add(colorVector);
  80610. };
  80611. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  80612. var result = new SphericalPolynomial();
  80613. result.x = harmonics.L11.scale(1.02333);
  80614. result.y = harmonics.L1_1.scale(1.02333);
  80615. result.z = harmonics.L10.scale(1.02333);
  80616. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  80617. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  80618. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  80619. result.yz = harmonics.L2_1.scale(0.858086);
  80620. result.zx = harmonics.L21.scale(0.858086);
  80621. result.xy = harmonics.L2_2.scale(0.858086);
  80622. result.scale(1.0 / Math.PI);
  80623. return result;
  80624. };
  80625. SphericalPolynomial.prototype.scale = function (scale) {
  80626. this.x = this.x.scale(scale);
  80627. this.y = this.y.scale(scale);
  80628. this.z = this.z.scale(scale);
  80629. this.xx = this.xx.scale(scale);
  80630. this.yy = this.yy.scale(scale);
  80631. this.zz = this.zz.scale(scale);
  80632. this.yz = this.yz.scale(scale);
  80633. this.zx = this.zx.scale(scale);
  80634. this.xy = this.xy.scale(scale);
  80635. };
  80636. return SphericalPolynomial;
  80637. }());
  80638. BABYLON.SphericalPolynomial = SphericalPolynomial;
  80639. var SphericalHarmonics = /** @class */ (function () {
  80640. function SphericalHarmonics() {
  80641. this.L00 = BABYLON.Vector3.Zero();
  80642. this.L1_1 = BABYLON.Vector3.Zero();
  80643. this.L10 = BABYLON.Vector3.Zero();
  80644. this.L11 = BABYLON.Vector3.Zero();
  80645. this.L2_2 = BABYLON.Vector3.Zero();
  80646. this.L2_1 = BABYLON.Vector3.Zero();
  80647. this.L20 = BABYLON.Vector3.Zero();
  80648. this.L21 = BABYLON.Vector3.Zero();
  80649. this.L22 = BABYLON.Vector3.Zero();
  80650. }
  80651. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  80652. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  80653. var c = colorVector.scale(deltaSolidAngle);
  80654. this.L00 = this.L00.add(c.scale(0.282095));
  80655. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  80656. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  80657. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  80658. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  80659. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  80660. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  80661. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  80662. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  80663. };
  80664. SphericalHarmonics.prototype.scale = function (scale) {
  80665. this.L00 = this.L00.scale(scale);
  80666. this.L1_1 = this.L1_1.scale(scale);
  80667. this.L10 = this.L10.scale(scale);
  80668. this.L11 = this.L11.scale(scale);
  80669. this.L2_2 = this.L2_2.scale(scale);
  80670. this.L2_1 = this.L2_1.scale(scale);
  80671. this.L20 = this.L20.scale(scale);
  80672. this.L21 = this.L21.scale(scale);
  80673. this.L22 = this.L22.scale(scale);
  80674. };
  80675. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  80676. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  80677. //
  80678. // E_lm = A_l * L_lm
  80679. //
  80680. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  80681. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  80682. // the scaling factors are given in equation 9.
  80683. // Constant (Band 0)
  80684. this.L00 = this.L00.scale(3.141593);
  80685. // Linear (Band 1)
  80686. this.L1_1 = this.L1_1.scale(2.094395);
  80687. this.L10 = this.L10.scale(2.094395);
  80688. this.L11 = this.L11.scale(2.094395);
  80689. // Quadratic (Band 2)
  80690. this.L2_2 = this.L2_2.scale(0.785398);
  80691. this.L2_1 = this.L2_1.scale(0.785398);
  80692. this.L20 = this.L20.scale(0.785398);
  80693. this.L21 = this.L21.scale(0.785398);
  80694. this.L22 = this.L22.scale(0.785398);
  80695. };
  80696. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  80697. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  80698. // L = (1/pi) * E * rho
  80699. //
  80700. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  80701. this.scale(1.0 / Math.PI);
  80702. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  80703. // (The pixel shader must apply albedo after texture fetches, etc).
  80704. };
  80705. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  80706. var result = new SphericalHarmonics();
  80707. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  80708. result.L1_1 = polynomial.y.scale(0.977204);
  80709. result.L10 = polynomial.z.scale(0.977204);
  80710. result.L11 = polynomial.x.scale(0.977204);
  80711. result.L2_2 = polynomial.xy.scale(1.16538);
  80712. result.L2_1 = polynomial.yz.scale(1.16538);
  80713. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  80714. result.L21 = polynomial.zx.scale(1.16538);
  80715. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  80716. result.scale(Math.PI);
  80717. return result;
  80718. };
  80719. return SphericalHarmonics;
  80720. }());
  80721. BABYLON.SphericalHarmonics = SphericalHarmonics;
  80722. })(BABYLON || (BABYLON = {}));
  80723. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  80724. var BABYLON;
  80725. (function (BABYLON) {
  80726. var FileFaceOrientation = /** @class */ (function () {
  80727. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  80728. this.name = name;
  80729. this.worldAxisForNormal = worldAxisForNormal;
  80730. this.worldAxisForFileX = worldAxisForFileX;
  80731. this.worldAxisForFileY = worldAxisForFileY;
  80732. }
  80733. return FileFaceOrientation;
  80734. }());
  80735. ;
  80736. /**
  80737. * Helper class dealing with the extraction of spherical polynomial dataArray
  80738. * from a cube map.
  80739. */
  80740. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  80741. function CubeMapToSphericalPolynomialTools() {
  80742. }
  80743. /**
  80744. * Converts a texture to the according Spherical Polynomial data.
  80745. * This extracts the first 3 orders only as they are the only one used in the lighting.
  80746. *
  80747. * @param texture The texture to extract the information from.
  80748. * @return The Spherical Polynomial data.
  80749. */
  80750. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  80751. if (!texture.isCube) {
  80752. // Only supports cube Textures currently.
  80753. return null;
  80754. }
  80755. var size = texture.getSize().width;
  80756. var right = texture.readPixels(0);
  80757. var left = texture.readPixels(1);
  80758. var up;
  80759. var down;
  80760. if (texture.isRenderTarget) {
  80761. up = texture.readPixels(3);
  80762. down = texture.readPixels(2);
  80763. }
  80764. else {
  80765. up = texture.readPixels(2);
  80766. down = texture.readPixels(3);
  80767. }
  80768. var front = texture.readPixels(4);
  80769. var back = texture.readPixels(5);
  80770. var gammaSpace = texture.gammaSpace;
  80771. // Always read as RGBA.
  80772. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  80773. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  80774. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  80775. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  80776. }
  80777. var cubeInfo = {
  80778. size: size,
  80779. right: right,
  80780. left: left,
  80781. up: up,
  80782. down: down,
  80783. front: front,
  80784. back: back,
  80785. format: format,
  80786. type: type,
  80787. gammaSpace: gammaSpace,
  80788. };
  80789. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  80790. };
  80791. /**
  80792. * Converts a cubemap to the according Spherical Polynomial data.
  80793. * This extracts the first 3 orders only as they are the only one used in the lighting.
  80794. *
  80795. * @param cubeInfo The Cube map to extract the information from.
  80796. * @return The Spherical Polynomial data.
  80797. */
  80798. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  80799. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  80800. var totalSolidAngle = 0.0;
  80801. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  80802. var du = 2.0 / cubeInfo.size;
  80803. var dv = du;
  80804. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  80805. var minUV = du * 0.5 - 1.0;
  80806. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  80807. var fileFace = this.FileFaces[faceIndex];
  80808. var dataArray = cubeInfo[fileFace.name];
  80809. var v = minUV;
  80810. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  80811. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  80812. // Because SP is still linear, so summation is fine in that basis.
  80813. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  80814. for (var y = 0; y < cubeInfo.size; y++) {
  80815. var u = minUV;
  80816. for (var x = 0; x < cubeInfo.size; x++) {
  80817. // World direction (not normalised)
  80818. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  80819. worldDirection.normalize();
  80820. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  80821. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  80822. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  80823. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  80824. // Handle Integer types.
  80825. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  80826. r /= 255;
  80827. g /= 255;
  80828. b /= 255;
  80829. }
  80830. // Handle Gamma space textures.
  80831. if (cubeInfo.gammaSpace) {
  80832. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  80833. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  80834. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  80835. }
  80836. var color = new BABYLON.Color3(r, g, b);
  80837. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  80838. totalSolidAngle += deltaSolidAngle;
  80839. u += du;
  80840. }
  80841. v += dv;
  80842. }
  80843. }
  80844. // Solid angle for entire sphere is 4*pi
  80845. var sphereSolidAngle = 4.0 * Math.PI;
  80846. // Adjust the solid angle to allow for how many faces we processed.
  80847. var facesProcessed = 6.0;
  80848. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  80849. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  80850. // This is needed because the numerical integration over the cube uses a
  80851. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  80852. // and also to compensate for accumulative error due to float precision in the summation.
  80853. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  80854. sphericalHarmonics.scale(correctionFactor);
  80855. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  80856. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  80857. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  80858. };
  80859. CubeMapToSphericalPolynomialTools.FileFaces = [
  80860. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  80861. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  80862. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  80863. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  80864. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  80865. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  80866. ];
  80867. return CubeMapToSphericalPolynomialTools;
  80868. }());
  80869. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  80870. })(BABYLON || (BABYLON = {}));
  80871. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  80872. var BABYLON;
  80873. (function (BABYLON) {
  80874. /**
  80875. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  80876. */
  80877. var PanoramaToCubeMapTools = /** @class */ (function () {
  80878. function PanoramaToCubeMapTools() {
  80879. }
  80880. /**
  80881. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  80882. *
  80883. * @param float32Array The source data.
  80884. * @param inputWidth The width of the input panorama.
  80885. * @param inputhHeight The height of the input panorama.
  80886. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  80887. * @return The cubemap data
  80888. */
  80889. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  80890. if (!float32Array) {
  80891. throw "ConvertPanoramaToCubemap: input cannot be null";
  80892. }
  80893. if (float32Array.length != inputWidth * inputHeight * 3) {
  80894. throw "ConvertPanoramaToCubemap: input size is wrong";
  80895. }
  80896. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  80897. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  80898. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  80899. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  80900. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  80901. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  80902. return {
  80903. front: textureFront,
  80904. back: textureBack,
  80905. left: textureLeft,
  80906. right: textureRight,
  80907. up: textureUp,
  80908. down: textureDown,
  80909. size: size,
  80910. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  80911. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  80912. gammaSpace: false,
  80913. };
  80914. };
  80915. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  80916. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  80917. var textureArray = new Float32Array(buffer);
  80918. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  80919. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  80920. var dy = 1 / texSize;
  80921. var fy = 0;
  80922. for (var y = 0; y < texSize; y++) {
  80923. var xv1 = faceData[0];
  80924. var xv2 = faceData[2];
  80925. for (var x = 0; x < texSize; x++) {
  80926. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  80927. v.normalize();
  80928. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  80929. // 3 channels per pixels
  80930. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  80931. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  80932. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  80933. xv1 = xv1.add(rotDX1);
  80934. xv2 = xv2.add(rotDX2);
  80935. }
  80936. fy += dy;
  80937. }
  80938. return textureArray;
  80939. };
  80940. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  80941. var theta = Math.atan2(vDir.z, vDir.x);
  80942. var phi = Math.acos(vDir.y);
  80943. while (theta < -Math.PI)
  80944. theta += 2 * Math.PI;
  80945. while (theta > Math.PI)
  80946. theta -= 2 * Math.PI;
  80947. var dx = theta / Math.PI;
  80948. var dy = phi / Math.PI;
  80949. // recenter.
  80950. dx = dx * 0.5 + 0.5;
  80951. var px = Math.round(dx * inputWidth);
  80952. if (px < 0)
  80953. px = 0;
  80954. else if (px >= inputWidth)
  80955. px = inputWidth - 1;
  80956. var py = Math.round(dy * inputHeight);
  80957. if (py < 0)
  80958. py = 0;
  80959. else if (py >= inputHeight)
  80960. py = inputHeight - 1;
  80961. var inputY = (inputHeight - py - 1);
  80962. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  80963. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  80964. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  80965. return {
  80966. r: r,
  80967. g: g,
  80968. b: b
  80969. };
  80970. };
  80971. PanoramaToCubeMapTools.FACE_FRONT = [
  80972. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  80973. new BABYLON.Vector3(1.0, -1.0, -1.0),
  80974. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  80975. new BABYLON.Vector3(1.0, 1.0, -1.0)
  80976. ];
  80977. PanoramaToCubeMapTools.FACE_BACK = [
  80978. new BABYLON.Vector3(1.0, -1.0, 1.0),
  80979. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  80980. new BABYLON.Vector3(1.0, 1.0, 1.0),
  80981. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  80982. ];
  80983. PanoramaToCubeMapTools.FACE_RIGHT = [
  80984. new BABYLON.Vector3(1.0, -1.0, -1.0),
  80985. new BABYLON.Vector3(1.0, -1.0, 1.0),
  80986. new BABYLON.Vector3(1.0, 1.0, -1.0),
  80987. new BABYLON.Vector3(1.0, 1.0, 1.0)
  80988. ];
  80989. PanoramaToCubeMapTools.FACE_LEFT = [
  80990. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  80991. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  80992. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  80993. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  80994. ];
  80995. PanoramaToCubeMapTools.FACE_DOWN = [
  80996. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  80997. new BABYLON.Vector3(1.0, 1.0, -1.0),
  80998. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  80999. new BABYLON.Vector3(1.0, 1.0, 1.0)
  81000. ];
  81001. PanoramaToCubeMapTools.FACE_UP = [
  81002. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  81003. new BABYLON.Vector3(1.0, -1.0, 1.0),
  81004. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  81005. new BABYLON.Vector3(1.0, -1.0, -1.0)
  81006. ];
  81007. return PanoramaToCubeMapTools;
  81008. }());
  81009. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  81010. })(BABYLON || (BABYLON = {}));
  81011. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  81012. var BABYLON;
  81013. (function (BABYLON) {
  81014. ;
  81015. /**
  81016. * This groups tools to convert HDR texture to native colors array.
  81017. */
  81018. var HDRTools = /** @class */ (function () {
  81019. function HDRTools() {
  81020. }
  81021. HDRTools.Ldexp = function (mantissa, exponent) {
  81022. if (exponent > 1023) {
  81023. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  81024. }
  81025. if (exponent < -1074) {
  81026. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  81027. }
  81028. return mantissa * Math.pow(2, exponent);
  81029. };
  81030. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  81031. if (exponent > 0) { /*nonzero pixel*/
  81032. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  81033. float32array[index + 0] = red * exponent;
  81034. float32array[index + 1] = green * exponent;
  81035. float32array[index + 2] = blue * exponent;
  81036. }
  81037. else {
  81038. float32array[index + 0] = 0;
  81039. float32array[index + 1] = 0;
  81040. float32array[index + 2] = 0;
  81041. }
  81042. };
  81043. HDRTools.readStringLine = function (uint8array, startIndex) {
  81044. var line = "";
  81045. var character = "";
  81046. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  81047. character = String.fromCharCode(uint8array[i]);
  81048. if (character == "\n") {
  81049. break;
  81050. }
  81051. line += character;
  81052. }
  81053. return line;
  81054. };
  81055. /**
  81056. * Reads header information from an RGBE texture stored in a native array.
  81057. * More information on this format are available here:
  81058. * https://en.wikipedia.org/wiki/RGBE_image_format
  81059. *
  81060. * @param uint8array The binary file stored in native array.
  81061. * @return The header information.
  81062. */
  81063. HDRTools.RGBE_ReadHeader = function (uint8array) {
  81064. var height = 0;
  81065. var width = 0;
  81066. var line = this.readStringLine(uint8array, 0);
  81067. if (line[0] != '#' || line[1] != '?') {
  81068. throw "Bad HDR Format.";
  81069. }
  81070. var endOfHeader = false;
  81071. var findFormat = false;
  81072. var lineIndex = 0;
  81073. do {
  81074. lineIndex += (line.length + 1);
  81075. line = this.readStringLine(uint8array, lineIndex);
  81076. if (line == "FORMAT=32-bit_rle_rgbe") {
  81077. findFormat = true;
  81078. }
  81079. else if (line.length == 0) {
  81080. endOfHeader = true;
  81081. }
  81082. } while (!endOfHeader);
  81083. if (!findFormat) {
  81084. throw "HDR Bad header format, unsupported FORMAT";
  81085. }
  81086. lineIndex += (line.length + 1);
  81087. line = this.readStringLine(uint8array, lineIndex);
  81088. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  81089. var match = sizeRegexp.exec(line);
  81090. // TODO. Support +Y and -X if needed.
  81091. if (!match || match.length < 3) {
  81092. throw "HDR Bad header format, no size";
  81093. }
  81094. width = parseInt(match[2]);
  81095. height = parseInt(match[1]);
  81096. if (width < 8 || width > 0x7fff) {
  81097. throw "HDR Bad header format, unsupported size";
  81098. }
  81099. lineIndex += (line.length + 1);
  81100. return {
  81101. height: height,
  81102. width: width,
  81103. dataPosition: lineIndex
  81104. };
  81105. };
  81106. /**
  81107. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  81108. * This RGBE texture needs to store the information as a panorama.
  81109. *
  81110. * More information on this format are available here:
  81111. * https://en.wikipedia.org/wiki/RGBE_image_format
  81112. *
  81113. * @param buffer The binary file stored in an array buffer.
  81114. * @param size The expected size of the extracted cubemap.
  81115. * @return The Cube Map information.
  81116. */
  81117. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  81118. var uint8array = new Uint8Array(buffer);
  81119. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  81120. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  81121. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  81122. return cubeMapData;
  81123. };
  81124. /**
  81125. * Returns the pixels data extracted from an RGBE texture.
  81126. * This pixels will be stored left to right up to down in the R G B order in one array.
  81127. *
  81128. * More information on this format are available here:
  81129. * https://en.wikipedia.org/wiki/RGBE_image_format
  81130. *
  81131. * @param uint8array The binary file stored in an array buffer.
  81132. * @param hdrInfo The header information of the file.
  81133. * @return The pixels data in RGB right to left up to down order.
  81134. */
  81135. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  81136. // Keep for multi format supports.
  81137. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  81138. };
  81139. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  81140. var num_scanlines = hdrInfo.height;
  81141. var scanline_width = hdrInfo.width;
  81142. var a, b, c, d, count;
  81143. var dataIndex = hdrInfo.dataPosition;
  81144. var index = 0, endIndex = 0, i = 0;
  81145. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  81146. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  81147. // 3 channels of 4 bytes per pixel in float.
  81148. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  81149. var resultArray = new Float32Array(resultBuffer);
  81150. // read in each successive scanline
  81151. while (num_scanlines > 0) {
  81152. a = uint8array[dataIndex++];
  81153. b = uint8array[dataIndex++];
  81154. c = uint8array[dataIndex++];
  81155. d = uint8array[dataIndex++];
  81156. if (a != 2 || b != 2 || (c & 0x80)) {
  81157. // this file is not run length encoded
  81158. throw "HDR Bad header format, not RLE";
  81159. }
  81160. if (((c << 8) | d) != scanline_width) {
  81161. throw "HDR Bad header format, wrong scan line width";
  81162. }
  81163. index = 0;
  81164. // read each of the four channels for the scanline into the buffer
  81165. for (i = 0; i < 4; i++) {
  81166. endIndex = (i + 1) * scanline_width;
  81167. while (index < endIndex) {
  81168. a = uint8array[dataIndex++];
  81169. b = uint8array[dataIndex++];
  81170. if (a > 128) {
  81171. // a run of the same value
  81172. count = a - 128;
  81173. if ((count == 0) || (count > endIndex - index)) {
  81174. throw "HDR Bad Format, bad scanline data (run)";
  81175. }
  81176. while (count-- > 0) {
  81177. scanLineArray[index++] = b;
  81178. }
  81179. }
  81180. else {
  81181. // a non-run
  81182. count = a;
  81183. if ((count == 0) || (count > endIndex - index)) {
  81184. throw "HDR Bad Format, bad scanline data (non-run)";
  81185. }
  81186. scanLineArray[index++] = b;
  81187. if (--count > 0) {
  81188. for (var j = 0; j < count; j++) {
  81189. scanLineArray[index++] = uint8array[dataIndex++];
  81190. }
  81191. }
  81192. }
  81193. }
  81194. }
  81195. // now convert data from buffer into floats
  81196. for (i = 0; i < scanline_width; i++) {
  81197. a = scanLineArray[i];
  81198. b = scanLineArray[i + scanline_width];
  81199. c = scanLineArray[i + 2 * scanline_width];
  81200. d = scanLineArray[i + 3 * scanline_width];
  81201. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  81202. }
  81203. num_scanlines--;
  81204. }
  81205. return resultArray;
  81206. };
  81207. return HDRTools;
  81208. }());
  81209. BABYLON.HDRTools = HDRTools;
  81210. })(BABYLON || (BABYLON = {}));
  81211. //# sourceMappingURL=babylon.hdr.js.map
  81212. var BABYLON;
  81213. (function (BABYLON) {
  81214. /**
  81215. * Sets of helpers addressing the serialization and deserialization of environment texture
  81216. * stored in a BabylonJS env file.
  81217. * Those files are usually stored as .env files.
  81218. */
  81219. var EnvironmentTextureTools = /** @class */ (function () {
  81220. function EnvironmentTextureTools() {
  81221. }
  81222. /**
  81223. * Gets the environment info from an env file.
  81224. * @param data The array buffer containing the .env bytes.
  81225. * @returns the environment file info (the json header) if successfully parsed.
  81226. */
  81227. EnvironmentTextureTools.GetEnvInfo = function (data) {
  81228. var dataView = new DataView(data);
  81229. var pos = 0;
  81230. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  81231. if (dataView.getUint8(pos++) !== EnvironmentTextureTools._MagicBytes[i]) {
  81232. BABYLON.Tools.Error('Not a babylon environment map');
  81233. return null;
  81234. }
  81235. }
  81236. // Read json manifest - collect characters up to null terminator
  81237. var manifestString = '';
  81238. var charCode = 0x00;
  81239. while ((charCode = dataView.getUint8(pos++))) {
  81240. manifestString += String.fromCharCode(charCode);
  81241. }
  81242. var manifest = JSON.parse(manifestString);
  81243. if (manifest.specular) {
  81244. // Extend the header with the position of the payload.
  81245. manifest.specular.specularDataPosition = pos;
  81246. }
  81247. return manifest;
  81248. };
  81249. /**
  81250. * Creates an environment texture from a loaded cube texture.
  81251. * @param texture defines the cube texture to convert in env file
  81252. * @return a promise containing the environment data if succesfull.
  81253. */
  81254. EnvironmentTextureTools.CreateEnvTextureAsync = function (texture) {
  81255. var _this = this;
  81256. var internalTexture = texture.getInternalTexture();
  81257. if (!internalTexture) {
  81258. return Promise.reject("The cube texture is invalid.");
  81259. }
  81260. if (!texture._prefiltered) {
  81261. return Promise.reject("The cube texture is invalid (not prefiltered).");
  81262. }
  81263. var engine = internalTexture.getEngine();
  81264. if (engine && engine.premultipliedAlpha) {
  81265. return Promise.reject("Env texture can only be created when the engine is created with the premultipliedAlpha option set to false.");
  81266. }
  81267. var canvas = engine.getRenderingCanvas();
  81268. if (!canvas) {
  81269. return Promise.reject("Env texture can only be created when the engine is associated to a canvas.");
  81270. }
  81271. var textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  81272. if (!engine.getCaps().textureFloatRender) {
  81273. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  81274. if (!engine.getCaps().textureHalfFloatRender) {
  81275. return Promise.reject("Env texture can only be created when the browser supports half float or full float rendering.");
  81276. }
  81277. }
  81278. var cubeWidth = internalTexture.width;
  81279. var hostingScene = new BABYLON.Scene(engine);
  81280. var specularTextures = {};
  81281. var promises = [];
  81282. // Read and collect all mipmaps data from the cube.
  81283. var mipmapsCount = BABYLON.Scalar.Log2(internalTexture.width);
  81284. mipmapsCount = Math.round(mipmapsCount);
  81285. var _loop_1 = function (i) {
  81286. var faceWidth = Math.pow(2, mipmapsCount - i);
  81287. var _loop_2 = function (face) {
  81288. var data = texture.readPixels(face, i);
  81289. // Creates a temp texture with the face data.
  81290. var tempTexture = engine.createRawTexture(data, faceWidth, faceWidth, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, textureType);
  81291. // And rgbdEncode them.
  81292. var promise = new Promise(function (resolve, reject) {
  81293. 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);
  81294. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  81295. rgbdPostProcess.onApply = function (effect) {
  81296. effect._bindTexture("textureSampler", tempTexture);
  81297. };
  81298. // As the process needs to happen on the main canvas, keep track of the current size
  81299. var currentW = engine.getRenderWidth();
  81300. var currentH = engine.getRenderHeight();
  81301. // Set the desired size for the texture
  81302. engine.setSize(faceWidth, faceWidth);
  81303. hostingScene.postProcessManager.directRender([rgbdPostProcess], null);
  81304. // Reading datas from WebGL
  81305. canvas.toBlob(function (blob) {
  81306. var fileReader = new FileReader();
  81307. fileReader.onload = function (event) {
  81308. var arrayBuffer = event.target.result;
  81309. specularTextures[i * 6 + face] = arrayBuffer;
  81310. resolve();
  81311. };
  81312. fileReader.readAsArrayBuffer(blob);
  81313. });
  81314. // Reapply the previous canvas size
  81315. engine.setSize(currentW, currentH);
  81316. });
  81317. });
  81318. promises.push(promise);
  81319. };
  81320. // All faces of the cube.
  81321. for (var face = 0; face < 6; face++) {
  81322. _loop_2(face);
  81323. }
  81324. };
  81325. for (var i = 0; i <= mipmapsCount; i++) {
  81326. _loop_1(i);
  81327. }
  81328. // Once all the textures haves been collected as RGBD stored in PNGs
  81329. return Promise.all(promises).then(function () {
  81330. // We can delete the hosting scene keeping track of all the creation objects
  81331. hostingScene.dispose();
  81332. // Creates the json header for the env texture
  81333. var info = {
  81334. version: 1,
  81335. width: cubeWidth,
  81336. irradiance: _this._CreateEnvTextureIrradiance(texture),
  81337. specular: {
  81338. mipmaps: []
  81339. }
  81340. };
  81341. // Sets the specular image data information
  81342. var position = 0;
  81343. for (var i = 0; i <= mipmapsCount; i++) {
  81344. for (var face = 0; face < 6; face++) {
  81345. var byteLength = specularTextures[i * 6 + face].byteLength;
  81346. info.specular.mipmaps.push({
  81347. length: byteLength,
  81348. position: position
  81349. });
  81350. position += byteLength;
  81351. }
  81352. }
  81353. // Encode the JSON as an array buffer
  81354. var infoString = JSON.stringify(info);
  81355. var infoBuffer = new ArrayBuffer(infoString.length + 1);
  81356. var infoView = new Uint8Array(infoBuffer); // Limited to ascii subset matching unicode.
  81357. for (var i = 0, strLen = infoString.length; i < strLen; i++) {
  81358. infoView[i] = infoString.charCodeAt(i);
  81359. }
  81360. // Ends up with a null terminator for easier parsing
  81361. infoView[infoString.length] = 0x00;
  81362. // Computes the final required size and creates the storage
  81363. var totalSize = EnvironmentTextureTools._MagicBytes.length + position + infoBuffer.byteLength;
  81364. var finalBuffer = new ArrayBuffer(totalSize);
  81365. var finalBufferView = new Uint8Array(finalBuffer);
  81366. var dataView = new DataView(finalBuffer);
  81367. // Copy the magic bytes identifying the file in
  81368. var pos = 0;
  81369. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  81370. dataView.setUint8(pos++, EnvironmentTextureTools._MagicBytes[i]);
  81371. }
  81372. // Add the json info
  81373. finalBufferView.set(new Uint8Array(infoBuffer), pos);
  81374. pos += infoBuffer.byteLength;
  81375. // Finally inserts the texture data
  81376. for (var i = 0; i <= mipmapsCount; i++) {
  81377. for (var face = 0; face < 6; face++) {
  81378. var dataBuffer = specularTextures[i * 6 + face];
  81379. finalBufferView.set(new Uint8Array(dataBuffer), pos);
  81380. pos += dataBuffer.byteLength;
  81381. }
  81382. }
  81383. // Voila
  81384. return finalBuffer;
  81385. });
  81386. };
  81387. /**
  81388. * Creates a JSON representation of the spherical data.
  81389. * @param texture defines the texture containing the polynomials
  81390. * @return the JSON representation of the spherical info
  81391. */
  81392. EnvironmentTextureTools._CreateEnvTextureIrradiance = function (texture) {
  81393. var polynmials = texture.sphericalPolynomial;
  81394. if (polynmials == null) {
  81395. return null;
  81396. }
  81397. return {
  81398. polynomials: true,
  81399. x: [polynmials.x.x, polynmials.x.y, polynmials.x.z],
  81400. y: [polynmials.y.x, polynmials.y.y, polynmials.y.z],
  81401. z: [polynmials.z.x, polynmials.z.y, polynmials.z.z],
  81402. xx: [polynmials.xx.x, polynmials.xx.y, polynmials.xx.z],
  81403. yy: [polynmials.yy.x, polynmials.yy.y, polynmials.yy.z],
  81404. zz: [polynmials.zz.x, polynmials.zz.y, polynmials.zz.z],
  81405. yz: [polynmials.yz.x, polynmials.yz.y, polynmials.yz.z],
  81406. zx: [polynmials.zx.x, polynmials.zx.y, polynmials.zx.z],
  81407. xy: [polynmials.xy.x, polynmials.xy.y, polynmials.xy.z]
  81408. };
  81409. };
  81410. /**
  81411. * Uploads the texture info contained in the env file to te GPU.
  81412. * @param texture defines the internal texture to upload to
  81413. * @param arrayBuffer defines the buffer cotaining the data to load
  81414. * @param info defines the texture info retrieved through the GetEnvInfo method
  81415. * @returns a promise
  81416. */
  81417. EnvironmentTextureTools.UploadLevelsAsync = function (texture, arrayBuffer, info) {
  81418. if (info.version !== 1) {
  81419. BABYLON.Tools.Warn('Unsupported babylon environment map version "' + info.version + '"');
  81420. }
  81421. var specularInfo = info.specular;
  81422. if (!specularInfo) {
  81423. // Nothing else parsed so far
  81424. return Promise.resolve();
  81425. }
  81426. // Double checks the enclosed info
  81427. var mipmapsCount = BABYLON.Scalar.Log2(info.width);
  81428. mipmapsCount = Math.round(mipmapsCount) + 1;
  81429. if (specularInfo.mipmaps.length !== 6 * mipmapsCount) {
  81430. BABYLON.Tools.Warn('Unsupported specular mipmaps number "' + specularInfo.mipmaps.length + '"');
  81431. }
  81432. // Gets everything ready.
  81433. var engine = texture.getEngine();
  81434. var expandTexture = false;
  81435. var generateNonLODTextures = false;
  81436. var rgbdPostProcess = null;
  81437. var cubeRtt = null;
  81438. var lodTextures = null;
  81439. var caps = engine.getCaps();
  81440. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  81441. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  81442. texture.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  81443. // Add extra process if texture lod is not supported
  81444. if (!caps.textureLOD) {
  81445. expandTexture = false;
  81446. generateNonLODTextures = true;
  81447. lodTextures = {};
  81448. }
  81449. // in webgl 1 there are no ways to either render or copy lod level information for float textures.
  81450. else if (engine.webGLVersion < 2) {
  81451. expandTexture = false;
  81452. }
  81453. // If half float available we can uncompress the texture
  81454. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  81455. expandTexture = true;
  81456. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  81457. }
  81458. // If full float available we can uncompress the texture
  81459. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  81460. expandTexture = true;
  81461. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  81462. }
  81463. // Expand the texture if possible
  81464. if (expandTexture) {
  81465. // Simply run through the decode PP
  81466. rgbdPostProcess = new BABYLON.PostProcess("rgbdDecode", "rgbdDecode", null, null, 1, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, engine, false, undefined, texture.type, undefined, null, false);
  81467. texture._isRGBD = false;
  81468. texture.invertY = false;
  81469. cubeRtt = engine.createRenderTargetCubeTexture(texture.width, {
  81470. generateDepthBuffer: false,
  81471. generateMipMaps: true,
  81472. generateStencilBuffer: false,
  81473. samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE,
  81474. type: texture.type,
  81475. format: BABYLON.Engine.TEXTUREFORMAT_RGBA
  81476. });
  81477. }
  81478. else {
  81479. texture._isRGBD = true;
  81480. texture.invertY = true;
  81481. // In case of missing support, applies the same patch than DDS files.
  81482. if (generateNonLODTextures) {
  81483. var mipSlices = 3;
  81484. var scale = texture._lodGenerationScale;
  81485. var offset = texture._lodGenerationOffset;
  81486. for (var i = 0; i < mipSlices; i++) {
  81487. //compute LOD from even spacing in smoothness (matching shader calculation)
  81488. var smoothness = i / (mipSlices - 1);
  81489. var roughness = 1 - smoothness;
  81490. var minLODIndex = offset; // roughness = 0
  81491. var maxLODIndex = BABYLON.Scalar.Log2(info.width) * scale + offset; // roughness = 1
  81492. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  81493. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  81494. var glTextureFromLod = new BABYLON.InternalTexture(engine, BABYLON.InternalTexture.DATASOURCE_TEMP);
  81495. glTextureFromLod.isCube = true;
  81496. glTextureFromLod.invertY = true;
  81497. glTextureFromLod.generateMipMaps = false;
  81498. engine.updateTextureSamplingMode(BABYLON.Texture.LINEAR_LINEAR, glTextureFromLod);
  81499. // Wrap in a base texture for easy binding.
  81500. var lodTexture = new BABYLON.BaseTexture(null);
  81501. lodTexture.isCube = true;
  81502. lodTexture._texture = glTextureFromLod;
  81503. lodTextures[mipmapIndex] = lodTexture;
  81504. switch (i) {
  81505. case 0:
  81506. texture._lodTextureLow = lodTexture;
  81507. break;
  81508. case 1:
  81509. texture._lodTextureMid = lodTexture;
  81510. break;
  81511. case 2:
  81512. texture._lodTextureHigh = lodTexture;
  81513. break;
  81514. }
  81515. }
  81516. }
  81517. }
  81518. var promises = [];
  81519. var _loop_3 = function (i) {
  81520. var _loop_4 = function (face) {
  81521. // Retrieves the face data
  81522. var imageData = specularInfo.mipmaps[i * 6 + face];
  81523. var bytes = new Uint8Array(arrayBuffer, specularInfo.specularDataPosition + imageData.position, imageData.length);
  81524. // Constructs an image element from bytes
  81525. var blob = new Blob([bytes], { type: 'image/png' });
  81526. var url = URL.createObjectURL(blob);
  81527. var image = new Image();
  81528. image.src = url;
  81529. // Enqueue promise to upload to the texture.
  81530. var promise = new Promise(function (resolve, reject) {
  81531. ;
  81532. image.onload = function () {
  81533. if (expandTexture) {
  81534. var tempTexture_1 = engine.createTexture(null, true, true, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, function (message) {
  81535. reject(message);
  81536. }, image);
  81537. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  81538. // Uncompress the data to a RTT
  81539. rgbdPostProcess.onApply = function (effect) {
  81540. effect._bindTexture("textureSampler", tempTexture_1);
  81541. effect.setFloat2("scale", 1, 1);
  81542. };
  81543. engine.scenes[0].postProcessManager.directRender([rgbdPostProcess], cubeRtt, true, face, i);
  81544. // Cleanup
  81545. engine.restoreDefaultFramebuffer();
  81546. tempTexture_1.dispose();
  81547. window.URL.revokeObjectURL(url);
  81548. resolve();
  81549. });
  81550. }
  81551. else {
  81552. engine._uploadImageToTexture(texture, face, i, image);
  81553. // Upload the face to the none lod texture support
  81554. if (generateNonLODTextures) {
  81555. var lodTexture = lodTextures[i];
  81556. if (lodTexture) {
  81557. engine._uploadImageToTexture(lodTexture._texture, face, 0, image);
  81558. }
  81559. }
  81560. resolve();
  81561. }
  81562. };
  81563. image.onerror = function (error) {
  81564. reject(error);
  81565. };
  81566. });
  81567. promises.push(promise);
  81568. };
  81569. // All faces
  81570. for (var face = 0; face < 6; face++) {
  81571. _loop_4(face);
  81572. }
  81573. };
  81574. // All mipmaps
  81575. for (var i = 0; i < mipmapsCount; i++) {
  81576. _loop_3(i);
  81577. }
  81578. // Once all done, finishes the cleanup and return
  81579. return Promise.all(promises).then(function () {
  81580. // Relase temp RTT.
  81581. if (cubeRtt) {
  81582. engine._releaseFramebufferObjects(cubeRtt);
  81583. cubeRtt._swapAndDie(texture);
  81584. }
  81585. // Relase temp Post Process.
  81586. if (rgbdPostProcess) {
  81587. rgbdPostProcess.dispose();
  81588. }
  81589. // Flag internal texture as ready in case they are in use.
  81590. if (generateNonLODTextures) {
  81591. if (texture._lodTextureHigh && texture._lodTextureHigh._texture) {
  81592. texture._lodTextureHigh._texture.isReady = true;
  81593. }
  81594. if (texture._lodTextureMid && texture._lodTextureMid._texture) {
  81595. texture._lodTextureMid._texture.isReady = true;
  81596. }
  81597. if (texture._lodTextureLow && texture._lodTextureLow._texture) {
  81598. texture._lodTextureLow._texture.isReady = true;
  81599. }
  81600. }
  81601. });
  81602. };
  81603. /**
  81604. * Uploads spherical polynomials information to the texture.
  81605. * @param texture defines the texture we are trying to upload the information to
  81606. * @param arrayBuffer defines the array buffer holding the data
  81607. * @param info defines the environment texture info retrieved through the GetEnvInfo method
  81608. */
  81609. EnvironmentTextureTools.UploadPolynomials = function (texture, arrayBuffer, info) {
  81610. if (info.version !== 1) {
  81611. BABYLON.Tools.Warn('Unsupported babylon environment map version "' + info.version + '"');
  81612. }
  81613. var irradianceInfo = info.irradiance;
  81614. if (!irradianceInfo) {
  81615. return;
  81616. }
  81617. //harmonics now represent radiance
  81618. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  81619. if (irradianceInfo.polynomials) {
  81620. EnvironmentTextureTools._UploadSP(irradianceInfo, texture._sphericalPolynomial);
  81621. }
  81622. else {
  81623. // convert From SH to SP.
  81624. EnvironmentTextureTools._ConvertSHIrradianceToLambertianRadiance(irradianceInfo);
  81625. EnvironmentTextureTools._ConvertSHToSP(irradianceInfo, texture._sphericalPolynomial);
  81626. }
  81627. };
  81628. /**
  81629. * Upload spherical polynomial coefficients to the texture
  81630. * @param polynmials Spherical polynmial coefficients (9)
  81631. * @param outPolynomialCoefficents Polynomial coefficients (9) object to store result
  81632. */
  81633. EnvironmentTextureTools._UploadSP = function (polynmials, outPolynomialCoefficents) {
  81634. outPolynomialCoefficents.x.x = polynmials.x[0];
  81635. outPolynomialCoefficents.x.y = polynmials.x[1];
  81636. outPolynomialCoefficents.x.z = polynmials.x[2];
  81637. outPolynomialCoefficents.y.x = polynmials.y[0];
  81638. outPolynomialCoefficents.y.y = polynmials.y[1];
  81639. outPolynomialCoefficents.y.z = polynmials.y[2];
  81640. outPolynomialCoefficents.z.x = polynmials.z[0];
  81641. outPolynomialCoefficents.z.y = polynmials.z[1];
  81642. outPolynomialCoefficents.z.z = polynmials.z[2];
  81643. //xx
  81644. outPolynomialCoefficents.xx.x = polynmials.xx[0];
  81645. outPolynomialCoefficents.xx.y = polynmials.xx[1];
  81646. outPolynomialCoefficents.xx.z = polynmials.xx[2];
  81647. outPolynomialCoefficents.yy.x = polynmials.yy[0];
  81648. outPolynomialCoefficents.yy.y = polynmials.yy[1];
  81649. outPolynomialCoefficents.yy.z = polynmials.yy[2];
  81650. outPolynomialCoefficents.zz.x = polynmials.zz[0];
  81651. outPolynomialCoefficents.zz.y = polynmials.zz[1];
  81652. outPolynomialCoefficents.zz.z = polynmials.zz[2];
  81653. //yz
  81654. outPolynomialCoefficents.yz.x = polynmials.yz[0];
  81655. outPolynomialCoefficents.yz.y = polynmials.yz[1];
  81656. outPolynomialCoefficents.yz.z = polynmials.yz[2];
  81657. outPolynomialCoefficents.zx.x = polynmials.zx[0];
  81658. outPolynomialCoefficents.zx.y = polynmials.zx[1];
  81659. outPolynomialCoefficents.zx.z = polynmials.zx[2];
  81660. outPolynomialCoefficents.xy.x = polynmials.xy[0];
  81661. outPolynomialCoefficents.xy.y = polynmials.xy[1];
  81662. outPolynomialCoefficents.xy.z = polynmials.xy[2];
  81663. };
  81664. /**
  81665. * Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  81666. * L = (1/pi) * E * rho
  81667. *
  81668. * This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  81669. * @param harmonics Spherical harmonic coefficients (9)
  81670. */
  81671. EnvironmentTextureTools._ConvertSHIrradianceToLambertianRadiance = function (harmonics) {
  81672. var scaleFactor = 1 / Math.PI;
  81673. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  81674. // (The pixel shader must apply albedo after texture fetches, etc).
  81675. harmonics.l00[0] *= scaleFactor;
  81676. harmonics.l00[1] *= scaleFactor;
  81677. harmonics.l00[2] *= scaleFactor;
  81678. harmonics.l1_1[0] *= scaleFactor;
  81679. harmonics.l1_1[1] *= scaleFactor;
  81680. harmonics.l1_1[2] *= scaleFactor;
  81681. harmonics.l10[0] *= scaleFactor;
  81682. harmonics.l10[1] *= scaleFactor;
  81683. harmonics.l10[2] *= scaleFactor;
  81684. harmonics.l11[0] *= scaleFactor;
  81685. harmonics.l11[1] *= scaleFactor;
  81686. harmonics.l11[2] *= scaleFactor;
  81687. harmonics.l2_2[0] *= scaleFactor;
  81688. harmonics.l2_2[1] *= scaleFactor;
  81689. harmonics.l2_2[2] *= scaleFactor;
  81690. harmonics.l2_1[0] *= scaleFactor;
  81691. harmonics.l2_1[1] *= scaleFactor;
  81692. harmonics.l2_1[2] *= scaleFactor;
  81693. harmonics.l20[0] *= scaleFactor;
  81694. harmonics.l20[1] *= scaleFactor;
  81695. harmonics.l20[2] *= scaleFactor;
  81696. harmonics.l21[0] *= scaleFactor;
  81697. harmonics.l21[1] *= scaleFactor;
  81698. harmonics.l21[2] *= scaleFactor;
  81699. harmonics.l22[0] *= scaleFactor;
  81700. harmonics.l22[1] *= scaleFactor;
  81701. harmonics.l22[2] *= scaleFactor;
  81702. };
  81703. /**
  81704. * Convert spherical harmonics to spherical polynomial coefficients
  81705. * @param harmonics Spherical harmonic coefficients (9)
  81706. * @param outPolynomialCoefficents Polynomial coefficients (9) object to store result
  81707. */
  81708. EnvironmentTextureTools._ConvertSHToSP = function (harmonics, outPolynomialCoefficents) {
  81709. var rPi = 1 / Math.PI;
  81710. //x
  81711. outPolynomialCoefficents.x.x = 1.02333 * harmonics.l11[0] * rPi;
  81712. outPolynomialCoefficents.x.y = 1.02333 * harmonics.l11[1] * rPi;
  81713. outPolynomialCoefficents.x.z = 1.02333 * harmonics.l11[2] * rPi;
  81714. outPolynomialCoefficents.y.x = 1.02333 * harmonics.l1_1[0] * rPi;
  81715. outPolynomialCoefficents.y.y = 1.02333 * harmonics.l1_1[1] * rPi;
  81716. outPolynomialCoefficents.y.z = 1.02333 * harmonics.l1_1[2] * rPi;
  81717. outPolynomialCoefficents.z.x = 1.02333 * harmonics.l10[0] * rPi;
  81718. outPolynomialCoefficents.z.y = 1.02333 * harmonics.l10[1] * rPi;
  81719. outPolynomialCoefficents.z.z = 1.02333 * harmonics.l10[2] * rPi;
  81720. //xx
  81721. outPolynomialCoefficents.xx.x = (0.886277 * harmonics.l00[0] - 0.247708 * harmonics.l20[0] + 0.429043 * harmonics.l22[0]) * rPi;
  81722. outPolynomialCoefficents.xx.y = (0.886277 * harmonics.l00[1] - 0.247708 * harmonics.l20[1] + 0.429043 * harmonics.l22[1]) * rPi;
  81723. outPolynomialCoefficents.xx.z = (0.886277 * harmonics.l00[2] - 0.247708 * harmonics.l20[2] + 0.429043 * harmonics.l22[2]) * rPi;
  81724. outPolynomialCoefficents.yy.x = (0.886277 * harmonics.l00[0] - 0.247708 * harmonics.l20[0] - 0.429043 * harmonics.l22[0]) * rPi;
  81725. outPolynomialCoefficents.yy.y = (0.886277 * harmonics.l00[1] - 0.247708 * harmonics.l20[1] - 0.429043 * harmonics.l22[1]) * rPi;
  81726. outPolynomialCoefficents.yy.z = (0.886277 * harmonics.l00[2] - 0.247708 * harmonics.l20[2] - 0.429043 * harmonics.l22[2]) * rPi;
  81727. outPolynomialCoefficents.zz.x = (0.886277 * harmonics.l00[0] + 0.495417 * harmonics.l20[0]) * rPi;
  81728. outPolynomialCoefficents.zz.y = (0.886277 * harmonics.l00[1] + 0.495417 * harmonics.l20[1]) * rPi;
  81729. outPolynomialCoefficents.zz.z = (0.886277 * harmonics.l00[2] + 0.495417 * harmonics.l20[2]) * rPi;
  81730. //yz
  81731. outPolynomialCoefficents.yz.x = 0.858086 * harmonics.l2_1[0] * rPi;
  81732. outPolynomialCoefficents.yz.y = 0.858086 * harmonics.l2_1[1] * rPi;
  81733. outPolynomialCoefficents.yz.z = 0.858086 * harmonics.l2_1[2] * rPi;
  81734. outPolynomialCoefficents.zx.x = 0.858086 * harmonics.l21[0] * rPi;
  81735. outPolynomialCoefficents.zx.y = 0.858086 * harmonics.l21[1] * rPi;
  81736. outPolynomialCoefficents.zx.z = 0.858086 * harmonics.l21[2] * rPi;
  81737. outPolynomialCoefficents.xy.x = 0.858086 * harmonics.l2_2[0] * rPi;
  81738. outPolynomialCoefficents.xy.y = 0.858086 * harmonics.l2_2[1] * rPi;
  81739. outPolynomialCoefficents.xy.z = 0.858086 * harmonics.l2_2[2] * rPi;
  81740. };
  81741. /**
  81742. * Magic number identifying the env file.
  81743. */
  81744. EnvironmentTextureTools._MagicBytes = [0x86, 0x16, 0x87, 0x96, 0xf6, 0xd6, 0x96, 0x36];
  81745. return EnvironmentTextureTools;
  81746. }());
  81747. BABYLON.EnvironmentTextureTools = EnvironmentTextureTools;
  81748. })(BABYLON || (BABYLON = {}));
  81749. //# sourceMappingURL=babylon.environmentTextureTools.js.map
  81750. var BABYLON;
  81751. (function (BABYLON) {
  81752. /**
  81753. * This represents a texture coming from an HDR input.
  81754. *
  81755. * The only supported format is currently panorama picture stored in RGBE format.
  81756. * Example of such files can be found on HDRLib: http://hdrlib.com/
  81757. */
  81758. var HDRCubeTexture = /** @class */ (function (_super) {
  81759. __extends(HDRCubeTexture, _super);
  81760. /**
  81761. * Instantiates an HDRTexture from the following parameters.
  81762. *
  81763. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  81764. * @param scene The scene the texture will be used in
  81765. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  81766. * @param noMipmap Forces to not generate the mipmap if true
  81767. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  81768. * @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)
  81769. * @param reserved Reserved flag for internal use.
  81770. */
  81771. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, gammaSpace, reserved, onLoad, onError) {
  81772. if (noMipmap === void 0) { noMipmap = false; }
  81773. if (generateHarmonics === void 0) { generateHarmonics = true; }
  81774. if (gammaSpace === void 0) { gammaSpace = false; }
  81775. if (reserved === void 0) { reserved = false; }
  81776. if (onLoad === void 0) { onLoad = null; }
  81777. if (onError === void 0) { onError = null; }
  81778. var _this = _super.call(this, scene) || this;
  81779. _this._generateHarmonics = true;
  81780. _this._onLoad = null;
  81781. _this._onError = null;
  81782. /**
  81783. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  81784. */
  81785. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  81786. _this._isBlocking = true;
  81787. _this._rotationY = 0;
  81788. /**
  81789. * Gets or sets the center of the bounding box associated with the cube texture
  81790. * It must define where the camera used to render the texture was set
  81791. */
  81792. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  81793. if (!url) {
  81794. return _this;
  81795. }
  81796. _this.name = url;
  81797. _this.url = url;
  81798. _this.hasAlpha = false;
  81799. _this.isCube = true;
  81800. _this._textureMatrix = BABYLON.Matrix.Identity();
  81801. _this._onLoad = onLoad;
  81802. _this._onError = onError;
  81803. _this.gammaSpace = gammaSpace;
  81804. _this._noMipmap = noMipmap;
  81805. _this._size = size;
  81806. _this._texture = _this._getFromCache(url, _this._noMipmap);
  81807. if (!_this._texture) {
  81808. if (!scene.useDelayedTextureLoading) {
  81809. _this.loadTexture();
  81810. }
  81811. else {
  81812. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  81813. }
  81814. }
  81815. return _this;
  81816. }
  81817. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  81818. /**
  81819. * Gets wether or not the texture is blocking during loading.
  81820. */
  81821. get: function () {
  81822. return this._isBlocking;
  81823. },
  81824. /**
  81825. * Sets wether or not the texture is blocking during loading.
  81826. */
  81827. set: function (value) {
  81828. this._isBlocking = value;
  81829. },
  81830. enumerable: true,
  81831. configurable: true
  81832. });
  81833. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  81834. /**
  81835. * Gets texture matrix rotation angle around Y axis radians.
  81836. */
  81837. get: function () {
  81838. return this._rotationY;
  81839. },
  81840. /**
  81841. * Sets texture matrix rotation angle around Y axis in radians.
  81842. */
  81843. set: function (value) {
  81844. this._rotationY = value;
  81845. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  81846. },
  81847. enumerable: true,
  81848. configurable: true
  81849. });
  81850. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  81851. get: function () {
  81852. return this._boundingBoxSize;
  81853. },
  81854. /**
  81855. * Gets or sets the size of the bounding box associated with the cube texture
  81856. * When defined, the cubemap will switch to local mode
  81857. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  81858. * @example https://www.babylonjs-playground.com/#RNASML
  81859. */
  81860. set: function (value) {
  81861. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  81862. return;
  81863. }
  81864. this._boundingBoxSize = value;
  81865. var scene = this.getScene();
  81866. if (scene) {
  81867. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  81868. }
  81869. },
  81870. enumerable: true,
  81871. configurable: true
  81872. });
  81873. /**
  81874. * Occurs when the file is raw .hdr file.
  81875. */
  81876. HDRCubeTexture.prototype.loadTexture = function () {
  81877. var _this = this;
  81878. var callback = function (buffer) {
  81879. _this.lodGenerationOffset = 0.0;
  81880. _this.lodGenerationScale = 0.8;
  81881. var scene = _this.getScene();
  81882. if (!scene) {
  81883. return null;
  81884. }
  81885. // Extract the raw linear data.
  81886. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  81887. // Generate harmonics if needed.
  81888. if (_this._generateHarmonics) {
  81889. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  81890. _this.sphericalPolynomial = sphericalPolynomial;
  81891. }
  81892. var results = [];
  81893. var byteArray = null;
  81894. // Push each faces.
  81895. for (var j = 0; j < 6; j++) {
  81896. // Create uintarray fallback.
  81897. if (!scene.getEngine().getCaps().textureFloat) {
  81898. // 3 channels of 1 bytes per pixel in bytes.
  81899. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  81900. byteArray = new Uint8Array(byteBuffer);
  81901. }
  81902. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  81903. // If special cases.
  81904. if (_this.gammaSpace || byteArray) {
  81905. for (var i = 0; i < _this._size * _this._size; i++) {
  81906. // Put in gamma space if requested.
  81907. if (_this.gammaSpace) {
  81908. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  81909. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  81910. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  81911. }
  81912. // Convert to int texture for fallback.
  81913. if (byteArray) {
  81914. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  81915. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  81916. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  81917. // May use luminance instead if the result is not accurate.
  81918. var max = Math.max(Math.max(r, g), b);
  81919. if (max > 255) {
  81920. var scale = 255 / max;
  81921. r *= scale;
  81922. g *= scale;
  81923. b *= scale;
  81924. }
  81925. byteArray[(i * 3) + 0] = r;
  81926. byteArray[(i * 3) + 1] = g;
  81927. byteArray[(i * 3) + 2] = b;
  81928. }
  81929. }
  81930. }
  81931. if (byteArray) {
  81932. results.push(byteArray);
  81933. }
  81934. else {
  81935. results.push(dataFace);
  81936. }
  81937. }
  81938. return results;
  81939. };
  81940. var scene = this.getScene();
  81941. if (scene) {
  81942. 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);
  81943. }
  81944. };
  81945. HDRCubeTexture.prototype.clone = function () {
  81946. var scene = this.getScene();
  81947. if (!scene) {
  81948. return this;
  81949. }
  81950. var newTexture = new HDRCubeTexture(this.url, scene, this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace);
  81951. // Base texture
  81952. newTexture.level = this.level;
  81953. newTexture.wrapU = this.wrapU;
  81954. newTexture.wrapV = this.wrapV;
  81955. newTexture.coordinatesIndex = this.coordinatesIndex;
  81956. newTexture.coordinatesMode = this.coordinatesMode;
  81957. return newTexture;
  81958. };
  81959. // Methods
  81960. HDRCubeTexture.prototype.delayLoad = function () {
  81961. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  81962. return;
  81963. }
  81964. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  81965. this._texture = this._getFromCache(this.url, this._noMipmap);
  81966. if (!this._texture) {
  81967. this.loadTexture();
  81968. }
  81969. };
  81970. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  81971. return this._textureMatrix;
  81972. };
  81973. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  81974. this._textureMatrix = value;
  81975. };
  81976. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  81977. var texture = null;
  81978. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  81979. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace);
  81980. texture.name = parsedTexture.name;
  81981. texture.hasAlpha = parsedTexture.hasAlpha;
  81982. texture.level = parsedTexture.level;
  81983. texture.coordinatesMode = parsedTexture.coordinatesMode;
  81984. texture.isBlocking = parsedTexture.isBlocking;
  81985. }
  81986. if (texture) {
  81987. if (parsedTexture.boundingBoxPosition) {
  81988. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  81989. }
  81990. if (parsedTexture.boundingBoxSize) {
  81991. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  81992. }
  81993. if (parsedTexture.rotationY) {
  81994. texture.rotationY = parsedTexture.rotationY;
  81995. }
  81996. }
  81997. return texture;
  81998. };
  81999. HDRCubeTexture.prototype.serialize = function () {
  82000. if (!this.name) {
  82001. return null;
  82002. }
  82003. var serializationObject = {};
  82004. serializationObject.name = this.name;
  82005. serializationObject.hasAlpha = this.hasAlpha;
  82006. serializationObject.isCube = true;
  82007. serializationObject.level = this.level;
  82008. serializationObject.size = this._size;
  82009. serializationObject.coordinatesMode = this.coordinatesMode;
  82010. serializationObject.useInGammaSpace = this.gammaSpace;
  82011. serializationObject.generateHarmonics = this._generateHarmonics;
  82012. serializationObject.customType = "BABYLON.HDRCubeTexture";
  82013. serializationObject.noMipmap = this._noMipmap;
  82014. serializationObject.isBlocking = this._isBlocking;
  82015. serializationObject.rotationY = this._rotationY;
  82016. return serializationObject;
  82017. };
  82018. HDRCubeTexture._facesMapping = [
  82019. "right",
  82020. "left",
  82021. "up",
  82022. "down",
  82023. "front",
  82024. "back"
  82025. ];
  82026. return HDRCubeTexture;
  82027. }(BABYLON.BaseTexture));
  82028. BABYLON.HDRCubeTexture = HDRCubeTexture;
  82029. })(BABYLON || (BABYLON = {}));
  82030. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  82031. var BABYLON;
  82032. (function (BABYLON) {
  82033. var IndexedVector2 = /** @class */ (function (_super) {
  82034. __extends(IndexedVector2, _super);
  82035. function IndexedVector2(original, index) {
  82036. var _this = _super.call(this, original.x, original.y) || this;
  82037. _this.index = index;
  82038. return _this;
  82039. }
  82040. return IndexedVector2;
  82041. }(BABYLON.Vector2));
  82042. var PolygonPoints = /** @class */ (function () {
  82043. function PolygonPoints() {
  82044. this.elements = new Array();
  82045. }
  82046. PolygonPoints.prototype.add = function (originalPoints) {
  82047. var _this = this;
  82048. var result = new Array();
  82049. originalPoints.forEach(function (point) {
  82050. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  82051. var newPoint = new IndexedVector2(point, _this.elements.length);
  82052. result.push(newPoint);
  82053. _this.elements.push(newPoint);
  82054. }
  82055. });
  82056. return result;
  82057. };
  82058. PolygonPoints.prototype.computeBounds = function () {
  82059. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  82060. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  82061. this.elements.forEach(function (point) {
  82062. // x
  82063. if (point.x < lmin.x) {
  82064. lmin.x = point.x;
  82065. }
  82066. else if (point.x > lmax.x) {
  82067. lmax.x = point.x;
  82068. }
  82069. // y
  82070. if (point.y < lmin.y) {
  82071. lmin.y = point.y;
  82072. }
  82073. else if (point.y > lmax.y) {
  82074. lmax.y = point.y;
  82075. }
  82076. });
  82077. return {
  82078. min: lmin,
  82079. max: lmax,
  82080. width: lmax.x - lmin.x,
  82081. height: lmax.y - lmin.y
  82082. };
  82083. };
  82084. return PolygonPoints;
  82085. }());
  82086. var Polygon = /** @class */ (function () {
  82087. function Polygon() {
  82088. }
  82089. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  82090. return [
  82091. new BABYLON.Vector2(xmin, ymin),
  82092. new BABYLON.Vector2(xmax, ymin),
  82093. new BABYLON.Vector2(xmax, ymax),
  82094. new BABYLON.Vector2(xmin, ymax)
  82095. ];
  82096. };
  82097. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  82098. if (cx === void 0) { cx = 0; }
  82099. if (cy === void 0) { cy = 0; }
  82100. if (numberOfSides === void 0) { numberOfSides = 32; }
  82101. var result = new Array();
  82102. var angle = 0;
  82103. var increment = (Math.PI * 2) / numberOfSides;
  82104. for (var i = 0; i < numberOfSides; i++) {
  82105. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  82106. angle -= increment;
  82107. }
  82108. return result;
  82109. };
  82110. Polygon.Parse = function (input) {
  82111. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  82112. var i, result = [];
  82113. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  82114. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  82115. }
  82116. return result;
  82117. };
  82118. Polygon.StartingAt = function (x, y) {
  82119. return BABYLON.Path2.StartingAt(x, y);
  82120. };
  82121. return Polygon;
  82122. }());
  82123. BABYLON.Polygon = Polygon;
  82124. var PolygonMeshBuilder = /** @class */ (function () {
  82125. function PolygonMeshBuilder(name, contours, scene) {
  82126. this._points = new PolygonPoints();
  82127. this._outlinepoints = new PolygonPoints();
  82128. this._holes = new Array();
  82129. this._epoints = new Array();
  82130. this._eholes = new Array();
  82131. this._name = name;
  82132. this._scene = scene;
  82133. var points;
  82134. if (contours instanceof BABYLON.Path2) {
  82135. points = contours.getPoints();
  82136. }
  82137. else {
  82138. points = contours;
  82139. }
  82140. this._addToepoint(points);
  82141. this._points.add(points);
  82142. this._outlinepoints.add(points);
  82143. if (typeof earcut === 'undefined') {
  82144. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  82145. }
  82146. }
  82147. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  82148. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  82149. var p = points_1[_i];
  82150. this._epoints.push(p.x, p.y);
  82151. }
  82152. };
  82153. PolygonMeshBuilder.prototype.addHole = function (hole) {
  82154. this._points.add(hole);
  82155. var holepoints = new PolygonPoints();
  82156. holepoints.add(hole);
  82157. this._holes.push(holepoints);
  82158. this._eholes.push(this._epoints.length / 2);
  82159. this._addToepoint(hole);
  82160. return this;
  82161. };
  82162. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  82163. var _this = this;
  82164. if (updatable === void 0) { updatable = false; }
  82165. if (depth === void 0) { depth = 0; }
  82166. var result = new BABYLON.Mesh(this._name, this._scene);
  82167. var normals = new Array();
  82168. var positions = new Array();
  82169. var uvs = new Array();
  82170. var bounds = this._points.computeBounds();
  82171. this._points.elements.forEach(function (p) {
  82172. normals.push(0, 1.0, 0);
  82173. positions.push(p.x, 0, p.y);
  82174. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  82175. });
  82176. var indices = new Array();
  82177. var res = earcut(this._epoints, this._eholes, 2);
  82178. for (var i = 0; i < res.length; i++) {
  82179. indices.push(res[i]);
  82180. }
  82181. if (depth > 0) {
  82182. var positionscount = (positions.length / 3); //get the current pointcount
  82183. this._points.elements.forEach(function (p) {
  82184. normals.push(0, -1.0, 0);
  82185. positions.push(p.x, -depth, p.y);
  82186. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  82187. });
  82188. var totalCount = indices.length;
  82189. for (var i = 0; i < totalCount; i += 3) {
  82190. var i0 = indices[i + 0];
  82191. var i1 = indices[i + 1];
  82192. var i2 = indices[i + 2];
  82193. indices.push(i2 + positionscount);
  82194. indices.push(i1 + positionscount);
  82195. indices.push(i0 + positionscount);
  82196. }
  82197. //Add the sides
  82198. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  82199. this._holes.forEach(function (hole) {
  82200. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  82201. });
  82202. }
  82203. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  82204. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  82205. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  82206. result.setIndices(indices);
  82207. return result;
  82208. };
  82209. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  82210. var StartIndex = positions.length / 3;
  82211. var ulength = 0;
  82212. for (var i = 0; i < points.elements.length; i++) {
  82213. var p = points.elements[i];
  82214. var p1;
  82215. if ((i + 1) > points.elements.length - 1) {
  82216. p1 = points.elements[0];
  82217. }
  82218. else {
  82219. p1 = points.elements[i + 1];
  82220. }
  82221. positions.push(p.x, 0, p.y);
  82222. positions.push(p.x, -depth, p.y);
  82223. positions.push(p1.x, 0, p1.y);
  82224. positions.push(p1.x, -depth, p1.y);
  82225. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  82226. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  82227. var v3 = v2.subtract(v1);
  82228. var v4 = new BABYLON.Vector3(0, 1, 0);
  82229. var vn = BABYLON.Vector3.Cross(v3, v4);
  82230. vn = vn.normalize();
  82231. uvs.push(ulength / bounds.width, 0);
  82232. uvs.push(ulength / bounds.width, 1);
  82233. ulength += v3.length();
  82234. uvs.push((ulength / bounds.width), 0);
  82235. uvs.push((ulength / bounds.width), 1);
  82236. if (!flip) {
  82237. normals.push(-vn.x, -vn.y, -vn.z);
  82238. normals.push(-vn.x, -vn.y, -vn.z);
  82239. normals.push(-vn.x, -vn.y, -vn.z);
  82240. normals.push(-vn.x, -vn.y, -vn.z);
  82241. indices.push(StartIndex);
  82242. indices.push(StartIndex + 1);
  82243. indices.push(StartIndex + 2);
  82244. indices.push(StartIndex + 1);
  82245. indices.push(StartIndex + 3);
  82246. indices.push(StartIndex + 2);
  82247. }
  82248. else {
  82249. normals.push(vn.x, vn.y, vn.z);
  82250. normals.push(vn.x, vn.y, vn.z);
  82251. normals.push(vn.x, vn.y, vn.z);
  82252. normals.push(vn.x, vn.y, vn.z);
  82253. indices.push(StartIndex);
  82254. indices.push(StartIndex + 2);
  82255. indices.push(StartIndex + 1);
  82256. indices.push(StartIndex + 1);
  82257. indices.push(StartIndex + 2);
  82258. indices.push(StartIndex + 3);
  82259. }
  82260. StartIndex += 4;
  82261. }
  82262. ;
  82263. };
  82264. return PolygonMeshBuilder;
  82265. }());
  82266. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  82267. })(BABYLON || (BABYLON = {}));
  82268. //# sourceMappingURL=babylon.polygonMesh.js.map
  82269. var BABYLON;
  82270. (function (BABYLON) {
  82271. // Unique ID when we import meshes from Babylon to CSG
  82272. var currentCSGMeshId = 0;
  82273. // # class Vertex
  82274. // Represents a vertex of a polygon. Use your own vertex class instead of this
  82275. // one to provide additional features like texture coordinates and vertex
  82276. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  82277. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  82278. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  82279. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  82280. // is not used anywhere else.
  82281. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  82282. var Vertex = /** @class */ (function () {
  82283. function Vertex(pos, normal, uv) {
  82284. this.pos = pos;
  82285. this.normal = normal;
  82286. this.uv = uv;
  82287. }
  82288. Vertex.prototype.clone = function () {
  82289. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  82290. };
  82291. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  82292. // orientation of a polygon is flipped.
  82293. Vertex.prototype.flip = function () {
  82294. this.normal = this.normal.scale(-1);
  82295. };
  82296. // Create a new vertex between this vertex and `other` by linearly
  82297. // interpolating all properties using a parameter of `t`. Subclasses should
  82298. // override this to interpolate additional properties.
  82299. Vertex.prototype.interpolate = function (other, t) {
  82300. 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));
  82301. };
  82302. return Vertex;
  82303. }());
  82304. // # class Plane
  82305. // Represents a plane in 3D space.
  82306. var Plane = /** @class */ (function () {
  82307. function Plane(normal, w) {
  82308. this.normal = normal;
  82309. this.w = w;
  82310. }
  82311. Plane.FromPoints = function (a, b, c) {
  82312. var v0 = c.subtract(a);
  82313. var v1 = b.subtract(a);
  82314. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  82315. return null;
  82316. }
  82317. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  82318. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  82319. };
  82320. Plane.prototype.clone = function () {
  82321. return new Plane(this.normal.clone(), this.w);
  82322. };
  82323. Plane.prototype.flip = function () {
  82324. this.normal.scaleInPlace(-1);
  82325. this.w = -this.w;
  82326. };
  82327. // Split `polygon` by this plane if needed, then put the polygon or polygon
  82328. // fragments in the appropriate lists. Coplanar polygons go into either
  82329. // `coplanarFront` or `coplanarBack` depending on their orientation with
  82330. // respect to this plane. Polygons in front or in back of this plane go into
  82331. // either `front` or `back`.
  82332. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  82333. var COPLANAR = 0;
  82334. var FRONT = 1;
  82335. var BACK = 2;
  82336. var SPANNING = 3;
  82337. // Classify each point as well as the entire polygon into one of the above
  82338. // four classes.
  82339. var polygonType = 0;
  82340. var types = [];
  82341. var i;
  82342. var t;
  82343. for (i = 0; i < polygon.vertices.length; i++) {
  82344. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  82345. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  82346. polygonType |= type;
  82347. types.push(type);
  82348. }
  82349. // Put the polygon in the correct list, splitting it when necessary.
  82350. switch (polygonType) {
  82351. case COPLANAR:
  82352. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  82353. break;
  82354. case FRONT:
  82355. front.push(polygon);
  82356. break;
  82357. case BACK:
  82358. back.push(polygon);
  82359. break;
  82360. case SPANNING:
  82361. var f = [], b = [];
  82362. for (i = 0; i < polygon.vertices.length; i++) {
  82363. var j = (i + 1) % polygon.vertices.length;
  82364. var ti = types[i], tj = types[j];
  82365. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  82366. if (ti !== BACK)
  82367. f.push(vi);
  82368. if (ti !== FRONT)
  82369. b.push(ti !== BACK ? vi.clone() : vi);
  82370. if ((ti | tj) === SPANNING) {
  82371. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  82372. var v = vi.interpolate(vj, t);
  82373. f.push(v);
  82374. b.push(v.clone());
  82375. }
  82376. }
  82377. var poly;
  82378. if (f.length >= 3) {
  82379. poly = new Polygon(f, polygon.shared);
  82380. if (poly.plane)
  82381. front.push(poly);
  82382. }
  82383. if (b.length >= 3) {
  82384. poly = new Polygon(b, polygon.shared);
  82385. if (poly.plane)
  82386. back.push(poly);
  82387. }
  82388. break;
  82389. }
  82390. };
  82391. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  82392. // point is on the plane.
  82393. Plane.EPSILON = 1e-5;
  82394. return Plane;
  82395. }());
  82396. // # class Polygon
  82397. // Represents a convex polygon. The vertices used to initialize a polygon must
  82398. // be coplanar and form a convex loop.
  82399. //
  82400. // Each convex polygon has a `shared` property, which is shared between all
  82401. // polygons that are clones of each other or were split from the same polygon.
  82402. // This can be used to define per-polygon properties (such as surface color).
  82403. var Polygon = /** @class */ (function () {
  82404. function Polygon(vertices, shared) {
  82405. this.vertices = vertices;
  82406. this.shared = shared;
  82407. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  82408. }
  82409. Polygon.prototype.clone = function () {
  82410. var vertices = this.vertices.map(function (v) { return v.clone(); });
  82411. return new Polygon(vertices, this.shared);
  82412. };
  82413. Polygon.prototype.flip = function () {
  82414. this.vertices.reverse().map(function (v) { v.flip(); });
  82415. this.plane.flip();
  82416. };
  82417. return Polygon;
  82418. }());
  82419. // # class Node
  82420. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  82421. // by picking a polygon to split along. That polygon (and all other coplanar
  82422. // polygons) are added directly to that node and the other polygons are added to
  82423. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  82424. // no distinction between internal and leaf nodes.
  82425. var Node = /** @class */ (function () {
  82426. function Node(polygons) {
  82427. this.plane = null;
  82428. this.front = null;
  82429. this.back = null;
  82430. this.polygons = new Array();
  82431. if (polygons) {
  82432. this.build(polygons);
  82433. }
  82434. }
  82435. Node.prototype.clone = function () {
  82436. var node = new Node();
  82437. node.plane = this.plane && this.plane.clone();
  82438. node.front = this.front && this.front.clone();
  82439. node.back = this.back && this.back.clone();
  82440. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  82441. return node;
  82442. };
  82443. // Convert solid space to empty space and empty space to solid space.
  82444. Node.prototype.invert = function () {
  82445. for (var i = 0; i < this.polygons.length; i++) {
  82446. this.polygons[i].flip();
  82447. }
  82448. if (this.plane) {
  82449. this.plane.flip();
  82450. }
  82451. if (this.front) {
  82452. this.front.invert();
  82453. }
  82454. if (this.back) {
  82455. this.back.invert();
  82456. }
  82457. var temp = this.front;
  82458. this.front = this.back;
  82459. this.back = temp;
  82460. };
  82461. // Recursively remove all polygons in `polygons` that are inside this BSP
  82462. // tree.
  82463. Node.prototype.clipPolygons = function (polygons) {
  82464. if (!this.plane)
  82465. return polygons.slice();
  82466. var front = new Array(), back = new Array();
  82467. for (var i = 0; i < polygons.length; i++) {
  82468. this.plane.splitPolygon(polygons[i], front, back, front, back);
  82469. }
  82470. if (this.front) {
  82471. front = this.front.clipPolygons(front);
  82472. }
  82473. if (this.back) {
  82474. back = this.back.clipPolygons(back);
  82475. }
  82476. else {
  82477. back = [];
  82478. }
  82479. return front.concat(back);
  82480. };
  82481. // Remove all polygons in this BSP tree that are inside the other BSP tree
  82482. // `bsp`.
  82483. Node.prototype.clipTo = function (bsp) {
  82484. this.polygons = bsp.clipPolygons(this.polygons);
  82485. if (this.front)
  82486. this.front.clipTo(bsp);
  82487. if (this.back)
  82488. this.back.clipTo(bsp);
  82489. };
  82490. // Return a list of all polygons in this BSP tree.
  82491. Node.prototype.allPolygons = function () {
  82492. var polygons = this.polygons.slice();
  82493. if (this.front)
  82494. polygons = polygons.concat(this.front.allPolygons());
  82495. if (this.back)
  82496. polygons = polygons.concat(this.back.allPolygons());
  82497. return polygons;
  82498. };
  82499. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  82500. // new polygons are filtered down to the bottom of the tree and become new
  82501. // nodes there. Each set of polygons is partitioned using the first polygon
  82502. // (no heuristic is used to pick a good split).
  82503. Node.prototype.build = function (polygons) {
  82504. if (!polygons.length)
  82505. return;
  82506. if (!this.plane)
  82507. this.plane = polygons[0].plane.clone();
  82508. var front = new Array(), back = new Array();
  82509. for (var i = 0; i < polygons.length; i++) {
  82510. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  82511. }
  82512. if (front.length) {
  82513. if (!this.front)
  82514. this.front = new Node();
  82515. this.front.build(front);
  82516. }
  82517. if (back.length) {
  82518. if (!this.back)
  82519. this.back = new Node();
  82520. this.back.build(back);
  82521. }
  82522. };
  82523. return Node;
  82524. }());
  82525. var CSG = /** @class */ (function () {
  82526. function CSG() {
  82527. this.polygons = new Array();
  82528. }
  82529. // Convert BABYLON.Mesh to BABYLON.CSG
  82530. CSG.FromMesh = function (mesh) {
  82531. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  82532. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  82533. if (mesh instanceof BABYLON.Mesh) {
  82534. mesh.computeWorldMatrix(true);
  82535. matrix = mesh.getWorldMatrix();
  82536. meshPosition = mesh.position.clone();
  82537. meshRotation = mesh.rotation.clone();
  82538. if (mesh.rotationQuaternion) {
  82539. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  82540. }
  82541. meshScaling = mesh.scaling.clone();
  82542. }
  82543. else {
  82544. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  82545. }
  82546. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  82547. var subMeshes = mesh.subMeshes;
  82548. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  82549. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  82550. vertices = [];
  82551. for (var j = 0; j < 3; j++) {
  82552. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  82553. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  82554. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  82555. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  82556. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  82557. vertex = new Vertex(position, normal, uv);
  82558. vertices.push(vertex);
  82559. }
  82560. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  82561. // To handle the case of degenerated triangle
  82562. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  82563. if (polygon.plane)
  82564. polygons.push(polygon);
  82565. }
  82566. }
  82567. var csg = CSG.FromPolygons(polygons);
  82568. csg.matrix = matrix;
  82569. csg.position = meshPosition;
  82570. csg.rotation = meshRotation;
  82571. csg.scaling = meshScaling;
  82572. csg.rotationQuaternion = meshRotationQuaternion;
  82573. currentCSGMeshId++;
  82574. return csg;
  82575. };
  82576. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  82577. CSG.FromPolygons = function (polygons) {
  82578. var csg = new CSG();
  82579. csg.polygons = polygons;
  82580. return csg;
  82581. };
  82582. CSG.prototype.clone = function () {
  82583. var csg = new CSG();
  82584. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  82585. csg.copyTransformAttributes(this);
  82586. return csg;
  82587. };
  82588. CSG.prototype.union = function (csg) {
  82589. var a = new Node(this.clone().polygons);
  82590. var b = new Node(csg.clone().polygons);
  82591. a.clipTo(b);
  82592. b.clipTo(a);
  82593. b.invert();
  82594. b.clipTo(a);
  82595. b.invert();
  82596. a.build(b.allPolygons());
  82597. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  82598. };
  82599. CSG.prototype.unionInPlace = function (csg) {
  82600. var a = new Node(this.polygons);
  82601. var b = new Node(csg.polygons);
  82602. a.clipTo(b);
  82603. b.clipTo(a);
  82604. b.invert();
  82605. b.clipTo(a);
  82606. b.invert();
  82607. a.build(b.allPolygons());
  82608. this.polygons = a.allPolygons();
  82609. };
  82610. CSG.prototype.subtract = function (csg) {
  82611. var a = new Node(this.clone().polygons);
  82612. var b = new Node(csg.clone().polygons);
  82613. a.invert();
  82614. a.clipTo(b);
  82615. b.clipTo(a);
  82616. b.invert();
  82617. b.clipTo(a);
  82618. b.invert();
  82619. a.build(b.allPolygons());
  82620. a.invert();
  82621. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  82622. };
  82623. CSG.prototype.subtractInPlace = function (csg) {
  82624. var a = new Node(this.polygons);
  82625. var b = new Node(csg.polygons);
  82626. a.invert();
  82627. a.clipTo(b);
  82628. b.clipTo(a);
  82629. b.invert();
  82630. b.clipTo(a);
  82631. b.invert();
  82632. a.build(b.allPolygons());
  82633. a.invert();
  82634. this.polygons = a.allPolygons();
  82635. };
  82636. CSG.prototype.intersect = function (csg) {
  82637. var a = new Node(this.clone().polygons);
  82638. var b = new Node(csg.clone().polygons);
  82639. a.invert();
  82640. b.clipTo(a);
  82641. b.invert();
  82642. a.clipTo(b);
  82643. b.clipTo(a);
  82644. a.build(b.allPolygons());
  82645. a.invert();
  82646. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  82647. };
  82648. CSG.prototype.intersectInPlace = function (csg) {
  82649. var a = new Node(this.polygons);
  82650. var b = new Node(csg.polygons);
  82651. a.invert();
  82652. b.clipTo(a);
  82653. b.invert();
  82654. a.clipTo(b);
  82655. b.clipTo(a);
  82656. a.build(b.allPolygons());
  82657. a.invert();
  82658. this.polygons = a.allPolygons();
  82659. };
  82660. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  82661. // not modified.
  82662. CSG.prototype.inverse = function () {
  82663. var csg = this.clone();
  82664. csg.inverseInPlace();
  82665. return csg;
  82666. };
  82667. CSG.prototype.inverseInPlace = function () {
  82668. this.polygons.map(function (p) { p.flip(); });
  82669. };
  82670. // This is used to keep meshes transformations so they can be restored
  82671. // when we build back a Babylon Mesh
  82672. // NB : All CSG operations are performed in world coordinates
  82673. CSG.prototype.copyTransformAttributes = function (csg) {
  82674. this.matrix = csg.matrix;
  82675. this.position = csg.position;
  82676. this.rotation = csg.rotation;
  82677. this.scaling = csg.scaling;
  82678. this.rotationQuaternion = csg.rotationQuaternion;
  82679. return this;
  82680. };
  82681. // Build Raw mesh from CSG
  82682. // Coordinates here are in world space
  82683. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  82684. var matrix = this.matrix.clone();
  82685. matrix.invert();
  82686. 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;
  82687. if (keepSubMeshes) {
  82688. // Sort Polygons, since subMeshes are indices range
  82689. polygons.sort(function (a, b) {
  82690. if (a.shared.meshId === b.shared.meshId) {
  82691. return a.shared.subMeshId - b.shared.subMeshId;
  82692. }
  82693. else {
  82694. return a.shared.meshId - b.shared.meshId;
  82695. }
  82696. });
  82697. }
  82698. for (var i = 0, il = polygons.length; i < il; i++) {
  82699. polygon = polygons[i];
  82700. // Building SubMeshes
  82701. if (!subMesh_dict[polygon.shared.meshId]) {
  82702. subMesh_dict[polygon.shared.meshId] = {};
  82703. }
  82704. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  82705. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  82706. indexStart: +Infinity,
  82707. indexEnd: -Infinity,
  82708. materialIndex: polygon.shared.materialIndex
  82709. };
  82710. }
  82711. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  82712. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  82713. polygonIndices[0] = 0;
  82714. polygonIndices[1] = j - 1;
  82715. polygonIndices[2] = j;
  82716. for (var k = 0; k < 3; k++) {
  82717. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  82718. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  82719. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  82720. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  82721. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  82722. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  82723. // Check if 2 points can be merged
  82724. if (!(typeof vertex_idx !== 'undefined' &&
  82725. normals[vertex_idx * 3] === localNormal.x &&
  82726. normals[vertex_idx * 3 + 1] === localNormal.y &&
  82727. normals[vertex_idx * 3 + 2] === localNormal.z &&
  82728. uvs[vertex_idx * 2] === uv.x &&
  82729. uvs[vertex_idx * 2 + 1] === uv.y)) {
  82730. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  82731. uvs.push(uv.x, uv.y);
  82732. normals.push(normal.x, normal.y, normal.z);
  82733. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  82734. }
  82735. indices.push(vertex_idx);
  82736. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  82737. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  82738. currentIndex++;
  82739. }
  82740. }
  82741. }
  82742. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  82743. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  82744. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  82745. mesh.setIndices(indices, null);
  82746. if (keepSubMeshes) {
  82747. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  82748. var materialIndexOffset = 0, materialMaxIndex;
  82749. mesh.subMeshes = new Array();
  82750. for (var m in subMesh_dict) {
  82751. materialMaxIndex = -1;
  82752. for (var sm in subMesh_dict[m]) {
  82753. subMesh_obj = subMesh_dict[m][sm];
  82754. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  82755. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  82756. }
  82757. materialIndexOffset += ++materialMaxIndex;
  82758. }
  82759. }
  82760. return mesh;
  82761. };
  82762. // Build Mesh from CSG taking material and transforms into account
  82763. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  82764. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  82765. mesh.material = material;
  82766. mesh.position.copyFrom(this.position);
  82767. mesh.rotation.copyFrom(this.rotation);
  82768. if (this.rotationQuaternion) {
  82769. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  82770. }
  82771. mesh.scaling.copyFrom(this.scaling);
  82772. mesh.computeWorldMatrix(true);
  82773. return mesh;
  82774. };
  82775. return CSG;
  82776. }());
  82777. BABYLON.CSG = CSG;
  82778. })(BABYLON || (BABYLON = {}));
  82779. //# sourceMappingURL=babylon.csg.js.map
  82780. var BABYLON;
  82781. (function (BABYLON) {
  82782. var LensFlare = /** @class */ (function () {
  82783. function LensFlare(size, position, color, imgUrl, system) {
  82784. this.size = size;
  82785. this.position = position;
  82786. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  82787. this.color = color || new BABYLON.Color3(1, 1, 1);
  82788. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  82789. this._system = system;
  82790. system.lensFlares.push(this);
  82791. }
  82792. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  82793. return new LensFlare(size, position, color, imgUrl, system);
  82794. };
  82795. LensFlare.prototype.dispose = function () {
  82796. if (this.texture) {
  82797. this.texture.dispose();
  82798. }
  82799. // Remove from scene
  82800. var index = this._system.lensFlares.indexOf(this);
  82801. this._system.lensFlares.splice(index, 1);
  82802. };
  82803. ;
  82804. return LensFlare;
  82805. }());
  82806. BABYLON.LensFlare = LensFlare;
  82807. })(BABYLON || (BABYLON = {}));
  82808. //# sourceMappingURL=babylon.lensFlare.js.map
  82809. var BABYLON;
  82810. (function (BABYLON) {
  82811. var LensFlareSystem = /** @class */ (function () {
  82812. function LensFlareSystem(name, emitter, scene) {
  82813. this.name = name;
  82814. this.lensFlares = new Array();
  82815. this.borderLimit = 300;
  82816. this.viewportBorder = 0;
  82817. this.layerMask = 0x0FFFFFFF;
  82818. this._vertexBuffers = {};
  82819. this._isEnabled = true;
  82820. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  82821. this._emitter = emitter;
  82822. this.id = name;
  82823. scene.lensFlareSystems.push(this);
  82824. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  82825. var engine = scene.getEngine();
  82826. // VBO
  82827. var vertices = [];
  82828. vertices.push(1, 1);
  82829. vertices.push(-1, 1);
  82830. vertices.push(-1, -1);
  82831. vertices.push(1, -1);
  82832. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  82833. // Indices
  82834. var indices = [];
  82835. indices.push(0);
  82836. indices.push(1);
  82837. indices.push(2);
  82838. indices.push(0);
  82839. indices.push(2);
  82840. indices.push(3);
  82841. this._indexBuffer = engine.createIndexBuffer(indices);
  82842. // Effects
  82843. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  82844. }
  82845. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  82846. get: function () {
  82847. return this._isEnabled;
  82848. },
  82849. set: function (value) {
  82850. this._isEnabled = value;
  82851. },
  82852. enumerable: true,
  82853. configurable: true
  82854. });
  82855. LensFlareSystem.prototype.getScene = function () {
  82856. return this._scene;
  82857. };
  82858. LensFlareSystem.prototype.getEmitter = function () {
  82859. return this._emitter;
  82860. };
  82861. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  82862. this._emitter = newEmitter;
  82863. };
  82864. LensFlareSystem.prototype.getEmitterPosition = function () {
  82865. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  82866. };
  82867. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  82868. var position = this.getEmitterPosition();
  82869. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  82870. this._positionX = position.x;
  82871. this._positionY = position.y;
  82872. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  82873. if (this.viewportBorder > 0) {
  82874. globalViewport.x -= this.viewportBorder;
  82875. globalViewport.y -= this.viewportBorder;
  82876. globalViewport.width += this.viewportBorder * 2;
  82877. globalViewport.height += this.viewportBorder * 2;
  82878. position.x += this.viewportBorder;
  82879. position.y += this.viewportBorder;
  82880. this._positionX += this.viewportBorder;
  82881. this._positionY += this.viewportBorder;
  82882. }
  82883. if (position.z > 0) {
  82884. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  82885. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  82886. return true;
  82887. }
  82888. return true;
  82889. }
  82890. return false;
  82891. };
  82892. LensFlareSystem.prototype._isVisible = function () {
  82893. if (!this._isEnabled || !this._scene.activeCamera) {
  82894. return false;
  82895. }
  82896. var emitterPosition = this.getEmitterPosition();
  82897. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  82898. var distance = direction.length();
  82899. direction.normalize();
  82900. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  82901. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  82902. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  82903. };
  82904. LensFlareSystem.prototype.render = function () {
  82905. if (!this._effect.isReady() || !this._scene.activeCamera)
  82906. return false;
  82907. var engine = this._scene.getEngine();
  82908. var viewport = this._scene.activeCamera.viewport;
  82909. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  82910. // Position
  82911. if (!this.computeEffectivePosition(globalViewport)) {
  82912. return false;
  82913. }
  82914. // Visibility
  82915. if (!this._isVisible()) {
  82916. return false;
  82917. }
  82918. // Intensity
  82919. var awayX;
  82920. var awayY;
  82921. if (this._positionX < this.borderLimit + globalViewport.x) {
  82922. awayX = this.borderLimit + globalViewport.x - this._positionX;
  82923. }
  82924. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  82925. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  82926. }
  82927. else {
  82928. awayX = 0;
  82929. }
  82930. if (this._positionY < this.borderLimit + globalViewport.y) {
  82931. awayY = this.borderLimit + globalViewport.y - this._positionY;
  82932. }
  82933. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  82934. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  82935. }
  82936. else {
  82937. awayY = 0;
  82938. }
  82939. var away = (awayX > awayY) ? awayX : awayY;
  82940. away -= this.viewportBorder;
  82941. if (away > this.borderLimit) {
  82942. away = this.borderLimit;
  82943. }
  82944. var intensity = 1.0 - (away / this.borderLimit);
  82945. if (intensity < 0) {
  82946. return false;
  82947. }
  82948. if (intensity > 1.0) {
  82949. intensity = 1.0;
  82950. }
  82951. if (this.viewportBorder > 0) {
  82952. globalViewport.x += this.viewportBorder;
  82953. globalViewport.y += this.viewportBorder;
  82954. globalViewport.width -= this.viewportBorder * 2;
  82955. globalViewport.height -= this.viewportBorder * 2;
  82956. this._positionX -= this.viewportBorder;
  82957. this._positionY -= this.viewportBorder;
  82958. }
  82959. // Position
  82960. var centerX = globalViewport.x + globalViewport.width / 2;
  82961. var centerY = globalViewport.y + globalViewport.height / 2;
  82962. var distX = centerX - this._positionX;
  82963. var distY = centerY - this._positionY;
  82964. // Effects
  82965. engine.enableEffect(this._effect);
  82966. engine.setState(false);
  82967. engine.setDepthBuffer(false);
  82968. // VBOs
  82969. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  82970. // Flares
  82971. for (var index = 0; index < this.lensFlares.length; index++) {
  82972. var flare = this.lensFlares[index];
  82973. engine.setAlphaMode(flare.alphaMode);
  82974. var x = centerX - (distX * flare.position);
  82975. var y = centerY - (distY * flare.position);
  82976. var cw = flare.size;
  82977. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  82978. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  82979. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  82980. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  82981. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  82982. // Texture
  82983. this._effect.setTexture("textureSampler", flare.texture);
  82984. // Color
  82985. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  82986. // Draw order
  82987. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  82988. }
  82989. engine.setDepthBuffer(true);
  82990. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  82991. return true;
  82992. };
  82993. LensFlareSystem.prototype.dispose = function () {
  82994. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  82995. if (vertexBuffer) {
  82996. vertexBuffer.dispose();
  82997. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  82998. }
  82999. if (this._indexBuffer) {
  83000. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  83001. this._indexBuffer = null;
  83002. }
  83003. while (this.lensFlares.length) {
  83004. this.lensFlares[0].dispose();
  83005. }
  83006. // Remove from scene
  83007. var index = this._scene.lensFlareSystems.indexOf(this);
  83008. this._scene.lensFlareSystems.splice(index, 1);
  83009. };
  83010. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  83011. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  83012. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  83013. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  83014. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  83015. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  83016. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  83017. var parsedFlare = parsedLensFlareSystem.flares[index];
  83018. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  83019. }
  83020. return lensFlareSystem;
  83021. };
  83022. LensFlareSystem.prototype.serialize = function () {
  83023. var serializationObject = {};
  83024. serializationObject.id = this.id;
  83025. serializationObject.name = this.name;
  83026. serializationObject.emitterId = this.getEmitter().id;
  83027. serializationObject.borderLimit = this.borderLimit;
  83028. serializationObject.flares = [];
  83029. for (var index = 0; index < this.lensFlares.length; index++) {
  83030. var flare = this.lensFlares[index];
  83031. serializationObject.flares.push({
  83032. size: flare.size,
  83033. position: flare.position,
  83034. color: flare.color.asArray(),
  83035. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  83036. });
  83037. }
  83038. return serializationObject;
  83039. };
  83040. return LensFlareSystem;
  83041. }());
  83042. BABYLON.LensFlareSystem = LensFlareSystem;
  83043. })(BABYLON || (BABYLON = {}));
  83044. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  83045. var BABYLON;
  83046. (function (BABYLON) {
  83047. /**
  83048. * This is a holder class for the physics joint created by the physics plugin.
  83049. * It holds a set of functions to control the underlying joint.
  83050. */
  83051. var PhysicsJoint = /** @class */ (function () {
  83052. function PhysicsJoint(type, jointData) {
  83053. this.type = type;
  83054. this.jointData = jointData;
  83055. jointData.nativeParams = jointData.nativeParams || {};
  83056. }
  83057. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  83058. get: function () {
  83059. return this._physicsJoint;
  83060. },
  83061. set: function (newJoint) {
  83062. if (this._physicsJoint) {
  83063. //remove from the wolrd
  83064. }
  83065. this._physicsJoint = newJoint;
  83066. },
  83067. enumerable: true,
  83068. configurable: true
  83069. });
  83070. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  83071. set: function (physicsPlugin) {
  83072. this._physicsPlugin = physicsPlugin;
  83073. },
  83074. enumerable: true,
  83075. configurable: true
  83076. });
  83077. /**
  83078. * Execute a function that is physics-plugin specific.
  83079. * @param {Function} func the function that will be executed.
  83080. * It accepts two parameters: the physics world and the physics joint.
  83081. */
  83082. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  83083. func(this._physicsPlugin.world, this._physicsJoint);
  83084. };
  83085. //TODO check if the native joints are the same
  83086. //Joint Types
  83087. PhysicsJoint.DistanceJoint = 0;
  83088. PhysicsJoint.HingeJoint = 1;
  83089. PhysicsJoint.BallAndSocketJoint = 2;
  83090. PhysicsJoint.WheelJoint = 3;
  83091. PhysicsJoint.SliderJoint = 4;
  83092. //OIMO
  83093. PhysicsJoint.PrismaticJoint = 5;
  83094. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  83095. PhysicsJoint.UniversalJoint = 6;
  83096. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  83097. //Cannon
  83098. //Similar to a Ball-Joint. Different in params
  83099. PhysicsJoint.PointToPointJoint = 8;
  83100. //Cannon only at the moment
  83101. PhysicsJoint.SpringJoint = 9;
  83102. PhysicsJoint.LockJoint = 10;
  83103. return PhysicsJoint;
  83104. }());
  83105. BABYLON.PhysicsJoint = PhysicsJoint;
  83106. /**
  83107. * A class representing a physics distance joint.
  83108. */
  83109. var DistanceJoint = /** @class */ (function (_super) {
  83110. __extends(DistanceJoint, _super);
  83111. function DistanceJoint(jointData) {
  83112. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  83113. }
  83114. /**
  83115. * Update the predefined distance.
  83116. */
  83117. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  83118. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  83119. };
  83120. return DistanceJoint;
  83121. }(PhysicsJoint));
  83122. BABYLON.DistanceJoint = DistanceJoint;
  83123. var MotorEnabledJoint = /** @class */ (function (_super) {
  83124. __extends(MotorEnabledJoint, _super);
  83125. function MotorEnabledJoint(type, jointData) {
  83126. return _super.call(this, type, jointData) || this;
  83127. }
  83128. /**
  83129. * Set the motor values.
  83130. * Attention, this function is plugin specific. Engines won't react 100% the same.
  83131. * @param {number} force the force to apply
  83132. * @param {number} maxForce max force for this motor.
  83133. */
  83134. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  83135. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  83136. };
  83137. /**
  83138. * Set the motor's limits.
  83139. * Attention, this function is plugin specific. Engines won't react 100% the same.
  83140. */
  83141. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  83142. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  83143. };
  83144. return MotorEnabledJoint;
  83145. }(PhysicsJoint));
  83146. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  83147. /**
  83148. * This class represents a single hinge physics joint
  83149. */
  83150. var HingeJoint = /** @class */ (function (_super) {
  83151. __extends(HingeJoint, _super);
  83152. function HingeJoint(jointData) {
  83153. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  83154. }
  83155. /**
  83156. * Set the motor values.
  83157. * Attention, this function is plugin specific. Engines won't react 100% the same.
  83158. * @param {number} force the force to apply
  83159. * @param {number} maxForce max force for this motor.
  83160. */
  83161. HingeJoint.prototype.setMotor = function (force, maxForce) {
  83162. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  83163. };
  83164. /**
  83165. * Set the motor's limits.
  83166. * Attention, this function is plugin specific. Engines won't react 100% the same.
  83167. */
  83168. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  83169. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  83170. };
  83171. return HingeJoint;
  83172. }(MotorEnabledJoint));
  83173. BABYLON.HingeJoint = HingeJoint;
  83174. /**
  83175. * This class represents a dual hinge physics joint (same as wheel joint)
  83176. */
  83177. var Hinge2Joint = /** @class */ (function (_super) {
  83178. __extends(Hinge2Joint, _super);
  83179. function Hinge2Joint(jointData) {
  83180. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  83181. }
  83182. /**
  83183. * Set the motor values.
  83184. * Attention, this function is plugin specific. Engines won't react 100% the same.
  83185. * @param {number} force the force to apply
  83186. * @param {number} maxForce max force for this motor.
  83187. * @param {motorIndex} the motor's index, 0 or 1.
  83188. */
  83189. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  83190. if (motorIndex === void 0) { motorIndex = 0; }
  83191. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  83192. };
  83193. /**
  83194. * Set the motor limits.
  83195. * Attention, this function is plugin specific. Engines won't react 100% the same.
  83196. * @param {number} upperLimit the upper limit
  83197. * @param {number} lowerLimit lower limit
  83198. * @param {motorIndex} the motor's index, 0 or 1.
  83199. */
  83200. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  83201. if (motorIndex === void 0) { motorIndex = 0; }
  83202. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  83203. };
  83204. return Hinge2Joint;
  83205. }(MotorEnabledJoint));
  83206. BABYLON.Hinge2Joint = Hinge2Joint;
  83207. })(BABYLON || (BABYLON = {}));
  83208. //# sourceMappingURL=babylon.physicsJoint.js.map
  83209. var BABYLON;
  83210. (function (BABYLON) {
  83211. var PhysicsImpostor = /** @class */ (function () {
  83212. function PhysicsImpostor(object, type, _options, _scene) {
  83213. if (_options === void 0) { _options = { mass: 0 }; }
  83214. var _this = this;
  83215. this.object = object;
  83216. this.type = type;
  83217. this._options = _options;
  83218. this._scene = _scene;
  83219. this._bodyUpdateRequired = false;
  83220. this._onBeforePhysicsStepCallbacks = new Array();
  83221. this._onAfterPhysicsStepCallbacks = new Array();
  83222. this._onPhysicsCollideCallbacks = [];
  83223. this._deltaPosition = BABYLON.Vector3.Zero();
  83224. this._isDisposed = false;
  83225. //temp variables for parent rotation calculations
  83226. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  83227. this._tmpQuat = new BABYLON.Quaternion();
  83228. this._tmpQuat2 = new BABYLON.Quaternion();
  83229. /**
  83230. * this function is executed by the physics engine.
  83231. */
  83232. this.beforeStep = function () {
  83233. if (!_this._physicsEngine) {
  83234. return;
  83235. }
  83236. _this.object.translate(_this._deltaPosition, -1);
  83237. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  83238. _this.object.computeWorldMatrix(false);
  83239. if (_this.object.parent && _this.object.rotationQuaternion) {
  83240. _this.getParentsRotation();
  83241. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  83242. }
  83243. else {
  83244. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  83245. }
  83246. if (!_this._options.disableBidirectionalTransformation) {
  83247. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  83248. }
  83249. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  83250. func(_this);
  83251. });
  83252. };
  83253. /**
  83254. * this function is executed by the physics engine.
  83255. */
  83256. this.afterStep = function () {
  83257. if (!_this._physicsEngine) {
  83258. return;
  83259. }
  83260. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  83261. func(_this);
  83262. });
  83263. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  83264. // object has now its world rotation. needs to be converted to local.
  83265. if (_this.object.parent && _this.object.rotationQuaternion) {
  83266. _this.getParentsRotation();
  83267. _this._tmpQuat.conjugateInPlace();
  83268. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  83269. }
  83270. // take the position set and make it the absolute position of this object.
  83271. _this.object.setAbsolutePosition(_this.object.position);
  83272. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  83273. _this.object.translate(_this._deltaPosition, 1);
  83274. };
  83275. /**
  83276. * Legacy collision detection event support
  83277. */
  83278. this.onCollideEvent = null;
  83279. //event and body object due to cannon's event-based architecture.
  83280. this.onCollide = function (e) {
  83281. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  83282. return;
  83283. }
  83284. if (!_this._physicsEngine) {
  83285. return;
  83286. }
  83287. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  83288. if (otherImpostor) {
  83289. // Legacy collision detection event support
  83290. if (_this.onCollideEvent) {
  83291. _this.onCollideEvent(_this, otherImpostor);
  83292. }
  83293. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  83294. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  83295. }).forEach(function (obj) {
  83296. obj.callback(_this, otherImpostor);
  83297. });
  83298. }
  83299. };
  83300. //sanity check!
  83301. if (!this.object) {
  83302. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  83303. return;
  83304. }
  83305. //legacy support for old syntax.
  83306. if (!this._scene && object.getScene) {
  83307. this._scene = object.getScene();
  83308. }
  83309. if (!this._scene) {
  83310. return;
  83311. }
  83312. this._physicsEngine = this._scene.getPhysicsEngine();
  83313. if (!this._physicsEngine) {
  83314. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  83315. }
  83316. else {
  83317. //set the object's quaternion, if not set
  83318. if (!this.object.rotationQuaternion) {
  83319. if (this.object.rotation) {
  83320. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  83321. }
  83322. else {
  83323. this.object.rotationQuaternion = new BABYLON.Quaternion();
  83324. }
  83325. }
  83326. //default options params
  83327. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  83328. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  83329. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  83330. this._joints = [];
  83331. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  83332. if (!this.object.parent || this._options.ignoreParent) {
  83333. this._init();
  83334. }
  83335. else if (this.object.parent.physicsImpostor) {
  83336. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  83337. }
  83338. }
  83339. }
  83340. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  83341. get: function () {
  83342. return this._isDisposed;
  83343. },
  83344. enumerable: true,
  83345. configurable: true
  83346. });
  83347. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  83348. get: function () {
  83349. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  83350. },
  83351. set: function (value) {
  83352. this.setMass(value);
  83353. },
  83354. enumerable: true,
  83355. configurable: true
  83356. });
  83357. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  83358. get: function () {
  83359. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  83360. },
  83361. set: function (value) {
  83362. if (!this._physicsEngine) {
  83363. return;
  83364. }
  83365. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  83366. },
  83367. enumerable: true,
  83368. configurable: true
  83369. });
  83370. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  83371. get: function () {
  83372. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  83373. },
  83374. set: function (value) {
  83375. if (!this._physicsEngine) {
  83376. return;
  83377. }
  83378. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  83379. },
  83380. enumerable: true,
  83381. configurable: true
  83382. });
  83383. /**
  83384. * This function will completly initialize this impostor.
  83385. * It will create a new body - but only if this mesh has no parent.
  83386. * If it has, this impostor will not be used other than to define the impostor
  83387. * of the child mesh.
  83388. */
  83389. PhysicsImpostor.prototype._init = function () {
  83390. if (!this._physicsEngine) {
  83391. return;
  83392. }
  83393. this._physicsEngine.removeImpostor(this);
  83394. this.physicsBody = null;
  83395. this._parent = this._parent || this._getPhysicsParent();
  83396. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  83397. this._physicsEngine.addImpostor(this);
  83398. }
  83399. };
  83400. PhysicsImpostor.prototype._getPhysicsParent = function () {
  83401. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  83402. var parentMesh = this.object.parent;
  83403. return parentMesh.physicsImpostor;
  83404. }
  83405. return null;
  83406. };
  83407. /**
  83408. * Should a new body be generated.
  83409. */
  83410. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  83411. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  83412. };
  83413. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  83414. this.forceUpdate();
  83415. };
  83416. /**
  83417. * Force a regeneration of this or the parent's impostor's body.
  83418. * Use under cautious - This will remove all joints already implemented.
  83419. */
  83420. PhysicsImpostor.prototype.forceUpdate = function () {
  83421. this._init();
  83422. if (this.parent && !this._options.ignoreParent) {
  83423. this.parent.forceUpdate();
  83424. }
  83425. };
  83426. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  83427. /*public get mesh(): AbstractMesh {
  83428. return this._mesh;
  83429. }*/
  83430. /**
  83431. * Gets the body that holds this impostor. Either its own, or its parent.
  83432. */
  83433. get: function () {
  83434. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  83435. },
  83436. /**
  83437. * Set the physics body. Used mainly by the physics engine/plugin
  83438. */
  83439. set: function (physicsBody) {
  83440. if (this._physicsBody && this._physicsEngine) {
  83441. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  83442. }
  83443. this._physicsBody = physicsBody;
  83444. this.resetUpdateFlags();
  83445. },
  83446. enumerable: true,
  83447. configurable: true
  83448. });
  83449. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  83450. get: function () {
  83451. return !this._options.ignoreParent && this._parent ? this._parent : null;
  83452. },
  83453. set: function (value) {
  83454. this._parent = value;
  83455. },
  83456. enumerable: true,
  83457. configurable: true
  83458. });
  83459. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  83460. this._bodyUpdateRequired = false;
  83461. };
  83462. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  83463. if (this.object.getBoundingInfo) {
  83464. var q = this.object.rotationQuaternion;
  83465. //reset rotation
  83466. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  83467. //calculate the world matrix with no rotation
  83468. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  83469. var boundingInfo = this.object.getBoundingInfo();
  83470. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  83471. //bring back the rotation
  83472. this.object.rotationQuaternion = q;
  83473. //calculate the world matrix with the new rotation
  83474. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  83475. return size;
  83476. }
  83477. else {
  83478. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  83479. }
  83480. };
  83481. PhysicsImpostor.prototype.getObjectCenter = function () {
  83482. if (this.object.getBoundingInfo) {
  83483. var boundingInfo = this.object.getBoundingInfo();
  83484. return boundingInfo.boundingBox.centerWorld;
  83485. }
  83486. else {
  83487. return this.object.position;
  83488. }
  83489. };
  83490. /**
  83491. * Get a specific parametes from the options parameter.
  83492. */
  83493. PhysicsImpostor.prototype.getParam = function (paramName) {
  83494. return this._options[paramName];
  83495. };
  83496. /**
  83497. * Sets a specific parameter in the options given to the physics plugin
  83498. */
  83499. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  83500. this._options[paramName] = value;
  83501. this._bodyUpdateRequired = true;
  83502. };
  83503. /**
  83504. * Specifically change the body's mass option. Won't recreate the physics body object
  83505. */
  83506. PhysicsImpostor.prototype.setMass = function (mass) {
  83507. if (this.getParam("mass") !== mass) {
  83508. this.setParam("mass", mass);
  83509. }
  83510. if (this._physicsEngine) {
  83511. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  83512. }
  83513. };
  83514. PhysicsImpostor.prototype.getLinearVelocity = function () {
  83515. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  83516. };
  83517. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  83518. if (this._physicsEngine) {
  83519. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  83520. }
  83521. };
  83522. PhysicsImpostor.prototype.getAngularVelocity = function () {
  83523. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  83524. };
  83525. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  83526. if (this._physicsEngine) {
  83527. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  83528. }
  83529. };
  83530. /**
  83531. * Execute a function with the physics plugin native code.
  83532. * Provide a function the will have two variables - the world object and the physics body object.
  83533. */
  83534. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  83535. if (this._physicsEngine) {
  83536. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  83537. }
  83538. };
  83539. /**
  83540. * Register a function that will be executed before the physics world is stepping forward.
  83541. */
  83542. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  83543. this._onBeforePhysicsStepCallbacks.push(func);
  83544. };
  83545. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  83546. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  83547. if (index > -1) {
  83548. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  83549. }
  83550. else {
  83551. BABYLON.Tools.Warn("Function to remove was not found");
  83552. }
  83553. };
  83554. /**
  83555. * Register a function that will be executed after the physics step
  83556. */
  83557. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  83558. this._onAfterPhysicsStepCallbacks.push(func);
  83559. };
  83560. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  83561. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  83562. if (index > -1) {
  83563. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  83564. }
  83565. else {
  83566. BABYLON.Tools.Warn("Function to remove was not found");
  83567. }
  83568. };
  83569. /**
  83570. * register a function that will be executed when this impostor collides against a different body.
  83571. */
  83572. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  83573. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  83574. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  83575. };
  83576. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  83577. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  83578. var index = -1;
  83579. var found = this._onPhysicsCollideCallbacks.some(function (cbDef, idx) {
  83580. if (cbDef.callback === func && cbDef.otherImpostors.length === collidedAgainstList.length) {
  83581. // chcek the arrays match
  83582. var sameList = cbDef.otherImpostors.every(function (impostor) {
  83583. return collidedAgainstList.indexOf(impostor) > -1;
  83584. });
  83585. if (sameList) {
  83586. index = idx;
  83587. }
  83588. return sameList;
  83589. }
  83590. return false;
  83591. });
  83592. if (found) {
  83593. this._onPhysicsCollideCallbacks.splice(index, 1);
  83594. }
  83595. else {
  83596. BABYLON.Tools.Warn("Function to remove was not found");
  83597. }
  83598. };
  83599. PhysicsImpostor.prototype.getParentsRotation = function () {
  83600. var parent = this.object.parent;
  83601. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  83602. while (parent) {
  83603. if (parent.rotationQuaternion) {
  83604. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  83605. }
  83606. else {
  83607. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  83608. }
  83609. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  83610. parent = parent.parent;
  83611. }
  83612. return this._tmpQuat;
  83613. };
  83614. /**
  83615. * Apply a force
  83616. */
  83617. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  83618. if (this._physicsEngine) {
  83619. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  83620. }
  83621. return this;
  83622. };
  83623. /**
  83624. * Apply an impulse
  83625. */
  83626. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  83627. if (this._physicsEngine) {
  83628. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  83629. }
  83630. return this;
  83631. };
  83632. /**
  83633. * A help function to create a joint.
  83634. */
  83635. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  83636. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  83637. this.addJoint(otherImpostor, joint);
  83638. return this;
  83639. };
  83640. /**
  83641. * Add a joint to this impostor with a different impostor.
  83642. */
  83643. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  83644. this._joints.push({
  83645. otherImpostor: otherImpostor,
  83646. joint: joint
  83647. });
  83648. if (this._physicsEngine) {
  83649. this._physicsEngine.addJoint(this, otherImpostor, joint);
  83650. }
  83651. return this;
  83652. };
  83653. /**
  83654. * Will keep this body still, in a sleep mode.
  83655. */
  83656. PhysicsImpostor.prototype.sleep = function () {
  83657. if (this._physicsEngine) {
  83658. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  83659. }
  83660. return this;
  83661. };
  83662. /**
  83663. * Wake the body up.
  83664. */
  83665. PhysicsImpostor.prototype.wakeUp = function () {
  83666. if (this._physicsEngine) {
  83667. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  83668. }
  83669. return this;
  83670. };
  83671. PhysicsImpostor.prototype.clone = function (newObject) {
  83672. if (!newObject)
  83673. return null;
  83674. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  83675. };
  83676. PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {
  83677. var _this = this;
  83678. //no dispose if no physics engine is available.
  83679. if (!this._physicsEngine) {
  83680. return;
  83681. }
  83682. this._joints.forEach(function (j) {
  83683. if (_this._physicsEngine) {
  83684. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  83685. }
  83686. });
  83687. //dispose the physics body
  83688. this._physicsEngine.removeImpostor(this);
  83689. if (this.parent) {
  83690. this.parent.forceUpdate();
  83691. }
  83692. else {
  83693. /*this._object.getChildMeshes().forEach(function(mesh) {
  83694. if (mesh.physicsImpostor) {
  83695. if (disposeChildren) {
  83696. mesh.physicsImpostor.dispose();
  83697. mesh.physicsImpostor = null;
  83698. }
  83699. }
  83700. })*/
  83701. }
  83702. this._isDisposed = true;
  83703. };
  83704. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  83705. this._deltaPosition.copyFrom(position);
  83706. };
  83707. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  83708. if (!this._deltaRotation) {
  83709. this._deltaRotation = new BABYLON.Quaternion();
  83710. }
  83711. this._deltaRotation.copyFrom(rotation);
  83712. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  83713. };
  83714. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  83715. if (this._physicsEngine) {
  83716. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  83717. }
  83718. return this;
  83719. };
  83720. PhysicsImpostor.prototype.getRadius = function () {
  83721. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  83722. };
  83723. /**
  83724. * Sync a bone with this impostor
  83725. * @param bone The bone to sync to the impostor.
  83726. * @param boneMesh The mesh that the bone is influencing.
  83727. * @param jointPivot The pivot of the joint / bone in local space.
  83728. * @param distToJoint Optional distance from the impostor to the joint.
  83729. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  83730. */
  83731. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  83732. var tempVec = PhysicsImpostor._tmpVecs[0];
  83733. var mesh = this.object;
  83734. if (mesh.rotationQuaternion) {
  83735. if (adjustRotation) {
  83736. var tempQuat = PhysicsImpostor._tmpQuat;
  83737. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  83738. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  83739. }
  83740. else {
  83741. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  83742. }
  83743. }
  83744. tempVec.x = 0;
  83745. tempVec.y = 0;
  83746. tempVec.z = 0;
  83747. if (jointPivot) {
  83748. tempVec.x = jointPivot.x;
  83749. tempVec.y = jointPivot.y;
  83750. tempVec.z = jointPivot.z;
  83751. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  83752. if (distToJoint === undefined || distToJoint === null) {
  83753. distToJoint = jointPivot.length();
  83754. }
  83755. tempVec.x *= distToJoint;
  83756. tempVec.y *= distToJoint;
  83757. tempVec.z *= distToJoint;
  83758. }
  83759. if (bone.getParent()) {
  83760. tempVec.addInPlace(mesh.getAbsolutePosition());
  83761. bone.setAbsolutePosition(tempVec, boneMesh);
  83762. }
  83763. else {
  83764. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  83765. boneMesh.position.x -= tempVec.x;
  83766. boneMesh.position.y -= tempVec.y;
  83767. boneMesh.position.z -= tempVec.z;
  83768. }
  83769. };
  83770. /**
  83771. * Sync impostor to a bone
  83772. * @param bone The bone that the impostor will be synced to.
  83773. * @param boneMesh The mesh that the bone is influencing.
  83774. * @param jointPivot The pivot of the joint / bone in local space.
  83775. * @param distToJoint Optional distance from the impostor to the joint.
  83776. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  83777. * @param boneAxis Optional vector3 axis the bone is aligned with
  83778. */
  83779. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  83780. var mesh = this.object;
  83781. if (mesh.rotationQuaternion) {
  83782. if (adjustRotation) {
  83783. var tempQuat = PhysicsImpostor._tmpQuat;
  83784. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  83785. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  83786. }
  83787. else {
  83788. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  83789. }
  83790. }
  83791. var pos = PhysicsImpostor._tmpVecs[0];
  83792. var boneDir = PhysicsImpostor._tmpVecs[1];
  83793. if (!boneAxis) {
  83794. boneAxis = PhysicsImpostor._tmpVecs[2];
  83795. boneAxis.x = 0;
  83796. boneAxis.y = 1;
  83797. boneAxis.z = 0;
  83798. }
  83799. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  83800. bone.getAbsolutePositionToRef(boneMesh, pos);
  83801. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  83802. distToJoint = jointPivot.length();
  83803. }
  83804. if (distToJoint !== undefined && distToJoint !== null) {
  83805. pos.x += boneDir.x * distToJoint;
  83806. pos.y += boneDir.y * distToJoint;
  83807. pos.z += boneDir.z * distToJoint;
  83808. }
  83809. mesh.setAbsolutePosition(pos);
  83810. };
  83811. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  83812. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  83813. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  83814. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  83815. //Impostor types
  83816. PhysicsImpostor.NoImpostor = 0;
  83817. PhysicsImpostor.SphereImpostor = 1;
  83818. PhysicsImpostor.BoxImpostor = 2;
  83819. PhysicsImpostor.PlaneImpostor = 3;
  83820. PhysicsImpostor.MeshImpostor = 4;
  83821. PhysicsImpostor.CylinderImpostor = 7;
  83822. PhysicsImpostor.ParticleImpostor = 8;
  83823. PhysicsImpostor.HeightmapImpostor = 9;
  83824. return PhysicsImpostor;
  83825. }());
  83826. BABYLON.PhysicsImpostor = PhysicsImpostor;
  83827. })(BABYLON || (BABYLON = {}));
  83828. //# sourceMappingURL=babylon.physicsImpostor.js.map
  83829. var BABYLON;
  83830. (function (BABYLON) {
  83831. var PhysicsEngine = /** @class */ (function () {
  83832. function PhysicsEngine(gravity, _physicsPlugin) {
  83833. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  83834. this._physicsPlugin = _physicsPlugin;
  83835. //new methods and parameters
  83836. this._impostors = [];
  83837. this._joints = [];
  83838. if (!this._physicsPlugin.isSupported()) {
  83839. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  83840. + "Please make sure it is included.");
  83841. }
  83842. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  83843. this.setGravity(gravity);
  83844. this.setTimeStep();
  83845. }
  83846. PhysicsEngine.prototype.setGravity = function (gravity) {
  83847. this.gravity = gravity;
  83848. this._physicsPlugin.setGravity(this.gravity);
  83849. };
  83850. /**
  83851. * Set the time step of the physics engine.
  83852. * default is 1/60.
  83853. * To slow it down, enter 1/600 for example.
  83854. * To speed it up, 1/30
  83855. * @param {number} newTimeStep the new timestep to apply to this world.
  83856. */
  83857. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  83858. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  83859. this._physicsPlugin.setTimeStep(newTimeStep);
  83860. };
  83861. /**
  83862. * Get the time step of the physics engine.
  83863. */
  83864. PhysicsEngine.prototype.getTimeStep = function () {
  83865. return this._physicsPlugin.getTimeStep();
  83866. };
  83867. PhysicsEngine.prototype.dispose = function () {
  83868. this._impostors.forEach(function (impostor) {
  83869. impostor.dispose();
  83870. });
  83871. this._physicsPlugin.dispose();
  83872. };
  83873. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  83874. return this._physicsPlugin.name;
  83875. };
  83876. /**
  83877. * Adding a new impostor for the impostor tracking.
  83878. * This will be done by the impostor itself.
  83879. * @param {PhysicsImpostor} impostor the impostor to add
  83880. */
  83881. PhysicsEngine.prototype.addImpostor = function (impostor) {
  83882. impostor.uniqueId = this._impostors.push(impostor);
  83883. //if no parent, generate the body
  83884. if (!impostor.parent) {
  83885. this._physicsPlugin.generatePhysicsBody(impostor);
  83886. }
  83887. };
  83888. /**
  83889. * Remove an impostor from the engine.
  83890. * This impostor and its mesh will not longer be updated by the physics engine.
  83891. * @param {PhysicsImpostor} impostor the impostor to remove
  83892. */
  83893. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  83894. var index = this._impostors.indexOf(impostor);
  83895. if (index > -1) {
  83896. var removed = this._impostors.splice(index, 1);
  83897. //Is it needed?
  83898. if (removed.length) {
  83899. //this will also remove it from the world.
  83900. removed[0].physicsBody = null;
  83901. }
  83902. }
  83903. };
  83904. /**
  83905. * Add a joint to the physics engine
  83906. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  83907. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  83908. * @param {PhysicsJoint} the joint that will connect both impostors.
  83909. */
  83910. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  83911. var impostorJoint = {
  83912. mainImpostor: mainImpostor,
  83913. connectedImpostor: connectedImpostor,
  83914. joint: joint
  83915. };
  83916. joint.physicsPlugin = this._physicsPlugin;
  83917. this._joints.push(impostorJoint);
  83918. this._physicsPlugin.generateJoint(impostorJoint);
  83919. };
  83920. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  83921. var matchingJoints = this._joints.filter(function (impostorJoint) {
  83922. return (impostorJoint.connectedImpostor === connectedImpostor
  83923. && impostorJoint.joint === joint
  83924. && impostorJoint.mainImpostor === mainImpostor);
  83925. });
  83926. if (matchingJoints.length) {
  83927. this._physicsPlugin.removeJoint(matchingJoints[0]);
  83928. //TODO remove it from the list as well
  83929. }
  83930. };
  83931. /**
  83932. * Called by the scene. no need to call it.
  83933. */
  83934. PhysicsEngine.prototype._step = function (delta) {
  83935. var _this = this;
  83936. //check if any mesh has no body / requires an update
  83937. this._impostors.forEach(function (impostor) {
  83938. if (impostor.isBodyInitRequired()) {
  83939. _this._physicsPlugin.generatePhysicsBody(impostor);
  83940. }
  83941. });
  83942. if (delta > 0.1) {
  83943. delta = 0.1;
  83944. }
  83945. else if (delta <= 0) {
  83946. delta = 1.0 / 60.0;
  83947. }
  83948. this._physicsPlugin.executeStep(delta, this._impostors);
  83949. };
  83950. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  83951. return this._physicsPlugin;
  83952. };
  83953. PhysicsEngine.prototype.getImpostors = function () {
  83954. return this._impostors;
  83955. };
  83956. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  83957. for (var i = 0; i < this._impostors.length; ++i) {
  83958. if (this._impostors[i].object === object) {
  83959. return this._impostors[i];
  83960. }
  83961. }
  83962. return null;
  83963. };
  83964. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  83965. for (var i = 0; i < this._impostors.length; ++i) {
  83966. if (this._impostors[i].physicsBody === body) {
  83967. return this._impostors[i];
  83968. }
  83969. }
  83970. return null;
  83971. };
  83972. // Statics
  83973. PhysicsEngine.Epsilon = 0.001;
  83974. return PhysicsEngine;
  83975. }());
  83976. BABYLON.PhysicsEngine = PhysicsEngine;
  83977. })(BABYLON || (BABYLON = {}));
  83978. //# sourceMappingURL=babylon.physicsEngine.js.map
  83979. var BABYLON;
  83980. (function (BABYLON) {
  83981. var PhysicsHelper = /** @class */ (function () {
  83982. function PhysicsHelper(scene) {
  83983. this._scene = scene;
  83984. this._physicsEngine = this._scene.getPhysicsEngine();
  83985. if (!this._physicsEngine) {
  83986. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  83987. }
  83988. }
  83989. /**
  83990. * @param {Vector3} origin the origin of the explosion
  83991. * @param {number} radius the explosion radius
  83992. * @param {number} strength the explosion strength
  83993. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  83994. */
  83995. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  83996. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  83997. if (!this._physicsEngine) {
  83998. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  83999. return null;
  84000. }
  84001. var impostors = this._physicsEngine.getImpostors();
  84002. if (impostors.length === 0) {
  84003. return null;
  84004. }
  84005. var event = new PhysicsRadialExplosionEvent(this._scene);
  84006. impostors.forEach(function (impostor) {
  84007. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  84008. if (!impostorForceAndContactPoint) {
  84009. return;
  84010. }
  84011. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  84012. });
  84013. event.dispose(false);
  84014. return event;
  84015. };
  84016. /**
  84017. * @param {Vector3} origin the origin of the explosion
  84018. * @param {number} radius the explosion radius
  84019. * @param {number} strength the explosion strength
  84020. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  84021. */
  84022. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  84023. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  84024. if (!this._physicsEngine) {
  84025. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  84026. return null;
  84027. }
  84028. var impostors = this._physicsEngine.getImpostors();
  84029. if (impostors.length === 0) {
  84030. return null;
  84031. }
  84032. var event = new PhysicsRadialExplosionEvent(this._scene);
  84033. impostors.forEach(function (impostor) {
  84034. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  84035. if (!impostorForceAndContactPoint) {
  84036. return;
  84037. }
  84038. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  84039. });
  84040. event.dispose(false);
  84041. return event;
  84042. };
  84043. /**
  84044. * @param {Vector3} origin the origin of the explosion
  84045. * @param {number} radius the explosion radius
  84046. * @param {number} strength the explosion strength
  84047. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  84048. */
  84049. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  84050. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  84051. if (!this._physicsEngine) {
  84052. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  84053. return null;
  84054. }
  84055. var impostors = this._physicsEngine.getImpostors();
  84056. if (impostors.length === 0) {
  84057. return null;
  84058. }
  84059. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  84060. event.dispose(false);
  84061. return event;
  84062. };
  84063. /**
  84064. * @param {Vector3} origin the origin of the updraft
  84065. * @param {number} radius the radius of the updraft
  84066. * @param {number} strength the strength of the updraft
  84067. * @param {number} height the height of the updraft
  84068. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  84069. */
  84070. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  84071. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  84072. if (!this._physicsEngine) {
  84073. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  84074. return null;
  84075. }
  84076. if (this._physicsEngine.getImpostors().length === 0) {
  84077. return null;
  84078. }
  84079. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  84080. event.dispose(false);
  84081. return event;
  84082. };
  84083. /**
  84084. * @param {Vector3} origin the of the vortex
  84085. * @param {number} radius the radius of the vortex
  84086. * @param {number} strength the strength of the vortex
  84087. * @param {number} height the height of the vortex
  84088. */
  84089. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  84090. if (!this._physicsEngine) {
  84091. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  84092. return null;
  84093. }
  84094. if (this._physicsEngine.getImpostors().length === 0) {
  84095. return null;
  84096. }
  84097. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  84098. event.dispose(false);
  84099. return event;
  84100. };
  84101. return PhysicsHelper;
  84102. }());
  84103. BABYLON.PhysicsHelper = PhysicsHelper;
  84104. /***** Radial explosion *****/
  84105. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  84106. function PhysicsRadialExplosionEvent(scene) {
  84107. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  84108. this._rays = [];
  84109. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  84110. this._scene = scene;
  84111. }
  84112. /**
  84113. * Returns the data related to the radial explosion event (sphere & rays).
  84114. * @returns {PhysicsRadialExplosionEventData}
  84115. */
  84116. PhysicsRadialExplosionEvent.prototype.getData = function () {
  84117. this._dataFetched = true;
  84118. return {
  84119. sphere: this._sphere,
  84120. rays: this._rays,
  84121. };
  84122. };
  84123. /**
  84124. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  84125. * @param impostor
  84126. * @param {Vector3} origin the origin of the explosion
  84127. * @param {number} radius the explosion radius
  84128. * @param {number} strength the explosion strength
  84129. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  84130. * @returns {Nullable<PhysicsForceAndContactPoint>}
  84131. */
  84132. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  84133. if (impostor.mass === 0) {
  84134. return null;
  84135. }
  84136. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  84137. return null;
  84138. }
  84139. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  84140. return null;
  84141. }
  84142. var impostorObjectCenter = impostor.getObjectCenter();
  84143. var direction = impostorObjectCenter.subtract(origin);
  84144. var ray = new BABYLON.Ray(origin, direction, radius);
  84145. this._rays.push(ray);
  84146. var hit = ray.intersectsMesh(impostor.object);
  84147. var contactPoint = hit.pickedPoint;
  84148. if (!contactPoint) {
  84149. return null;
  84150. }
  84151. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  84152. if (distanceFromOrigin > radius) {
  84153. return null;
  84154. }
  84155. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  84156. ? strength
  84157. : strength * (1 - (distanceFromOrigin / radius));
  84158. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  84159. return { force: force, contactPoint: contactPoint };
  84160. };
  84161. /**
  84162. * Disposes the sphere.
  84163. * @param {bolean} force
  84164. */
  84165. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  84166. var _this = this;
  84167. if (force === void 0) { force = true; }
  84168. if (force) {
  84169. this._sphere.dispose();
  84170. }
  84171. else {
  84172. setTimeout(function () {
  84173. if (!_this._dataFetched) {
  84174. _this._sphere.dispose();
  84175. }
  84176. }, 0);
  84177. }
  84178. };
  84179. /*** Helpers ***/
  84180. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  84181. if (!this._sphere) {
  84182. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  84183. this._sphere.isVisible = false;
  84184. }
  84185. };
  84186. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  84187. var impostorObject = impostor.object;
  84188. this._prepareSphere();
  84189. this._sphere.position = origin;
  84190. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  84191. this._sphere._updateBoundingInfo();
  84192. this._sphere.computeWorldMatrix(true);
  84193. return this._sphere.intersectsMesh(impostorObject, true);
  84194. };
  84195. return PhysicsRadialExplosionEvent;
  84196. }());
  84197. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  84198. /***** Gravitational Field *****/
  84199. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  84200. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  84201. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  84202. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  84203. this._physicsHelper = physicsHelper;
  84204. this._scene = scene;
  84205. this._origin = origin;
  84206. this._radius = radius;
  84207. this._strength = strength;
  84208. this._falloff = falloff;
  84209. this._tickCallback = this._tick.bind(this);
  84210. }
  84211. /**
  84212. * Returns the data related to the gravitational field event (sphere).
  84213. * @returns {PhysicsGravitationalFieldEventData}
  84214. */
  84215. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  84216. this._dataFetched = true;
  84217. return {
  84218. sphere: this._sphere,
  84219. };
  84220. };
  84221. /**
  84222. * Enables the gravitational field.
  84223. */
  84224. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  84225. this._tickCallback.call(this);
  84226. this._scene.registerBeforeRender(this._tickCallback);
  84227. };
  84228. /**
  84229. * Disables the gravitational field.
  84230. */
  84231. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  84232. this._scene.unregisterBeforeRender(this._tickCallback);
  84233. };
  84234. /**
  84235. * Disposes the sphere.
  84236. * @param {bolean} force
  84237. */
  84238. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  84239. var _this = this;
  84240. if (force === void 0) { force = true; }
  84241. if (force) {
  84242. this._sphere.dispose();
  84243. }
  84244. else {
  84245. setTimeout(function () {
  84246. if (!_this._dataFetched) {
  84247. _this._sphere.dispose();
  84248. }
  84249. }, 0);
  84250. }
  84251. };
  84252. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  84253. // Since the params won't change, we fetch the event only once
  84254. if (this._sphere) {
  84255. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  84256. }
  84257. else {
  84258. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  84259. if (radialExplosionEvent) {
  84260. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  84261. }
  84262. }
  84263. };
  84264. return PhysicsGravitationalFieldEvent;
  84265. }());
  84266. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  84267. /***** Updraft *****/
  84268. var PhysicsUpdraftEvent = /** @class */ (function () {
  84269. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  84270. this._scene = _scene;
  84271. this._origin = _origin;
  84272. this._radius = _radius;
  84273. this._strength = _strength;
  84274. this._height = _height;
  84275. this._updraftMode = _updraftMode;
  84276. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  84277. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  84278. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  84279. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  84280. this._physicsEngine = this._scene.getPhysicsEngine();
  84281. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  84282. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  84283. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  84284. this._originDirection = this._origin.subtract(this._originTop).normalize();
  84285. }
  84286. this._tickCallback = this._tick.bind(this);
  84287. }
  84288. /**
  84289. * Returns the data related to the updraft event (cylinder).
  84290. * @returns {PhysicsUpdraftEventData}
  84291. */
  84292. PhysicsUpdraftEvent.prototype.getData = function () {
  84293. this._dataFetched = true;
  84294. return {
  84295. cylinder: this._cylinder,
  84296. };
  84297. };
  84298. /**
  84299. * Enables the updraft.
  84300. */
  84301. PhysicsUpdraftEvent.prototype.enable = function () {
  84302. this._tickCallback.call(this);
  84303. this._scene.registerBeforeRender(this._tickCallback);
  84304. };
  84305. /**
  84306. * Disables the cortex.
  84307. */
  84308. PhysicsUpdraftEvent.prototype.disable = function () {
  84309. this._scene.unregisterBeforeRender(this._tickCallback);
  84310. };
  84311. /**
  84312. * Disposes the sphere.
  84313. * @param {bolean} force
  84314. */
  84315. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  84316. var _this = this;
  84317. if (force === void 0) { force = true; }
  84318. if (force) {
  84319. this._cylinder.dispose();
  84320. }
  84321. else {
  84322. setTimeout(function () {
  84323. if (!_this._dataFetched) {
  84324. _this._cylinder.dispose();
  84325. }
  84326. }, 0);
  84327. }
  84328. };
  84329. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  84330. if (impostor.mass === 0) {
  84331. return null;
  84332. }
  84333. if (!this._intersectsWithCylinder(impostor)) {
  84334. return null;
  84335. }
  84336. var impostorObjectCenter = impostor.getObjectCenter();
  84337. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  84338. var direction = this._originDirection;
  84339. }
  84340. else {
  84341. var direction = impostorObjectCenter.subtract(this._originTop);
  84342. }
  84343. var multiplier = this._strength * -1;
  84344. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  84345. return { force: force, contactPoint: impostorObjectCenter };
  84346. };
  84347. PhysicsUpdraftEvent.prototype._tick = function () {
  84348. var _this = this;
  84349. this._physicsEngine.getImpostors().forEach(function (impostor) {
  84350. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  84351. if (!impostorForceAndContactPoint) {
  84352. return;
  84353. }
  84354. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  84355. });
  84356. };
  84357. /*** Helpers ***/
  84358. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  84359. if (!this._cylinder) {
  84360. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  84361. height: this._height,
  84362. diameter: this._radius * 2,
  84363. }, this._scene);
  84364. this._cylinder.isVisible = false;
  84365. }
  84366. };
  84367. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  84368. var impostorObject = impostor.object;
  84369. this._prepareCylinder();
  84370. this._cylinder.position = this._cylinderPosition;
  84371. return this._cylinder.intersectsMesh(impostorObject, true);
  84372. };
  84373. return PhysicsUpdraftEvent;
  84374. }());
  84375. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  84376. /***** Vortex *****/
  84377. var PhysicsVortexEvent = /** @class */ (function () {
  84378. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  84379. this._scene = _scene;
  84380. this._origin = _origin;
  84381. this._radius = _radius;
  84382. this._strength = _strength;
  84383. this._height = _height;
  84384. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  84385. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  84386. this._updraftMultiplier = 0.02;
  84387. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  84388. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  84389. this._physicsEngine = this._scene.getPhysicsEngine();
  84390. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  84391. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  84392. this._tickCallback = this._tick.bind(this);
  84393. }
  84394. /**
  84395. * Returns the data related to the vortex event (cylinder).
  84396. * @returns {PhysicsVortexEventData}
  84397. */
  84398. PhysicsVortexEvent.prototype.getData = function () {
  84399. this._dataFetched = true;
  84400. return {
  84401. cylinder: this._cylinder,
  84402. };
  84403. };
  84404. /**
  84405. * Enables the vortex.
  84406. */
  84407. PhysicsVortexEvent.prototype.enable = function () {
  84408. this._tickCallback.call(this);
  84409. this._scene.registerBeforeRender(this._tickCallback);
  84410. };
  84411. /**
  84412. * Disables the cortex.
  84413. */
  84414. PhysicsVortexEvent.prototype.disable = function () {
  84415. this._scene.unregisterBeforeRender(this._tickCallback);
  84416. };
  84417. /**
  84418. * Disposes the sphere.
  84419. * @param {bolean} force
  84420. */
  84421. PhysicsVortexEvent.prototype.dispose = function (force) {
  84422. var _this = this;
  84423. if (force === void 0) { force = true; }
  84424. if (force) {
  84425. this._cylinder.dispose();
  84426. }
  84427. else {
  84428. setTimeout(function () {
  84429. if (!_this._dataFetched) {
  84430. _this._cylinder.dispose();
  84431. }
  84432. }, 0);
  84433. }
  84434. };
  84435. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  84436. if (impostor.mass === 0) {
  84437. return null;
  84438. }
  84439. if (!this._intersectsWithCylinder(impostor)) {
  84440. return null;
  84441. }
  84442. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  84443. return null;
  84444. }
  84445. var impostorObjectCenter = impostor.getObjectCenter();
  84446. 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)
  84447. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  84448. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  84449. var hit = ray.intersectsMesh(impostor.object);
  84450. var contactPoint = hit.pickedPoint;
  84451. if (!contactPoint) {
  84452. return null;
  84453. }
  84454. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  84455. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  84456. var directionToOrigin = contactPoint.normalize();
  84457. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  84458. directionToOrigin = directionToOrigin.negate();
  84459. }
  84460. // TODO: find a more physically based solution
  84461. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  84462. var forceX = directionToOrigin.x * this._strength / 8;
  84463. var forceY = directionToOrigin.y * this._updraftMultiplier;
  84464. var forceZ = directionToOrigin.z * this._strength / 8;
  84465. }
  84466. else {
  84467. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  84468. var forceY = this._originTop.y * this._updraftMultiplier;
  84469. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  84470. }
  84471. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  84472. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  84473. return { force: force, contactPoint: impostorObjectCenter };
  84474. };
  84475. PhysicsVortexEvent.prototype._tick = function () {
  84476. var _this = this;
  84477. this._physicsEngine.getImpostors().forEach(function (impostor) {
  84478. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  84479. if (!impostorForceAndContactPoint) {
  84480. return;
  84481. }
  84482. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  84483. });
  84484. };
  84485. /*** Helpers ***/
  84486. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  84487. if (!this._cylinder) {
  84488. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  84489. height: this._height,
  84490. diameter: this._radius * 2,
  84491. }, this._scene);
  84492. this._cylinder.isVisible = false;
  84493. }
  84494. };
  84495. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  84496. var impostorObject = impostor.object;
  84497. this._prepareCylinder();
  84498. this._cylinder.position = this._cylinderPosition;
  84499. return this._cylinder.intersectsMesh(impostorObject, true);
  84500. };
  84501. return PhysicsVortexEvent;
  84502. }());
  84503. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  84504. /***** Enums *****/
  84505. /**
  84506. * The strenght of the force in correspondence to the distance of the affected object
  84507. */
  84508. var PhysicsRadialImpulseFalloff;
  84509. (function (PhysicsRadialImpulseFalloff) {
  84510. /** Defines that impulse is constant in strength across it's whole radius */
  84511. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  84512. /** DEfines that impulse gets weaker if it's further from the origin */
  84513. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear";
  84514. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  84515. /**
  84516. * The strenght of the force in correspondence to the distance of the affected object
  84517. */
  84518. var PhysicsUpdraftMode;
  84519. (function (PhysicsUpdraftMode) {
  84520. /** Defines that the upstream forces will pull towards the top center of the cylinder */
  84521. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  84522. /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */
  84523. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular";
  84524. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  84525. })(BABYLON || (BABYLON = {}));
  84526. //# sourceMappingURL=babylon.physicsHelper.js.map
  84527. var BABYLON;
  84528. (function (BABYLON) {
  84529. var CannonJSPlugin = /** @class */ (function () {
  84530. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  84531. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  84532. if (iterations === void 0) { iterations = 10; }
  84533. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  84534. this.name = "CannonJSPlugin";
  84535. this._physicsMaterials = new Array();
  84536. this._fixedTimeStep = 1 / 60;
  84537. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  84538. this.BJSCANNON = CANNON;
  84539. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  84540. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  84541. this._tmpPosition = BABYLON.Vector3.Zero();
  84542. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  84543. this._tmpUnityRotation = new BABYLON.Quaternion();
  84544. if (!this.isSupported()) {
  84545. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  84546. return;
  84547. }
  84548. this._extendNamespace();
  84549. this.world = new this.BJSCANNON.World();
  84550. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  84551. this.world.solver.iterations = iterations;
  84552. }
  84553. CannonJSPlugin.prototype.setGravity = function (gravity) {
  84554. this.world.gravity.copy(gravity);
  84555. };
  84556. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  84557. this._fixedTimeStep = timeStep;
  84558. };
  84559. CannonJSPlugin.prototype.getTimeStep = function () {
  84560. return this._fixedTimeStep;
  84561. };
  84562. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  84563. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  84564. };
  84565. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  84566. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  84567. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  84568. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  84569. };
  84570. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  84571. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  84572. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  84573. impostor.physicsBody.applyForce(impulse, worldPoint);
  84574. };
  84575. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  84576. //parent-child relationship. Does this impostor has a parent impostor?
  84577. if (impostor.parent) {
  84578. if (impostor.physicsBody) {
  84579. this.removePhysicsBody(impostor);
  84580. //TODO is that needed?
  84581. impostor.forceUpdate();
  84582. }
  84583. return;
  84584. }
  84585. //should a new body be created for this impostor?
  84586. if (impostor.isBodyInitRequired()) {
  84587. var shape = this._createShape(impostor);
  84588. //unregister events, if body is being changed
  84589. var oldBody = impostor.physicsBody;
  84590. if (oldBody) {
  84591. this.removePhysicsBody(impostor);
  84592. }
  84593. //create the body and material
  84594. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  84595. var bodyCreationObject = {
  84596. mass: impostor.getParam("mass"),
  84597. material: material
  84598. };
  84599. // A simple extend, in case native options were used.
  84600. var nativeOptions = impostor.getParam("nativeOptions");
  84601. for (var key in nativeOptions) {
  84602. if (nativeOptions.hasOwnProperty(key)) {
  84603. bodyCreationObject[key] = nativeOptions[key];
  84604. }
  84605. }
  84606. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  84607. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  84608. this.world.addEventListener("preStep", impostor.beforeStep);
  84609. this.world.addEventListener("postStep", impostor.afterStep);
  84610. impostor.physicsBody.addShape(shape);
  84611. this.world.add(impostor.physicsBody);
  84612. //try to keep the body moving in the right direction by taking old properties.
  84613. //Should be tested!
  84614. if (oldBody) {
  84615. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  84616. impostor.physicsBody[param].copy(oldBody[param]);
  84617. });
  84618. }
  84619. this._processChildMeshes(impostor);
  84620. }
  84621. //now update the body's transformation
  84622. this._updatePhysicsBodyTransformation(impostor);
  84623. };
  84624. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  84625. var _this = this;
  84626. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  84627. var currentRotation = mainImpostor.object.rotationQuaternion;
  84628. if (meshChildren.length) {
  84629. var processMesh = function (localPosition, mesh) {
  84630. if (!currentRotation || !mesh.rotationQuaternion) {
  84631. return;
  84632. }
  84633. var childImpostor = mesh.getPhysicsImpostor();
  84634. if (childImpostor) {
  84635. var parent = childImpostor.parent;
  84636. if (parent !== mainImpostor) {
  84637. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  84638. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  84639. if (childImpostor.physicsBody) {
  84640. _this.removePhysicsBody(childImpostor);
  84641. childImpostor.physicsBody = null;
  84642. }
  84643. childImpostor.parent = mainImpostor;
  84644. childImpostor.resetUpdateFlags();
  84645. 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));
  84646. //Add the mass of the children.
  84647. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  84648. }
  84649. }
  84650. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  84651. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  84652. };
  84653. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  84654. }
  84655. };
  84656. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  84657. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  84658. this.world.removeEventListener("preStep", impostor.beforeStep);
  84659. this.world.removeEventListener("postStep", impostor.afterStep);
  84660. this.world.remove(impostor.physicsBody);
  84661. };
  84662. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  84663. var mainBody = impostorJoint.mainImpostor.physicsBody;
  84664. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  84665. if (!mainBody || !connectedBody) {
  84666. return;
  84667. }
  84668. var constraint;
  84669. var jointData = impostorJoint.joint.jointData;
  84670. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  84671. var constraintData = {
  84672. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  84673. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  84674. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  84675. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  84676. maxForce: jointData.nativeParams.maxForce,
  84677. collideConnected: !!jointData.collision
  84678. };
  84679. switch (impostorJoint.joint.type) {
  84680. case BABYLON.PhysicsJoint.HingeJoint:
  84681. case BABYLON.PhysicsJoint.Hinge2Joint:
  84682. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  84683. break;
  84684. case BABYLON.PhysicsJoint.DistanceJoint:
  84685. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  84686. break;
  84687. case BABYLON.PhysicsJoint.SpringJoint:
  84688. var springData = jointData;
  84689. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  84690. restLength: springData.length,
  84691. stiffness: springData.stiffness,
  84692. damping: springData.damping,
  84693. localAnchorA: constraintData.pivotA,
  84694. localAnchorB: constraintData.pivotB
  84695. });
  84696. break;
  84697. case BABYLON.PhysicsJoint.LockJoint:
  84698. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  84699. break;
  84700. case BABYLON.PhysicsJoint.PointToPointJoint:
  84701. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  84702. default:
  84703. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  84704. break;
  84705. }
  84706. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  84707. constraint.collideConnected = !!jointData.collision;
  84708. impostorJoint.joint.physicsJoint = constraint;
  84709. //don't add spring as constraint, as it is not one.
  84710. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  84711. this.world.addConstraint(constraint);
  84712. }
  84713. else {
  84714. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  84715. constraint.applyForce();
  84716. });
  84717. }
  84718. };
  84719. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  84720. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  84721. };
  84722. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  84723. var index;
  84724. var mat;
  84725. for (index = 0; index < this._physicsMaterials.length; index++) {
  84726. mat = this._physicsMaterials[index];
  84727. if (mat.friction === friction && mat.restitution === restitution) {
  84728. return mat;
  84729. }
  84730. }
  84731. var currentMat = new this.BJSCANNON.Material(name);
  84732. currentMat.friction = friction;
  84733. currentMat.restitution = restitution;
  84734. this._physicsMaterials.push(currentMat);
  84735. return currentMat;
  84736. };
  84737. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  84738. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  84739. };
  84740. CannonJSPlugin.prototype._createShape = function (impostor) {
  84741. var object = impostor.object;
  84742. var returnValue;
  84743. var extendSize = impostor.getObjectExtendSize();
  84744. switch (impostor.type) {
  84745. case BABYLON.PhysicsImpostor.SphereImpostor:
  84746. var radiusX = extendSize.x;
  84747. var radiusY = extendSize.y;
  84748. var radiusZ = extendSize.z;
  84749. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  84750. break;
  84751. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  84752. case BABYLON.PhysicsImpostor.CylinderImpostor:
  84753. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  84754. break;
  84755. case BABYLON.PhysicsImpostor.BoxImpostor:
  84756. var box = extendSize.scale(0.5);
  84757. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  84758. break;
  84759. case BABYLON.PhysicsImpostor.PlaneImpostor:
  84760. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  84761. returnValue = new this.BJSCANNON.Plane();
  84762. break;
  84763. case BABYLON.PhysicsImpostor.MeshImpostor:
  84764. // should transform the vertex data to world coordinates!!
  84765. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  84766. var rawFaces = object.getIndices ? object.getIndices() : [];
  84767. if (!rawVerts)
  84768. return;
  84769. // get only scale! so the object could transform correctly.
  84770. var oldPosition = object.position.clone();
  84771. var oldRotation = object.rotation && object.rotation.clone();
  84772. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  84773. object.position.copyFromFloats(0, 0, 0);
  84774. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  84775. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  84776. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  84777. var transform = object.computeWorldMatrix(true);
  84778. // convert rawVerts to object space
  84779. var temp = new Array();
  84780. var index;
  84781. for (index = 0; index < rawVerts.length; index += 3) {
  84782. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  84783. }
  84784. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  84785. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  84786. //now set back the transformation!
  84787. object.position.copyFrom(oldPosition);
  84788. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  84789. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  84790. break;
  84791. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  84792. var oldPosition2 = object.position.clone();
  84793. var oldRotation2 = object.rotation && object.rotation.clone();
  84794. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  84795. object.position.copyFromFloats(0, 0, 0);
  84796. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  84797. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  84798. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  84799. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  84800. returnValue = this._createHeightmap(object);
  84801. object.position.copyFrom(oldPosition2);
  84802. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  84803. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  84804. object.computeWorldMatrix(true);
  84805. break;
  84806. case BABYLON.PhysicsImpostor.ParticleImpostor:
  84807. returnValue = new this.BJSCANNON.Particle();
  84808. break;
  84809. }
  84810. return returnValue;
  84811. };
  84812. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  84813. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  84814. var transform = object.computeWorldMatrix(true);
  84815. // convert rawVerts to object space
  84816. var temp = new Array();
  84817. var index;
  84818. for (index = 0; index < pos.length; index += 3) {
  84819. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  84820. }
  84821. pos = temp;
  84822. var matrix = new Array();
  84823. //For now pointDepth will not be used and will be automatically calculated.
  84824. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  84825. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  84826. var boundingInfo = object.getBoundingInfo();
  84827. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  84828. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  84829. var elementSize = dim * 2 / arraySize;
  84830. for (var i = 0; i < pos.length; i = i + 3) {
  84831. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  84832. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  84833. var y = -pos[i + 2] + minY;
  84834. if (!matrix[x]) {
  84835. matrix[x] = [];
  84836. }
  84837. if (!matrix[x][z]) {
  84838. matrix[x][z] = y;
  84839. }
  84840. matrix[x][z] = Math.max(y, matrix[x][z]);
  84841. }
  84842. for (var x = 0; x <= arraySize; ++x) {
  84843. if (!matrix[x]) {
  84844. var loc = 1;
  84845. while (!matrix[(x + loc) % arraySize]) {
  84846. loc++;
  84847. }
  84848. matrix[x] = matrix[(x + loc) % arraySize].slice();
  84849. //console.log("missing x", x);
  84850. }
  84851. for (var z = 0; z <= arraySize; ++z) {
  84852. if (!matrix[x][z]) {
  84853. var loc = 1;
  84854. var newValue;
  84855. while (newValue === undefined) {
  84856. newValue = matrix[x][(z + loc++) % arraySize];
  84857. }
  84858. matrix[x][z] = newValue;
  84859. }
  84860. }
  84861. }
  84862. var shape = new this.BJSCANNON.Heightfield(matrix, {
  84863. elementSize: elementSize
  84864. });
  84865. //For future reference, needed for body transformation
  84866. shape.minY = minY;
  84867. return shape;
  84868. };
  84869. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  84870. var object = impostor.object;
  84871. //make sure it is updated...
  84872. object.computeWorldMatrix && object.computeWorldMatrix(true);
  84873. // The delta between the mesh position and the mesh bounding box center
  84874. var bInfo = object.getBoundingInfo();
  84875. if (!bInfo)
  84876. return;
  84877. var center = impostor.getObjectCenter();
  84878. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  84879. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  84880. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  84881. this._tmpPosition.copyFrom(center);
  84882. var quaternion = object.rotationQuaternion;
  84883. if (!quaternion) {
  84884. return;
  84885. }
  84886. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  84887. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  84888. //-90 DEG in X, precalculated
  84889. quaternion = quaternion.multiply(this._minus90X);
  84890. //Invert! (Precalculated, 90 deg in X)
  84891. //No need to clone. this will never change.
  84892. impostor.setDeltaRotation(this._plus90X);
  84893. }
  84894. //If it is a heightfield, if should be centered.
  84895. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  84896. var mesh = object;
  84897. var boundingInfo = mesh.getBoundingInfo();
  84898. //calculate the correct body position:
  84899. var rotationQuaternion = mesh.rotationQuaternion;
  84900. mesh.rotationQuaternion = this._tmpUnityRotation;
  84901. mesh.computeWorldMatrix(true);
  84902. //get original center with no rotation
  84903. var c = center.clone();
  84904. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  84905. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  84906. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  84907. mesh.setPreTransformMatrix(p);
  84908. mesh.computeWorldMatrix(true);
  84909. //calculate the translation
  84910. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  84911. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  84912. //add it inverted to the delta
  84913. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  84914. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  84915. //rotation is back
  84916. mesh.rotationQuaternion = rotationQuaternion;
  84917. mesh.setPreTransformMatrix(oldPivot);
  84918. mesh.computeWorldMatrix(true);
  84919. }
  84920. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  84921. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  84922. //this._tmpPosition.copyFrom(object.position);
  84923. }
  84924. impostor.setDeltaPosition(this._tmpDeltaPosition);
  84925. //Now update the impostor object
  84926. impostor.physicsBody.position.copy(this._tmpPosition);
  84927. impostor.physicsBody.quaternion.copy(quaternion);
  84928. };
  84929. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  84930. impostor.object.position.copyFrom(impostor.physicsBody.position);
  84931. if (impostor.object.rotationQuaternion) {
  84932. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  84933. }
  84934. };
  84935. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  84936. impostor.physicsBody.position.copy(newPosition);
  84937. impostor.physicsBody.quaternion.copy(newRotation);
  84938. };
  84939. CannonJSPlugin.prototype.isSupported = function () {
  84940. return this.BJSCANNON !== undefined;
  84941. };
  84942. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  84943. impostor.physicsBody.velocity.copy(velocity);
  84944. };
  84945. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  84946. impostor.physicsBody.angularVelocity.copy(velocity);
  84947. };
  84948. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  84949. var v = impostor.physicsBody.velocity;
  84950. if (!v) {
  84951. return null;
  84952. }
  84953. return new BABYLON.Vector3(v.x, v.y, v.z);
  84954. };
  84955. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  84956. var v = impostor.physicsBody.angularVelocity;
  84957. if (!v) {
  84958. return null;
  84959. }
  84960. return new BABYLON.Vector3(v.x, v.y, v.z);
  84961. };
  84962. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  84963. impostor.physicsBody.mass = mass;
  84964. impostor.physicsBody.updateMassProperties();
  84965. };
  84966. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  84967. return impostor.physicsBody.mass;
  84968. };
  84969. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  84970. return impostor.physicsBody.material.friction;
  84971. };
  84972. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  84973. impostor.physicsBody.material.friction = friction;
  84974. };
  84975. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  84976. return impostor.physicsBody.material.restitution;
  84977. };
  84978. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  84979. impostor.physicsBody.material.restitution = restitution;
  84980. };
  84981. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  84982. impostor.physicsBody.sleep();
  84983. };
  84984. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  84985. impostor.physicsBody.wakeUp();
  84986. };
  84987. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  84988. joint.physicsJoint.distance = maxDistance;
  84989. };
  84990. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  84991. // if (!motorIndex) {
  84992. // joint.physicsJoint.enableMotor();
  84993. // }
  84994. // }
  84995. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  84996. // if (!motorIndex) {
  84997. // joint.physicsJoint.disableMotor();
  84998. // }
  84999. // }
  85000. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  85001. if (!motorIndex) {
  85002. joint.physicsJoint.enableMotor();
  85003. joint.physicsJoint.setMotorSpeed(speed);
  85004. if (maxForce) {
  85005. this.setLimit(joint, maxForce);
  85006. }
  85007. }
  85008. };
  85009. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  85010. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  85011. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  85012. };
  85013. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  85014. var body = impostor.physicsBody;
  85015. mesh.position.x = body.position.x;
  85016. mesh.position.y = body.position.y;
  85017. mesh.position.z = body.position.z;
  85018. if (mesh.rotationQuaternion) {
  85019. mesh.rotationQuaternion.x = body.quaternion.x;
  85020. mesh.rotationQuaternion.y = body.quaternion.y;
  85021. mesh.rotationQuaternion.z = body.quaternion.z;
  85022. mesh.rotationQuaternion.w = body.quaternion.w;
  85023. }
  85024. };
  85025. CannonJSPlugin.prototype.getRadius = function (impostor) {
  85026. var shape = impostor.physicsBody.shapes[0];
  85027. return shape.boundingSphereRadius;
  85028. };
  85029. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  85030. var shape = impostor.physicsBody.shapes[0];
  85031. result.x = shape.halfExtents.x * 2;
  85032. result.y = shape.halfExtents.y * 2;
  85033. result.z = shape.halfExtents.z * 2;
  85034. };
  85035. CannonJSPlugin.prototype.dispose = function () {
  85036. };
  85037. CannonJSPlugin.prototype._extendNamespace = function () {
  85038. //this will force cannon to execute at least one step when using interpolation
  85039. var step_tmp1 = new this.BJSCANNON.Vec3();
  85040. var Engine = this.BJSCANNON;
  85041. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  85042. maxSubSteps = maxSubSteps || 10;
  85043. timeSinceLastCalled = timeSinceLastCalled || 0;
  85044. if (timeSinceLastCalled === 0) {
  85045. this.internalStep(dt);
  85046. this.time += dt;
  85047. }
  85048. else {
  85049. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  85050. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  85051. var t0 = performance.now();
  85052. for (var i = 0; i !== internalSteps; i++) {
  85053. this.internalStep(dt);
  85054. if (performance.now() - t0 > dt * 1000) {
  85055. break;
  85056. }
  85057. }
  85058. this.time += timeSinceLastCalled;
  85059. var h = this.time % dt;
  85060. var h_div_dt = h / dt;
  85061. var interpvelo = step_tmp1;
  85062. var bodies = this.bodies;
  85063. for (var j = 0; j !== bodies.length; j++) {
  85064. var b = bodies[j];
  85065. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  85066. b.position.vsub(b.previousPosition, interpvelo);
  85067. interpvelo.scale(h_div_dt, interpvelo);
  85068. b.position.vadd(interpvelo, b.interpolatedPosition);
  85069. }
  85070. else {
  85071. b.interpolatedPosition.copy(b.position);
  85072. b.interpolatedQuaternion.copy(b.quaternion);
  85073. }
  85074. }
  85075. }
  85076. };
  85077. };
  85078. return CannonJSPlugin;
  85079. }());
  85080. BABYLON.CannonJSPlugin = CannonJSPlugin;
  85081. })(BABYLON || (BABYLON = {}));
  85082. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  85083. var BABYLON;
  85084. (function (BABYLON) {
  85085. var OimoJSPlugin = /** @class */ (function () {
  85086. function OimoJSPlugin(iterations) {
  85087. this.name = "OimoJSPlugin";
  85088. this._tmpImpostorsArray = [];
  85089. this._tmpPositionVector = BABYLON.Vector3.Zero();
  85090. this.BJSOIMO = OIMO;
  85091. this.world = new this.BJSOIMO.World({
  85092. iterations: iterations
  85093. });
  85094. this.world.clear();
  85095. }
  85096. OimoJSPlugin.prototype.setGravity = function (gravity) {
  85097. this.world.gravity.copy(gravity);
  85098. };
  85099. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  85100. this.world.timeStep = timeStep;
  85101. };
  85102. OimoJSPlugin.prototype.getTimeStep = function () {
  85103. return this.world.timeStep;
  85104. };
  85105. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  85106. var _this = this;
  85107. impostors.forEach(function (impostor) {
  85108. impostor.beforeStep();
  85109. });
  85110. this.world.step();
  85111. impostors.forEach(function (impostor) {
  85112. impostor.afterStep();
  85113. //update the ordered impostors array
  85114. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  85115. });
  85116. //check for collisions
  85117. var contact = this.world.contacts;
  85118. while (contact !== null) {
  85119. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  85120. contact = contact.next;
  85121. continue;
  85122. }
  85123. //is this body colliding with any other? get the impostor
  85124. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  85125. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  85126. if (!mainImpostor || !collidingImpostor) {
  85127. contact = contact.next;
  85128. continue;
  85129. }
  85130. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  85131. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  85132. contact = contact.next;
  85133. }
  85134. };
  85135. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  85136. var mass = impostor.physicsBody.mass;
  85137. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  85138. };
  85139. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  85140. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  85141. this.applyImpulse(impostor, force, contactPoint);
  85142. };
  85143. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  85144. var _this = this;
  85145. //parent-child relationship. Does this impostor has a parent impostor?
  85146. if (impostor.parent) {
  85147. if (impostor.physicsBody) {
  85148. this.removePhysicsBody(impostor);
  85149. //TODO is that needed?
  85150. impostor.forceUpdate();
  85151. }
  85152. return;
  85153. }
  85154. if (impostor.isBodyInitRequired()) {
  85155. var bodyConfig = {
  85156. name: impostor.uniqueId,
  85157. //Oimo must have mass, also for static objects.
  85158. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  85159. size: [],
  85160. type: [],
  85161. pos: [],
  85162. posShape: [],
  85163. rot: [],
  85164. rotShape: [],
  85165. move: impostor.getParam("mass") !== 0,
  85166. density: impostor.getParam("mass"),
  85167. friction: impostor.getParam("friction"),
  85168. restitution: impostor.getParam("restitution"),
  85169. //Supporting older versions of Oimo
  85170. world: this.world
  85171. };
  85172. var impostors = [impostor];
  85173. var addToArray = function (parent) {
  85174. if (!parent.getChildMeshes)
  85175. return;
  85176. parent.getChildMeshes().forEach(function (m) {
  85177. if (m.physicsImpostor) {
  85178. impostors.push(m.physicsImpostor);
  85179. //m.physicsImpostor._init();
  85180. }
  85181. });
  85182. };
  85183. addToArray(impostor.object);
  85184. var checkWithEpsilon_1 = function (value) {
  85185. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  85186. };
  85187. impostors.forEach(function (i) {
  85188. if (!i.object.rotationQuaternion) {
  85189. return;
  85190. }
  85191. //get the correct bounding box
  85192. var oldQuaternion = i.object.rotationQuaternion;
  85193. var rot = oldQuaternion.toEulerAngles();
  85194. var extendSize = i.getObjectExtendSize();
  85195. var radToDeg = 57.295779513082320876;
  85196. if (i === impostor) {
  85197. var center = impostor.getObjectCenter();
  85198. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  85199. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  85200. //Can also use Array.prototype.push.apply
  85201. bodyConfig.pos.push(center.x);
  85202. bodyConfig.pos.push(center.y);
  85203. bodyConfig.pos.push(center.z);
  85204. bodyConfig.posShape.push(0, 0, 0);
  85205. //tmp solution
  85206. bodyConfig.rot.push(rot.x * radToDeg);
  85207. bodyConfig.rot.push(rot.y * radToDeg);
  85208. bodyConfig.rot.push(rot.z * radToDeg);
  85209. bodyConfig.rotShape.push(0, 0, 0);
  85210. }
  85211. else {
  85212. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  85213. bodyConfig.posShape.push(localPosition.x);
  85214. bodyConfig.posShape.push(localPosition.y);
  85215. bodyConfig.posShape.push(localPosition.z);
  85216. bodyConfig.pos.push(0, 0, 0);
  85217. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  85218. bodyConfig.rot.push(0);
  85219. bodyConfig.rot.push(0);
  85220. bodyConfig.rot.push(0);
  85221. bodyConfig.rotShape.push(rot.x * radToDeg);
  85222. bodyConfig.rotShape.push(rot.y * radToDeg);
  85223. bodyConfig.rotShape.push(rot.z * radToDeg);
  85224. }
  85225. // register mesh
  85226. switch (i.type) {
  85227. case BABYLON.PhysicsImpostor.ParticleImpostor:
  85228. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  85229. case BABYLON.PhysicsImpostor.SphereImpostor:
  85230. var radiusX = extendSize.x;
  85231. var radiusY = extendSize.y;
  85232. var radiusZ = extendSize.z;
  85233. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  85234. bodyConfig.type.push('sphere');
  85235. //due to the way oimo works with compounds, add 3 times
  85236. bodyConfig.size.push(size);
  85237. bodyConfig.size.push(size);
  85238. bodyConfig.size.push(size);
  85239. break;
  85240. case BABYLON.PhysicsImpostor.CylinderImpostor:
  85241. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  85242. var sizeY = checkWithEpsilon_1(extendSize.y);
  85243. bodyConfig.type.push('cylinder');
  85244. bodyConfig.size.push(sizeX);
  85245. bodyConfig.size.push(sizeY);
  85246. //due to the way oimo works with compounds, add one more value.
  85247. bodyConfig.size.push(sizeY);
  85248. break;
  85249. case BABYLON.PhysicsImpostor.PlaneImpostor:
  85250. case BABYLON.PhysicsImpostor.BoxImpostor:
  85251. default:
  85252. var sizeX = checkWithEpsilon_1(extendSize.x);
  85253. var sizeY = checkWithEpsilon_1(extendSize.y);
  85254. var sizeZ = checkWithEpsilon_1(extendSize.z);
  85255. bodyConfig.type.push('box');
  85256. //if (i === impostor) {
  85257. bodyConfig.size.push(sizeX);
  85258. bodyConfig.size.push(sizeY);
  85259. bodyConfig.size.push(sizeZ);
  85260. //} else {
  85261. // bodyConfig.size.push(0,0,0);
  85262. //}
  85263. break;
  85264. }
  85265. //actually not needed, but hey...
  85266. i.object.rotationQuaternion = oldQuaternion;
  85267. });
  85268. impostor.physicsBody = this.world.add(bodyConfig);
  85269. }
  85270. else {
  85271. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  85272. }
  85273. impostor.setDeltaPosition(this._tmpPositionVector);
  85274. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  85275. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  85276. };
  85277. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  85278. //impostor.physicsBody.dispose();
  85279. //Same as : (older oimo versions)
  85280. this.world.removeRigidBody(impostor.physicsBody);
  85281. };
  85282. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  85283. var mainBody = impostorJoint.mainImpostor.physicsBody;
  85284. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  85285. if (!mainBody || !connectedBody) {
  85286. return;
  85287. }
  85288. var jointData = impostorJoint.joint.jointData;
  85289. var options = jointData.nativeParams || {};
  85290. var type;
  85291. var nativeJointData = {
  85292. body1: mainBody,
  85293. body2: connectedBody,
  85294. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  85295. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  85296. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  85297. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  85298. min: options.min,
  85299. max: options.max,
  85300. collision: options.collision || jointData.collision,
  85301. spring: options.spring,
  85302. //supporting older version of Oimo
  85303. world: this.world
  85304. };
  85305. switch (impostorJoint.joint.type) {
  85306. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  85307. type = "jointBall";
  85308. break;
  85309. case BABYLON.PhysicsJoint.SpringJoint:
  85310. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  85311. var springData = jointData;
  85312. nativeJointData.min = springData.length || nativeJointData.min;
  85313. //Max should also be set, just make sure it is at least min
  85314. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  85315. case BABYLON.PhysicsJoint.DistanceJoint:
  85316. type = "jointDistance";
  85317. nativeJointData.max = jointData.maxDistance;
  85318. break;
  85319. case BABYLON.PhysicsJoint.PrismaticJoint:
  85320. type = "jointPrisme";
  85321. break;
  85322. case BABYLON.PhysicsJoint.SliderJoint:
  85323. type = "jointSlide";
  85324. break;
  85325. case BABYLON.PhysicsJoint.WheelJoint:
  85326. type = "jointWheel";
  85327. break;
  85328. case BABYLON.PhysicsJoint.HingeJoint:
  85329. default:
  85330. type = "jointHinge";
  85331. break;
  85332. }
  85333. nativeJointData.type = type;
  85334. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  85335. };
  85336. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  85337. //Bug in Oimo prevents us from disposing a joint in the playground
  85338. //joint.joint.physicsJoint.dispose();
  85339. //So we will bruteforce it!
  85340. try {
  85341. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  85342. }
  85343. catch (e) {
  85344. BABYLON.Tools.Warn(e);
  85345. }
  85346. };
  85347. OimoJSPlugin.prototype.isSupported = function () {
  85348. return this.BJSOIMO !== undefined;
  85349. };
  85350. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  85351. if (!impostor.physicsBody.sleeping) {
  85352. //TODO check that
  85353. /*if (impostor.physicsBody.shapes.next) {
  85354. var parentShape = this._getLastShape(impostor.physicsBody);
  85355. impostor.object.position.copyFrom(parentShape.position);
  85356. console.log(parentShape.position);
  85357. } else {*/
  85358. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  85359. //}
  85360. if (impostor.object.rotationQuaternion) {
  85361. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  85362. }
  85363. }
  85364. };
  85365. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  85366. var body = impostor.physicsBody;
  85367. body.position.copy(newPosition);
  85368. body.orientation.copy(newRotation);
  85369. body.syncShapes();
  85370. body.awake();
  85371. };
  85372. /*private _getLastShape(body: any): any {
  85373. var lastShape = body.shapes;
  85374. while (lastShape.next) {
  85375. lastShape = lastShape.next;
  85376. }
  85377. return lastShape;
  85378. }*/
  85379. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  85380. impostor.physicsBody.linearVelocity.copy(velocity);
  85381. };
  85382. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  85383. impostor.physicsBody.angularVelocity.copy(velocity);
  85384. };
  85385. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  85386. var v = impostor.physicsBody.linearVelocity;
  85387. if (!v) {
  85388. return null;
  85389. }
  85390. return new BABYLON.Vector3(v.x, v.y, v.z);
  85391. };
  85392. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  85393. var v = impostor.physicsBody.angularVelocity;
  85394. if (!v) {
  85395. return null;
  85396. }
  85397. return new BABYLON.Vector3(v.x, v.y, v.z);
  85398. };
  85399. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  85400. var staticBody = mass === 0;
  85401. //this will actually set the body's density and not its mass.
  85402. //But this is how oimo treats the mass variable.
  85403. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  85404. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  85405. };
  85406. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  85407. return impostor.physicsBody.shapes.density;
  85408. };
  85409. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  85410. return impostor.physicsBody.shapes.friction;
  85411. };
  85412. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  85413. impostor.physicsBody.shapes.friction = friction;
  85414. };
  85415. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  85416. return impostor.physicsBody.shapes.restitution;
  85417. };
  85418. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  85419. impostor.physicsBody.shapes.restitution = restitution;
  85420. };
  85421. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  85422. impostor.physicsBody.sleep();
  85423. };
  85424. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  85425. impostor.physicsBody.awake();
  85426. };
  85427. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  85428. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  85429. if (minDistance !== void 0) {
  85430. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  85431. }
  85432. };
  85433. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  85434. //TODO separate rotational and transational motors.
  85435. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  85436. if (motor) {
  85437. motor.setMotor(speed, maxForce);
  85438. }
  85439. };
  85440. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  85441. //TODO separate rotational and transational motors.
  85442. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  85443. if (motor) {
  85444. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  85445. }
  85446. };
  85447. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  85448. var body = impostor.physicsBody;
  85449. mesh.position.x = body.position.x;
  85450. mesh.position.y = body.position.y;
  85451. mesh.position.z = body.position.z;
  85452. if (mesh.rotationQuaternion) {
  85453. mesh.rotationQuaternion.x = body.orientation.x;
  85454. mesh.rotationQuaternion.y = body.orientation.y;
  85455. mesh.rotationQuaternion.z = body.orientation.z;
  85456. mesh.rotationQuaternion.w = body.orientation.s;
  85457. }
  85458. };
  85459. OimoJSPlugin.prototype.getRadius = function (impostor) {
  85460. return impostor.physicsBody.shapes.radius;
  85461. };
  85462. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  85463. var shape = impostor.physicsBody.shapes;
  85464. result.x = shape.halfWidth * 2;
  85465. result.y = shape.halfHeight * 2;
  85466. result.z = shape.halfDepth * 2;
  85467. };
  85468. OimoJSPlugin.prototype.dispose = function () {
  85469. this.world.clear();
  85470. };
  85471. return OimoJSPlugin;
  85472. }());
  85473. BABYLON.OimoJSPlugin = OimoJSPlugin;
  85474. })(BABYLON || (BABYLON = {}));
  85475. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  85476. var BABYLON;
  85477. (function (BABYLON) {
  85478. /*
  85479. * Based on jsTGALoader - Javascript loader for TGA file
  85480. * By Vincent Thibault
  85481. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  85482. */
  85483. var TGATools = /** @class */ (function () {
  85484. function TGATools() {
  85485. }
  85486. TGATools.GetTGAHeader = function (data) {
  85487. var offset = 0;
  85488. var header = {
  85489. id_length: data[offset++],
  85490. colormap_type: data[offset++],
  85491. image_type: data[offset++],
  85492. colormap_index: data[offset++] | data[offset++] << 8,
  85493. colormap_length: data[offset++] | data[offset++] << 8,
  85494. colormap_size: data[offset++],
  85495. origin: [
  85496. data[offset++] | data[offset++] << 8,
  85497. data[offset++] | data[offset++] << 8
  85498. ],
  85499. width: data[offset++] | data[offset++] << 8,
  85500. height: data[offset++] | data[offset++] << 8,
  85501. pixel_size: data[offset++],
  85502. flags: data[offset++]
  85503. };
  85504. return header;
  85505. };
  85506. TGATools.UploadContent = function (gl, data) {
  85507. // Not enough data to contain header ?
  85508. if (data.length < 19) {
  85509. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  85510. return;
  85511. }
  85512. // Read Header
  85513. var offset = 18;
  85514. var header = TGATools.GetTGAHeader(data);
  85515. // Assume it's a valid Targa file.
  85516. if (header.id_length + offset > data.length) {
  85517. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  85518. return;
  85519. }
  85520. // Skip not needed data
  85521. offset += header.id_length;
  85522. var use_rle = false;
  85523. var use_pal = false;
  85524. var use_grey = false;
  85525. // Get some informations.
  85526. switch (header.image_type) {
  85527. case TGATools._TYPE_RLE_INDEXED:
  85528. use_rle = true;
  85529. case TGATools._TYPE_INDEXED:
  85530. use_pal = true;
  85531. break;
  85532. case TGATools._TYPE_RLE_RGB:
  85533. use_rle = true;
  85534. case TGATools._TYPE_RGB:
  85535. // use_rgb = true;
  85536. break;
  85537. case TGATools._TYPE_RLE_GREY:
  85538. use_rle = true;
  85539. case TGATools._TYPE_GREY:
  85540. use_grey = true;
  85541. break;
  85542. }
  85543. var pixel_data;
  85544. // var numAlphaBits = header.flags & 0xf;
  85545. var pixel_size = header.pixel_size >> 3;
  85546. var pixel_total = header.width * header.height * pixel_size;
  85547. // Read palettes
  85548. var palettes;
  85549. if (use_pal) {
  85550. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  85551. }
  85552. // Read LRE
  85553. if (use_rle) {
  85554. pixel_data = new Uint8Array(pixel_total);
  85555. var c, count, i;
  85556. var localOffset = 0;
  85557. var pixels = new Uint8Array(pixel_size);
  85558. while (offset < pixel_total && localOffset < pixel_total) {
  85559. c = data[offset++];
  85560. count = (c & 0x7f) + 1;
  85561. // RLE pixels
  85562. if (c & 0x80) {
  85563. // Bind pixel tmp array
  85564. for (i = 0; i < pixel_size; ++i) {
  85565. pixels[i] = data[offset++];
  85566. }
  85567. // Copy pixel array
  85568. for (i = 0; i < count; ++i) {
  85569. pixel_data.set(pixels, localOffset + i * pixel_size);
  85570. }
  85571. localOffset += pixel_size * count;
  85572. }
  85573. // Raw pixels
  85574. else {
  85575. count *= pixel_size;
  85576. for (i = 0; i < count; ++i) {
  85577. pixel_data[localOffset + i] = data[offset++];
  85578. }
  85579. localOffset += count;
  85580. }
  85581. }
  85582. }
  85583. // RAW Pixels
  85584. else {
  85585. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  85586. }
  85587. // Load to texture
  85588. var x_start, y_start, x_step, y_step, y_end, x_end;
  85589. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  85590. default:
  85591. case TGATools._ORIGIN_UL:
  85592. x_start = 0;
  85593. x_step = 1;
  85594. x_end = header.width;
  85595. y_start = 0;
  85596. y_step = 1;
  85597. y_end = header.height;
  85598. break;
  85599. case TGATools._ORIGIN_BL:
  85600. x_start = 0;
  85601. x_step = 1;
  85602. x_end = header.width;
  85603. y_start = header.height - 1;
  85604. y_step = -1;
  85605. y_end = -1;
  85606. break;
  85607. case TGATools._ORIGIN_UR:
  85608. x_start = header.width - 1;
  85609. x_step = -1;
  85610. x_end = -1;
  85611. y_start = 0;
  85612. y_step = 1;
  85613. y_end = header.height;
  85614. break;
  85615. case TGATools._ORIGIN_BR:
  85616. x_start = header.width - 1;
  85617. x_step = -1;
  85618. x_end = -1;
  85619. y_start = header.height - 1;
  85620. y_step = -1;
  85621. y_end = -1;
  85622. break;
  85623. }
  85624. // Load the specify method
  85625. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  85626. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  85627. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  85628. };
  85629. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  85630. var image = pixel_data, colormap = palettes;
  85631. var width = header.width, height = header.height;
  85632. var color, i = 0, x, y;
  85633. var imageData = new Uint8Array(width * height * 4);
  85634. for (y = y_start; y !== y_end; y += y_step) {
  85635. for (x = x_start; x !== x_end; x += x_step, i++) {
  85636. color = image[i];
  85637. imageData[(x + width * y) * 4 + 3] = 255;
  85638. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  85639. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  85640. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  85641. }
  85642. }
  85643. return imageData;
  85644. };
  85645. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  85646. var image = pixel_data;
  85647. var width = header.width, height = header.height;
  85648. var color, i = 0, x, y;
  85649. var imageData = new Uint8Array(width * height * 4);
  85650. for (y = y_start; y !== y_end; y += y_step) {
  85651. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  85652. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  85653. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  85654. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  85655. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  85656. imageData[(x + width * y) * 4 + 0] = r;
  85657. imageData[(x + width * y) * 4 + 1] = g;
  85658. imageData[(x + width * y) * 4 + 2] = b;
  85659. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  85660. }
  85661. }
  85662. return imageData;
  85663. };
  85664. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  85665. var image = pixel_data;
  85666. var width = header.width, height = header.height;
  85667. var i = 0, x, y;
  85668. var imageData = new Uint8Array(width * height * 4);
  85669. for (y = y_start; y !== y_end; y += y_step) {
  85670. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  85671. imageData[(x + width * y) * 4 + 3] = 255;
  85672. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  85673. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  85674. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  85675. }
  85676. }
  85677. return imageData;
  85678. };
  85679. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  85680. var image = pixel_data;
  85681. var width = header.width, height = header.height;
  85682. var i = 0, x, y;
  85683. var imageData = new Uint8Array(width * height * 4);
  85684. for (y = y_start; y !== y_end; y += y_step) {
  85685. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  85686. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  85687. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  85688. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  85689. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  85690. }
  85691. }
  85692. return imageData;
  85693. };
  85694. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  85695. var image = pixel_data;
  85696. var width = header.width, height = header.height;
  85697. var color, i = 0, x, y;
  85698. var imageData = new Uint8Array(width * height * 4);
  85699. for (y = y_start; y !== y_end; y += y_step) {
  85700. for (x = x_start; x !== x_end; x += x_step, i++) {
  85701. color = image[i];
  85702. imageData[(x + width * y) * 4 + 0] = color;
  85703. imageData[(x + width * y) * 4 + 1] = color;
  85704. imageData[(x + width * y) * 4 + 2] = color;
  85705. imageData[(x + width * y) * 4 + 3] = 255;
  85706. }
  85707. }
  85708. return imageData;
  85709. };
  85710. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  85711. var image = pixel_data;
  85712. var width = header.width, height = header.height;
  85713. var i = 0, x, y;
  85714. var imageData = new Uint8Array(width * height * 4);
  85715. for (y = y_start; y !== y_end; y += y_step) {
  85716. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  85717. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  85718. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  85719. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  85720. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  85721. }
  85722. }
  85723. return imageData;
  85724. };
  85725. //private static _TYPE_NO_DATA = 0;
  85726. TGATools._TYPE_INDEXED = 1;
  85727. TGATools._TYPE_RGB = 2;
  85728. TGATools._TYPE_GREY = 3;
  85729. TGATools._TYPE_RLE_INDEXED = 9;
  85730. TGATools._TYPE_RLE_RGB = 10;
  85731. TGATools._TYPE_RLE_GREY = 11;
  85732. TGATools._ORIGIN_MASK = 0x30;
  85733. TGATools._ORIGIN_SHIFT = 0x04;
  85734. TGATools._ORIGIN_BL = 0x00;
  85735. TGATools._ORIGIN_BR = 0x01;
  85736. TGATools._ORIGIN_UL = 0x02;
  85737. TGATools._ORIGIN_UR = 0x03;
  85738. return TGATools;
  85739. }());
  85740. BABYLON.TGATools = TGATools;
  85741. })(BABYLON || (BABYLON = {}));
  85742. //# sourceMappingURL=babylon.tga.js.map
  85743. var BABYLON;
  85744. (function (BABYLON) {
  85745. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  85746. // All values and structures referenced from:
  85747. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  85748. var DDS_MAGIC = 0x20534444;
  85749. var
  85750. //DDSD_CAPS = 0x1,
  85751. //DDSD_HEIGHT = 0x2,
  85752. //DDSD_WIDTH = 0x4,
  85753. //DDSD_PITCH = 0x8,
  85754. //DDSD_PIXELFORMAT = 0x1000,
  85755. DDSD_MIPMAPCOUNT = 0x20000;
  85756. //DDSD_LINEARSIZE = 0x80000,
  85757. //DDSD_DEPTH = 0x800000;
  85758. // var DDSCAPS_COMPLEX = 0x8,
  85759. // DDSCAPS_MIPMAP = 0x400000,
  85760. // DDSCAPS_TEXTURE = 0x1000;
  85761. var DDSCAPS2_CUBEMAP = 0x200;
  85762. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  85763. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  85764. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  85765. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  85766. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  85767. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  85768. // DDSCAPS2_VOLUME = 0x200000;
  85769. var
  85770. //DDPF_ALPHAPIXELS = 0x1,
  85771. //DDPF_ALPHA = 0x2,
  85772. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  85773. //DDPF_YUV = 0x200,
  85774. DDPF_LUMINANCE = 0x20000;
  85775. function FourCCToInt32(value) {
  85776. return value.charCodeAt(0) +
  85777. (value.charCodeAt(1) << 8) +
  85778. (value.charCodeAt(2) << 16) +
  85779. (value.charCodeAt(3) << 24);
  85780. }
  85781. function Int32ToFourCC(value) {
  85782. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  85783. }
  85784. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  85785. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  85786. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  85787. var FOURCC_DX10 = FourCCToInt32("DX10");
  85788. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  85789. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  85790. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  85791. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  85792. var headerLengthInt = 31; // The header length in 32 bit ints
  85793. // Offsets into the header array
  85794. var off_magic = 0;
  85795. var off_size = 1;
  85796. var off_flags = 2;
  85797. var off_height = 3;
  85798. var off_width = 4;
  85799. var off_mipmapCount = 7;
  85800. var off_pfFlags = 20;
  85801. var off_pfFourCC = 21;
  85802. var off_RGBbpp = 22;
  85803. var off_RMask = 23;
  85804. var off_GMask = 24;
  85805. var off_BMask = 25;
  85806. var off_AMask = 26;
  85807. // var off_caps1 = 27;
  85808. var off_caps2 = 28;
  85809. // var off_caps3 = 29;
  85810. // var off_caps4 = 30;
  85811. var off_dxgiFormat = 32;
  85812. ;
  85813. var DDSTools = /** @class */ (function () {
  85814. function DDSTools() {
  85815. }
  85816. DDSTools.GetDDSInfo = function (arrayBuffer) {
  85817. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  85818. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  85819. var mipmapCount = 1;
  85820. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  85821. mipmapCount = Math.max(1, header[off_mipmapCount]);
  85822. }
  85823. var fourCC = header[off_pfFourCC];
  85824. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  85825. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  85826. switch (fourCC) {
  85827. case FOURCC_D3DFMT_R16G16B16A16F:
  85828. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  85829. break;
  85830. case FOURCC_D3DFMT_R32G32B32A32F:
  85831. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  85832. break;
  85833. case FOURCC_DX10:
  85834. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  85835. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  85836. break;
  85837. }
  85838. }
  85839. return {
  85840. width: header[off_width],
  85841. height: header[off_height],
  85842. mipmapCount: mipmapCount,
  85843. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  85844. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  85845. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  85846. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  85847. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  85848. dxgiFormat: dxgiFormat,
  85849. textureType: textureType
  85850. };
  85851. };
  85852. DDSTools._ToHalfFloat = function (value) {
  85853. if (!DDSTools._FloatView) {
  85854. DDSTools._FloatView = new Float32Array(1);
  85855. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  85856. }
  85857. DDSTools._FloatView[0] = value;
  85858. var x = DDSTools._Int32View[0];
  85859. var bits = (x >> 16) & 0x8000; /* Get the sign */
  85860. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  85861. var e = (x >> 23) & 0xff; /* Using int is faster here */
  85862. /* If zero, or denormal, or exponent underflows too much for a denormal
  85863. * half, return signed zero. */
  85864. if (e < 103) {
  85865. return bits;
  85866. }
  85867. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  85868. if (e > 142) {
  85869. bits |= 0x7c00;
  85870. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  85871. * not Inf, so make sure we set one mantissa bit too. */
  85872. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  85873. return bits;
  85874. }
  85875. /* If exponent underflows but not too much, return a denormal */
  85876. if (e < 113) {
  85877. m |= 0x0800;
  85878. /* Extra rounding may overflow and set mantissa to 0 and exponent
  85879. * to 1, which is OK. */
  85880. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  85881. return bits;
  85882. }
  85883. bits |= ((e - 112) << 10) | (m >> 1);
  85884. bits += m & 1;
  85885. return bits;
  85886. };
  85887. DDSTools._FromHalfFloat = function (value) {
  85888. var s = (value & 0x8000) >> 15;
  85889. var e = (value & 0x7C00) >> 10;
  85890. var f = value & 0x03FF;
  85891. if (e === 0) {
  85892. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  85893. }
  85894. else if (e == 0x1F) {
  85895. return f ? NaN : ((s ? -1 : 1) * Infinity);
  85896. }
  85897. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  85898. };
  85899. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  85900. var destArray = new Float32Array(dataLength);
  85901. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  85902. var index = 0;
  85903. for (var y = 0; y < height; y++) {
  85904. for (var x = 0; x < width; x++) {
  85905. var srcPos = (x + y * width) * 4;
  85906. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  85907. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  85908. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  85909. if (DDSTools.StoreLODInAlphaChannel) {
  85910. destArray[index + 3] = lod;
  85911. }
  85912. else {
  85913. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  85914. }
  85915. index += 4;
  85916. }
  85917. }
  85918. return destArray;
  85919. };
  85920. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  85921. if (DDSTools.StoreLODInAlphaChannel) {
  85922. var destArray = new Uint16Array(dataLength);
  85923. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  85924. var index = 0;
  85925. for (var y = 0; y < height; y++) {
  85926. for (var x = 0; x < width; x++) {
  85927. var srcPos = (x + y * width) * 4;
  85928. destArray[index] = srcData[srcPos];
  85929. destArray[index + 1] = srcData[srcPos + 1];
  85930. destArray[index + 2] = srcData[srcPos + 2];
  85931. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  85932. index += 4;
  85933. }
  85934. }
  85935. return destArray;
  85936. }
  85937. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  85938. };
  85939. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  85940. if (DDSTools.StoreLODInAlphaChannel) {
  85941. var destArray = new Float32Array(dataLength);
  85942. var srcData = new Float32Array(arrayBuffer, dataOffset);
  85943. var index = 0;
  85944. for (var y = 0; y < height; y++) {
  85945. for (var x = 0; x < width; x++) {
  85946. var srcPos = (x + y * width) * 4;
  85947. destArray[index] = srcData[srcPos];
  85948. destArray[index + 1] = srcData[srcPos + 1];
  85949. destArray[index + 2] = srcData[srcPos + 2];
  85950. destArray[index + 3] = lod;
  85951. index += 4;
  85952. }
  85953. }
  85954. return destArray;
  85955. }
  85956. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  85957. };
  85958. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  85959. var destArray = new Uint8Array(dataLength);
  85960. var srcData = new Float32Array(arrayBuffer, dataOffset);
  85961. var index = 0;
  85962. for (var y = 0; y < height; y++) {
  85963. for (var x = 0; x < width; x++) {
  85964. var srcPos = (x + y * width) * 4;
  85965. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  85966. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  85967. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  85968. if (DDSTools.StoreLODInAlphaChannel) {
  85969. destArray[index + 3] = lod;
  85970. }
  85971. else {
  85972. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  85973. }
  85974. index += 4;
  85975. }
  85976. }
  85977. return destArray;
  85978. };
  85979. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  85980. var destArray = new Uint8Array(dataLength);
  85981. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  85982. var index = 0;
  85983. for (var y = 0; y < height; y++) {
  85984. for (var x = 0; x < width; x++) {
  85985. var srcPos = (x + y * width) * 4;
  85986. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  85987. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  85988. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  85989. if (DDSTools.StoreLODInAlphaChannel) {
  85990. destArray[index + 3] = lod;
  85991. }
  85992. else {
  85993. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  85994. }
  85995. index += 4;
  85996. }
  85997. }
  85998. return destArray;
  85999. };
  86000. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  86001. var byteArray = new Uint8Array(dataLength);
  86002. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  86003. var index = 0;
  86004. for (var y = 0; y < height; y++) {
  86005. for (var x = 0; x < width; x++) {
  86006. var srcPos = (x + y * width) * 4;
  86007. byteArray[index] = srcData[srcPos + rOffset];
  86008. byteArray[index + 1] = srcData[srcPos + gOffset];
  86009. byteArray[index + 2] = srcData[srcPos + bOffset];
  86010. byteArray[index + 3] = srcData[srcPos + aOffset];
  86011. index += 4;
  86012. }
  86013. }
  86014. return byteArray;
  86015. };
  86016. DDSTools._ExtractLongWordOrder = function (value) {
  86017. if (value === 0 || value === 255 || value === -16777216) {
  86018. return 0;
  86019. }
  86020. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  86021. };
  86022. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  86023. var byteArray = new Uint8Array(dataLength);
  86024. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  86025. var index = 0;
  86026. for (var y = 0; y < height; y++) {
  86027. for (var x = 0; x < width; x++) {
  86028. var srcPos = (x + y * width) * 3;
  86029. byteArray[index] = srcData[srcPos + rOffset];
  86030. byteArray[index + 1] = srcData[srcPos + gOffset];
  86031. byteArray[index + 2] = srcData[srcPos + bOffset];
  86032. index += 3;
  86033. }
  86034. }
  86035. return byteArray;
  86036. };
  86037. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  86038. var byteArray = new Uint8Array(dataLength);
  86039. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  86040. var index = 0;
  86041. for (var y = 0; y < height; y++) {
  86042. for (var x = 0; x < width; x++) {
  86043. var srcPos = (x + y * width);
  86044. byteArray[index] = srcData[srcPos];
  86045. index++;
  86046. }
  86047. }
  86048. return byteArray;
  86049. };
  86050. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  86051. if (lodIndex === void 0) { lodIndex = -1; }
  86052. var sphericalPolynomialFaces = null;
  86053. if (info.sphericalPolynomial) {
  86054. sphericalPolynomialFaces = new Array();
  86055. }
  86056. var ext = engine.getCaps().s3tc;
  86057. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  86058. var fourCC, width, height, dataLength = 0, dataOffset;
  86059. var byteArray, mipmapCount, mip;
  86060. var internalFormat = 0;
  86061. var format = 0;
  86062. var blockBytes = 1;
  86063. if (header[off_magic] !== DDS_MAGIC) {
  86064. BABYLON.Tools.Error("Invalid magic number in DDS header");
  86065. return;
  86066. }
  86067. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  86068. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  86069. return;
  86070. }
  86071. if (info.isCompressed && !ext) {
  86072. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  86073. return;
  86074. }
  86075. var bpp = header[off_RGBbpp];
  86076. dataOffset = header[off_size] + 4;
  86077. var computeFormats = false;
  86078. if (info.isFourCC) {
  86079. fourCC = header[off_pfFourCC];
  86080. switch (fourCC) {
  86081. case FOURCC_DXT1:
  86082. blockBytes = 8;
  86083. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  86084. break;
  86085. case FOURCC_DXT3:
  86086. blockBytes = 16;
  86087. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  86088. break;
  86089. case FOURCC_DXT5:
  86090. blockBytes = 16;
  86091. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  86092. break;
  86093. case FOURCC_D3DFMT_R16G16B16A16F:
  86094. computeFormats = true;
  86095. break;
  86096. case FOURCC_D3DFMT_R32G32B32A32F:
  86097. computeFormats = true;
  86098. break;
  86099. case FOURCC_DX10:
  86100. // There is an additionnal header so dataOffset need to be changed
  86101. dataOffset += 5 * 4; // 5 uints
  86102. var supported = false;
  86103. switch (info.dxgiFormat) {
  86104. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  86105. computeFormats = true;
  86106. supported = true;
  86107. break;
  86108. case DXGI_FORMAT_B8G8R8X8_UNORM:
  86109. info.isRGB = true;
  86110. info.isFourCC = false;
  86111. bpp = 32;
  86112. supported = true;
  86113. break;
  86114. }
  86115. if (supported) {
  86116. break;
  86117. }
  86118. default:
  86119. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  86120. return;
  86121. }
  86122. }
  86123. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  86124. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  86125. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  86126. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  86127. if (computeFormats) {
  86128. format = engine._getWebGLTextureType(info.textureType);
  86129. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  86130. }
  86131. mipmapCount = 1;
  86132. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  86133. mipmapCount = Math.max(1, header[off_mipmapCount]);
  86134. }
  86135. for (var face = 0; face < faces; face++) {
  86136. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  86137. width = header[off_width];
  86138. height = header[off_height];
  86139. for (mip = 0; mip < mipmapCount; ++mip) {
  86140. if (lodIndex === -1 || lodIndex === mip) {
  86141. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  86142. var i = (lodIndex === -1) ? mip : 0;
  86143. if (!info.isCompressed && info.isFourCC) {
  86144. dataLength = width * height * 4;
  86145. var floatArray = null;
  86146. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
  86147. if (bpp === 128) {
  86148. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  86149. if (sphericalPolynomialFaces && i == 0) {
  86150. sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  86151. }
  86152. }
  86153. else if (bpp === 64) {
  86154. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  86155. if (sphericalPolynomialFaces && i == 0) {
  86156. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  86157. }
  86158. }
  86159. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  86160. format = engine._getWebGLTextureType(info.textureType);
  86161. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  86162. }
  86163. else {
  86164. if (bpp === 128) {
  86165. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  86166. if (sphericalPolynomialFaces && i == 0) {
  86167. sphericalPolynomialFaces.push(floatArray);
  86168. }
  86169. }
  86170. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  86171. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  86172. if (sphericalPolynomialFaces && i == 0) {
  86173. sphericalPolynomialFaces.push(floatArray);
  86174. }
  86175. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  86176. format = engine._getWebGLTextureType(info.textureType);
  86177. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  86178. }
  86179. else { // 64
  86180. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  86181. if (sphericalPolynomialFaces && i == 0) {
  86182. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  86183. }
  86184. }
  86185. }
  86186. if (floatArray) {
  86187. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  86188. }
  86189. }
  86190. else if (info.isRGB) {
  86191. if (bpp === 24) {
  86192. dataLength = width * height * 3;
  86193. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  86194. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  86195. }
  86196. else { // 32
  86197. dataLength = width * height * 4;
  86198. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  86199. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  86200. }
  86201. }
  86202. else if (info.isLuminance) {
  86203. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  86204. var unpaddedRowSize = width;
  86205. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  86206. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  86207. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  86208. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  86209. }
  86210. else {
  86211. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  86212. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  86213. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  86214. }
  86215. }
  86216. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  86217. width *= 0.5;
  86218. height *= 0.5;
  86219. width = Math.max(1.0, width);
  86220. height = Math.max(1.0, height);
  86221. }
  86222. if (currentFace !== undefined) {
  86223. // Loading a single face
  86224. break;
  86225. }
  86226. }
  86227. if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {
  86228. info.sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({
  86229. size: header[off_width],
  86230. right: sphericalPolynomialFaces[0],
  86231. left: sphericalPolynomialFaces[1],
  86232. up: sphericalPolynomialFaces[2],
  86233. down: sphericalPolynomialFaces[3],
  86234. front: sphericalPolynomialFaces[4],
  86235. back: sphericalPolynomialFaces[5],
  86236. format: BABYLON.Engine.TEXTUREFORMAT_RGBA,
  86237. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  86238. gammaSpace: false,
  86239. });
  86240. }
  86241. else {
  86242. info.sphericalPolynomial = undefined;
  86243. }
  86244. };
  86245. DDSTools.StoreLODInAlphaChannel = false;
  86246. return DDSTools;
  86247. }());
  86248. BABYLON.DDSTools = DDSTools;
  86249. })(BABYLON || (BABYLON = {}));
  86250. //# sourceMappingURL=babylon.dds.js.map
  86251. var BABYLON;
  86252. (function (BABYLON) {
  86253. /**
  86254. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  86255. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  86256. */
  86257. var KhronosTextureContainer = /** @class */ (function () {
  86258. /**
  86259. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  86260. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  86261. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  86262. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  86263. */
  86264. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  86265. this.arrayBuffer = arrayBuffer;
  86266. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  86267. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  86268. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  86269. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  86270. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  86271. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  86272. BABYLON.Tools.Error("texture missing KTX identifier");
  86273. return;
  86274. }
  86275. // load the reset of the header in native 32 bit int
  86276. var header = new Int32Array(this.arrayBuffer, 12, 13);
  86277. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  86278. var oppositeEndianess = header[0] === 0x01020304;
  86279. // read all the header elements in order they exist in the file, without modification (sans endainness)
  86280. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  86281. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  86282. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  86283. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  86284. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  86285. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  86286. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  86287. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  86288. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  86289. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  86290. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  86291. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  86292. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  86293. if (this.glType !== 0) {
  86294. BABYLON.Tools.Error("only compressed formats currently supported");
  86295. return;
  86296. }
  86297. else {
  86298. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  86299. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  86300. }
  86301. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  86302. BABYLON.Tools.Error("only 2D textures currently supported");
  86303. return;
  86304. }
  86305. if (this.numberOfArrayElements !== 0) {
  86306. BABYLON.Tools.Error("texture arrays not currently supported");
  86307. return;
  86308. }
  86309. if (this.numberOfFaces !== facesExpected) {
  86310. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  86311. return;
  86312. }
  86313. // we now have a completely validated file, so could use existence of loadType as success
  86314. // would need to make this more elaborate & adjust checks above to support more than one load type
  86315. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  86316. }
  86317. // not as fast hardware based, but will probably never need to use
  86318. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  86319. return ((val & 0xFF) << 24)
  86320. | ((val & 0xFF00) << 8)
  86321. | ((val >> 8) & 0xFF00)
  86322. | ((val >> 24) & 0xFF);
  86323. };
  86324. /**
  86325. * It is assumed that the texture has already been created & is currently bound
  86326. */
  86327. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  86328. switch (this.loadType) {
  86329. case KhronosTextureContainer.COMPRESSED_2D:
  86330. this._upload2DCompressedLevels(gl, loadMipmaps);
  86331. break;
  86332. case KhronosTextureContainer.TEX_2D:
  86333. case KhronosTextureContainer.COMPRESSED_3D:
  86334. case KhronosTextureContainer.TEX_3D:
  86335. }
  86336. };
  86337. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  86338. // initialize width & height for level 1
  86339. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  86340. var width = this.pixelWidth;
  86341. var height = this.pixelHeight;
  86342. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  86343. for (var level = 0; level < mipmapCount; level++) {
  86344. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  86345. for (var face = 0; face < this.numberOfFaces; face++) {
  86346. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  86347. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  86348. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  86349. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  86350. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  86351. }
  86352. width = Math.max(1.0, width * 0.5);
  86353. height = Math.max(1.0, height * 0.5);
  86354. }
  86355. };
  86356. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  86357. // load types
  86358. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  86359. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  86360. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  86361. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  86362. return KhronosTextureContainer;
  86363. }());
  86364. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  86365. })(BABYLON || (BABYLON = {}));
  86366. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  86367. var BABYLON;
  86368. (function (BABYLON) {
  86369. var Debug;
  86370. (function (Debug) {
  86371. /**
  86372. * Class used to render a debug view of a given skeleton
  86373. * @see http://www.babylonjs-playground.com/#1BZJVJ#8
  86374. */
  86375. var SkeletonViewer = /** @class */ (function () {
  86376. /**
  86377. * Creates a new SkeletonViewer
  86378. * @param skeleton defines the skeleton to render
  86379. * @param mesh defines the mesh attached to the skeleton
  86380. * @param scene defines the hosting scene
  86381. * @param autoUpdateBonesMatrices defines a boolean indicating if bones matrices must be forced to update before rendering (true by default)
  86382. * @param renderingGroupId defines the rendering group id to use with the viewer
  86383. */
  86384. function SkeletonViewer(
  86385. /** defines the skeleton to render */
  86386. skeleton,
  86387. /** defines the mesh attached to the skeleton */
  86388. mesh, scene,
  86389. /** defines a boolean indicating if bones matrices must be forced to update before rendering (true by default) */
  86390. autoUpdateBonesMatrices,
  86391. /** defines the rendering group id to use with the viewer */
  86392. renderingGroupId) {
  86393. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  86394. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  86395. this.skeleton = skeleton;
  86396. this.mesh = mesh;
  86397. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  86398. this.renderingGroupId = renderingGroupId;
  86399. /** Gets or sets the color used to render the skeleton */
  86400. this.color = BABYLON.Color3.White();
  86401. this._debugLines = new Array();
  86402. this._isEnabled = false;
  86403. this._scene = scene;
  86404. this.update();
  86405. this._renderFunction = this.update.bind(this);
  86406. }
  86407. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  86408. get: function () {
  86409. return this._isEnabled;
  86410. },
  86411. /** Gets or sets a boolean indicating if the viewer is enabled */
  86412. set: function (value) {
  86413. if (this._isEnabled === value) {
  86414. return;
  86415. }
  86416. this._isEnabled = value;
  86417. if (value) {
  86418. this._scene.registerBeforeRender(this._renderFunction);
  86419. }
  86420. else {
  86421. this._scene.unregisterBeforeRender(this._renderFunction);
  86422. }
  86423. },
  86424. enumerable: true,
  86425. configurable: true
  86426. });
  86427. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  86428. if (x === void 0) { x = 0; }
  86429. if (y === void 0) { y = 0; }
  86430. if (z === void 0) { z = 0; }
  86431. var tmat = BABYLON.Tmp.Matrix[0];
  86432. var parentBone = bone.getParent();
  86433. tmat.copyFrom(bone.getLocalMatrix());
  86434. if (x !== 0 || y !== 0 || z !== 0) {
  86435. var tmat2 = BABYLON.Tmp.Matrix[1];
  86436. BABYLON.Matrix.IdentityToRef(tmat2);
  86437. tmat2.m[12] = x;
  86438. tmat2.m[13] = y;
  86439. tmat2.m[14] = z;
  86440. tmat2.multiplyToRef(tmat, tmat);
  86441. }
  86442. if (parentBone) {
  86443. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  86444. }
  86445. tmat.multiplyToRef(meshMat, tmat);
  86446. position.x = tmat.m[12];
  86447. position.y = tmat.m[13];
  86448. position.z = tmat.m[14];
  86449. };
  86450. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  86451. var len = bones.length;
  86452. var meshPos = this.mesh.position;
  86453. for (var i = 0; i < len; i++) {
  86454. var bone = bones[i];
  86455. var points = this._debugLines[i];
  86456. if (!points) {
  86457. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  86458. this._debugLines[i] = points;
  86459. }
  86460. this._getBonePosition(points[0], bone, meshMat);
  86461. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  86462. points[0].subtractInPlace(meshPos);
  86463. points[1].subtractInPlace(meshPos);
  86464. }
  86465. };
  86466. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  86467. var len = bones.length;
  86468. var boneNum = 0;
  86469. var meshPos = this.mesh.position;
  86470. for (var i = len - 1; i >= 0; i--) {
  86471. var childBone = bones[i];
  86472. var parentBone = childBone.getParent();
  86473. if (!parentBone) {
  86474. continue;
  86475. }
  86476. var points = this._debugLines[boneNum];
  86477. if (!points) {
  86478. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  86479. this._debugLines[boneNum] = points;
  86480. }
  86481. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  86482. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  86483. points[0].subtractInPlace(meshPos);
  86484. points[1].subtractInPlace(meshPos);
  86485. boneNum++;
  86486. }
  86487. };
  86488. /** Update the viewer to sync with current skeleton state */
  86489. SkeletonViewer.prototype.update = function () {
  86490. if (this.autoUpdateBonesMatrices) {
  86491. this.skeleton.computeAbsoluteTransforms();
  86492. }
  86493. if (this.skeleton.bones[0].length === undefined) {
  86494. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  86495. }
  86496. else {
  86497. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  86498. }
  86499. if (!this._debugMesh) {
  86500. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  86501. this._debugMesh.renderingGroupId = this.renderingGroupId;
  86502. }
  86503. else {
  86504. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  86505. }
  86506. this._debugMesh.position.copyFrom(this.mesh.position);
  86507. this._debugMesh.color = this.color;
  86508. };
  86509. /** Release associated resources */
  86510. SkeletonViewer.prototype.dispose = function () {
  86511. if (this._debugMesh) {
  86512. this.isEnabled = false;
  86513. this._debugMesh.dispose();
  86514. this._debugMesh = null;
  86515. }
  86516. };
  86517. return SkeletonViewer;
  86518. }());
  86519. Debug.SkeletonViewer = SkeletonViewer;
  86520. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  86521. })(BABYLON || (BABYLON = {}));
  86522. //# sourceMappingURL=babylon.skeletonViewer.js.map
  86523. /**
  86524. * Module Debug contains the (visual) components to debug a scene correctly
  86525. */
  86526. var BABYLON;
  86527. (function (BABYLON) {
  86528. var Debug;
  86529. (function (Debug) {
  86530. /**
  86531. * The Axes viewer will show 3 axes in a specific point in space
  86532. */
  86533. var AxesViewer = /** @class */ (function () {
  86534. /**
  86535. * Creates a new AxesViewer
  86536. * @param scene defines the hosting scene
  86537. * @param scaleLines defines a number used to scale line length (1 by default)
  86538. */
  86539. function AxesViewer(scene, scaleLines) {
  86540. if (scaleLines === void 0) { scaleLines = 1; }
  86541. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  86542. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  86543. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  86544. /**
  86545. * Gets or sets a number used to scale line length
  86546. */
  86547. this.scaleLines = 1;
  86548. this.scaleLines = scaleLines;
  86549. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  86550. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  86551. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  86552. this._xmesh.renderingGroupId = 2;
  86553. this._ymesh.renderingGroupId = 2;
  86554. this._zmesh.renderingGroupId = 2;
  86555. this._xmesh.material.checkReadyOnlyOnce = true;
  86556. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  86557. this._ymesh.material.checkReadyOnlyOnce = true;
  86558. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  86559. this._zmesh.material.checkReadyOnlyOnce = true;
  86560. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  86561. this.scene = scene;
  86562. }
  86563. /**
  86564. * Force the viewer to update
  86565. * @param position defines the position of the viewer
  86566. * @param xaxis defines the x axis of the viewer
  86567. * @param yaxis defines the y axis of the viewer
  86568. * @param zaxis defines the z axis of the viewer
  86569. */
  86570. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  86571. var scaleLines = this.scaleLines;
  86572. if (this._xmesh) {
  86573. this._xmesh.position.copyFrom(position);
  86574. }
  86575. if (this._ymesh) {
  86576. this._ymesh.position.copyFrom(position);
  86577. }
  86578. if (this._zmesh) {
  86579. this._zmesh.position.copyFrom(position);
  86580. }
  86581. var point2 = this._xline[1];
  86582. point2.x = xaxis.x * scaleLines;
  86583. point2.y = xaxis.y * scaleLines;
  86584. point2.z = xaxis.z * scaleLines;
  86585. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  86586. point2 = this._yline[1];
  86587. point2.x = yaxis.x * scaleLines;
  86588. point2.y = yaxis.y * scaleLines;
  86589. point2.z = yaxis.z * scaleLines;
  86590. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  86591. point2 = this._zline[1];
  86592. point2.x = zaxis.x * scaleLines;
  86593. point2.y = zaxis.y * scaleLines;
  86594. point2.z = zaxis.z * scaleLines;
  86595. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  86596. };
  86597. /** Releases resources */
  86598. AxesViewer.prototype.dispose = function () {
  86599. if (this._xmesh) {
  86600. this._xmesh.dispose();
  86601. }
  86602. if (this._ymesh) {
  86603. this._ymesh.dispose();
  86604. }
  86605. if (this._zmesh) {
  86606. this._zmesh.dispose();
  86607. }
  86608. this._xmesh = null;
  86609. this._ymesh = null;
  86610. this._zmesh = null;
  86611. this.scene = null;
  86612. };
  86613. return AxesViewer;
  86614. }());
  86615. Debug.AxesViewer = AxesViewer;
  86616. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  86617. })(BABYLON || (BABYLON = {}));
  86618. //# sourceMappingURL=babylon.axesViewer.js.map
  86619. var BABYLON;
  86620. (function (BABYLON) {
  86621. var Debug;
  86622. (function (Debug) {
  86623. /**
  86624. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  86625. * @see demo here: https://www.babylonjs-playground.com/#0DE8F4#8
  86626. */
  86627. var BoneAxesViewer = /** @class */ (function (_super) {
  86628. __extends(BoneAxesViewer, _super);
  86629. /**
  86630. * Creates a new BoneAxesViewer
  86631. * @param scene defines the hosting scene
  86632. * @param bone defines the target bone
  86633. * @param mesh defines the target mesh
  86634. * @param scaleLines defines a scaling factor for line length (1 by default)
  86635. */
  86636. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  86637. if (scaleLines === void 0) { scaleLines = 1; }
  86638. var _this = _super.call(this, scene, scaleLines) || this;
  86639. /** Gets current position */
  86640. _this.pos = BABYLON.Vector3.Zero();
  86641. /** Gets direction of X axis */
  86642. _this.xaxis = BABYLON.Vector3.Zero();
  86643. /** Gets direction of Y axis */
  86644. _this.yaxis = BABYLON.Vector3.Zero();
  86645. /** Gets direction of Z axis */
  86646. _this.zaxis = BABYLON.Vector3.Zero();
  86647. _this.mesh = mesh;
  86648. _this.bone = bone;
  86649. return _this;
  86650. }
  86651. /**
  86652. * Force the viewer to update
  86653. */
  86654. BoneAxesViewer.prototype.update = function () {
  86655. if (!this.mesh || !this.bone) {
  86656. return;
  86657. }
  86658. var bone = this.bone;
  86659. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  86660. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  86661. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  86662. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  86663. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  86664. };
  86665. /** Releases resources */
  86666. BoneAxesViewer.prototype.dispose = function () {
  86667. if (this.mesh) {
  86668. this.mesh = null;
  86669. this.bone = null;
  86670. _super.prototype.dispose.call(this);
  86671. }
  86672. };
  86673. return BoneAxesViewer;
  86674. }(Debug.AxesViewer));
  86675. Debug.BoneAxesViewer = BoneAxesViewer;
  86676. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  86677. })(BABYLON || (BABYLON = {}));
  86678. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  86679. var BABYLON;
  86680. (function (BABYLON) {
  86681. var RayHelper = /** @class */ (function () {
  86682. function RayHelper(ray) {
  86683. this.ray = ray;
  86684. }
  86685. RayHelper.CreateAndShow = function (ray, scene, color) {
  86686. var helper = new RayHelper(ray);
  86687. helper.show(scene, color);
  86688. return helper;
  86689. };
  86690. RayHelper.prototype.show = function (scene, color) {
  86691. if (!this._renderFunction && this.ray) {
  86692. var ray = this.ray;
  86693. this._renderFunction = this._render.bind(this);
  86694. this._scene = scene;
  86695. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  86696. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  86697. if (this._renderFunction) {
  86698. this._scene.registerBeforeRender(this._renderFunction);
  86699. }
  86700. }
  86701. if (color && this._renderLine) {
  86702. this._renderLine.color.copyFrom(color);
  86703. }
  86704. };
  86705. RayHelper.prototype.hide = function () {
  86706. if (this._renderFunction && this._scene) {
  86707. this._scene.unregisterBeforeRender(this._renderFunction);
  86708. this._scene = null;
  86709. this._renderFunction = null;
  86710. if (this._renderLine) {
  86711. this._renderLine.dispose();
  86712. this._renderLine = null;
  86713. }
  86714. this._renderPoints = [];
  86715. }
  86716. };
  86717. RayHelper.prototype._render = function () {
  86718. var ray = this.ray;
  86719. if (!ray) {
  86720. return;
  86721. }
  86722. var point = this._renderPoints[1];
  86723. var len = Math.min(ray.length, 1000000);
  86724. point.copyFrom(ray.direction);
  86725. point.scaleInPlace(len);
  86726. point.addInPlace(ray.origin);
  86727. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  86728. };
  86729. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  86730. this._attachedToMesh = mesh;
  86731. var ray = this.ray;
  86732. if (!ray) {
  86733. return;
  86734. }
  86735. if (!ray.direction) {
  86736. ray.direction = BABYLON.Vector3.Zero();
  86737. }
  86738. if (!ray.origin) {
  86739. ray.origin = BABYLON.Vector3.Zero();
  86740. }
  86741. if (length) {
  86742. ray.length = length;
  86743. }
  86744. if (!meshSpaceOrigin) {
  86745. meshSpaceOrigin = BABYLON.Vector3.Zero();
  86746. }
  86747. if (!meshSpaceDirection) {
  86748. // -1 so that this will work with Mesh.lookAt
  86749. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  86750. }
  86751. if (!this._meshSpaceDirection) {
  86752. this._meshSpaceDirection = meshSpaceDirection.clone();
  86753. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  86754. }
  86755. else {
  86756. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  86757. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  86758. }
  86759. if (!this._updateToMeshFunction) {
  86760. this._updateToMeshFunction = this._updateToMesh.bind(this);
  86761. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  86762. }
  86763. this._updateToMesh();
  86764. };
  86765. RayHelper.prototype.detachFromMesh = function () {
  86766. if (this._attachedToMesh) {
  86767. if (this._updateToMeshFunction) {
  86768. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  86769. }
  86770. this._attachedToMesh = null;
  86771. this._updateToMeshFunction = null;
  86772. }
  86773. };
  86774. RayHelper.prototype._updateToMesh = function () {
  86775. var ray = this.ray;
  86776. if (!this._attachedToMesh || !ray) {
  86777. return;
  86778. }
  86779. if (this._attachedToMesh._isDisposed) {
  86780. this.detachFromMesh();
  86781. return;
  86782. }
  86783. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  86784. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  86785. };
  86786. RayHelper.prototype.dispose = function () {
  86787. this.hide();
  86788. this.detachFromMesh();
  86789. this.ray = null;
  86790. };
  86791. return RayHelper;
  86792. }());
  86793. BABYLON.RayHelper = RayHelper;
  86794. })(BABYLON || (BABYLON = {}));
  86795. //# sourceMappingURL=babylon.rayHelper.js.map
  86796. var BABYLON;
  86797. (function (BABYLON) {
  86798. // load the inspector using require, if not present in the global namespace.
  86799. var DebugLayer = /** @class */ (function () {
  86800. function DebugLayer(scene) {
  86801. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  86802. this._scene = scene;
  86803. // load inspector using require, if it doesn't exist on the global namespace.
  86804. }
  86805. /** Creates the inspector window. */
  86806. DebugLayer.prototype._createInspector = function (config) {
  86807. if (config === void 0) { config = {}; }
  86808. var popup = config.popup || false;
  86809. var initialTab = config.initialTab || 0;
  86810. var parentElement = config.parentElement || null;
  86811. if (!this._inspector) {
  86812. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  86813. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  86814. } // else nothing to do,; instance is already existing
  86815. };
  86816. DebugLayer.prototype.isVisible = function () {
  86817. if (!this._inspector) {
  86818. return false;
  86819. }
  86820. return true;
  86821. };
  86822. DebugLayer.prototype.hide = function () {
  86823. if (this._inspector) {
  86824. try {
  86825. this._inspector.dispose();
  86826. }
  86827. catch (e) {
  86828. // If the inspector has been removed directly from the inspector tool
  86829. }
  86830. this.onPropertyChangedObservable.clear();
  86831. this._inspector = null;
  86832. }
  86833. };
  86834. /**
  86835. *
  86836. * Launch the debugLayer.
  86837. *
  86838. * initialTab:
  86839. * | Value | Tab Name |
  86840. * | --- | --- |
  86841. * | 0 | Scene |
  86842. * | 1 | Console |
  86843. * | 2 | Stats |
  86844. * | 3 | Textures |
  86845. * | 4 | Mesh |
  86846. * | 5 | Light |
  86847. * | 6 | Material |
  86848. * | 7 | GLTF |
  86849. * | 8 | GUI |
  86850. * | 9 | Physics |
  86851. * | 10 | Camera |
  86852. * | 11 | Audio |
  86853. *
  86854. */
  86855. DebugLayer.prototype.show = function (config) {
  86856. if (config === void 0) { config = {}; }
  86857. if (typeof this.BJSINSPECTOR == 'undefined') {
  86858. // Load inspector and add it to the DOM
  86859. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  86860. }
  86861. else {
  86862. // Otherwise creates the inspector
  86863. this._createInspector(config);
  86864. this.onPropertyChangedObservable = new BABYLON.Observable();
  86865. }
  86866. };
  86867. /**
  86868. * Gets the active tab
  86869. * @return the index of the active tab or -1 if the inspector is hidden
  86870. */
  86871. DebugLayer.prototype.getActiveTab = function () {
  86872. return this._inspector ? this._inspector.getActiveTabIndex() : -1;
  86873. };
  86874. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  86875. return DebugLayer;
  86876. }());
  86877. BABYLON.DebugLayer = DebugLayer;
  86878. })(BABYLON || (BABYLON = {}));
  86879. //# sourceMappingURL=babylon.debugLayer.js.map
  86880. var BABYLON;
  86881. (function (BABYLON) {
  86882. var Debug;
  86883. (function (Debug) {
  86884. /**
  86885. * Used to show the physics impostor around the specific mesh
  86886. */
  86887. var PhysicsViewer = /** @class */ (function () {
  86888. /**
  86889. * Creates a new PhysicsViewer
  86890. * @param scene defines the hosting scene
  86891. */
  86892. function PhysicsViewer(scene) {
  86893. /** @hidden */
  86894. this._impostors = [];
  86895. /** @hidden */
  86896. this._meshes = [];
  86897. /** @hidden */
  86898. this._numMeshes = 0;
  86899. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  86900. var physicEngine = this._scene.getPhysicsEngine();
  86901. if (physicEngine) {
  86902. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  86903. }
  86904. }
  86905. /** @hidden */
  86906. PhysicsViewer.prototype._updateDebugMeshes = function () {
  86907. var plugin = this._physicsEnginePlugin;
  86908. for (var i = 0; i < this._numMeshes; i++) {
  86909. var impostor = this._impostors[i];
  86910. if (!impostor) {
  86911. continue;
  86912. }
  86913. if (impostor.isDisposed) {
  86914. this.hideImpostor(this._impostors[i--]);
  86915. }
  86916. else {
  86917. var mesh = this._meshes[i];
  86918. if (mesh && plugin) {
  86919. plugin.syncMeshWithImpostor(mesh, impostor);
  86920. }
  86921. }
  86922. }
  86923. };
  86924. /**
  86925. * Renders a specified physic impostor
  86926. * @param impostor defines the impostor to render
  86927. */
  86928. PhysicsViewer.prototype.showImpostor = function (impostor) {
  86929. if (!this._scene) {
  86930. return;
  86931. }
  86932. for (var i = 0; i < this._numMeshes; i++) {
  86933. if (this._impostors[i] == impostor) {
  86934. return;
  86935. }
  86936. }
  86937. var debugMesh = this._getDebugMesh(impostor, this._scene);
  86938. if (debugMesh) {
  86939. this._impostors[this._numMeshes] = impostor;
  86940. this._meshes[this._numMeshes] = debugMesh;
  86941. if (this._numMeshes === 0) {
  86942. this._renderFunction = this._updateDebugMeshes.bind(this);
  86943. this._scene.registerBeforeRender(this._renderFunction);
  86944. }
  86945. this._numMeshes++;
  86946. }
  86947. };
  86948. /**
  86949. * Hides a specified physic impostor
  86950. * @param impostor defines the impostor to hide
  86951. */
  86952. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  86953. if (!impostor || !this._scene) {
  86954. return;
  86955. }
  86956. var removed = false;
  86957. for (var i = 0; i < this._numMeshes; i++) {
  86958. if (this._impostors[i] == impostor) {
  86959. var mesh = this._meshes[i];
  86960. if (!mesh) {
  86961. continue;
  86962. }
  86963. this._scene.removeMesh(mesh);
  86964. mesh.dispose();
  86965. this._numMeshes--;
  86966. if (this._numMeshes > 0) {
  86967. this._meshes[i] = this._meshes[this._numMeshes];
  86968. this._impostors[i] = this._impostors[this._numMeshes];
  86969. this._meshes[this._numMeshes] = null;
  86970. this._impostors[this._numMeshes] = null;
  86971. }
  86972. else {
  86973. this._meshes[0] = null;
  86974. this._impostors[0] = null;
  86975. }
  86976. removed = true;
  86977. break;
  86978. }
  86979. }
  86980. if (removed && this._numMeshes === 0) {
  86981. this._scene.unregisterBeforeRender(this._renderFunction);
  86982. }
  86983. };
  86984. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  86985. if (!this._debugMaterial) {
  86986. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  86987. this._debugMaterial.wireframe = true;
  86988. }
  86989. return this._debugMaterial;
  86990. };
  86991. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  86992. if (!this._debugBoxMesh) {
  86993. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  86994. this._debugBoxMesh.renderingGroupId = 1;
  86995. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  86996. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  86997. scene.removeMesh(this._debugBoxMesh);
  86998. }
  86999. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  87000. };
  87001. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  87002. if (!this._debugSphereMesh) {
  87003. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  87004. this._debugSphereMesh.renderingGroupId = 1;
  87005. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  87006. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  87007. scene.removeMesh(this._debugSphereMesh);
  87008. }
  87009. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  87010. };
  87011. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  87012. var mesh = null;
  87013. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  87014. mesh = this._getDebugBoxMesh(scene);
  87015. impostor.getBoxSizeToRef(mesh.scaling);
  87016. }
  87017. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  87018. mesh = this._getDebugSphereMesh(scene);
  87019. var radius = impostor.getRadius();
  87020. mesh.scaling.x = radius * 2;
  87021. mesh.scaling.y = radius * 2;
  87022. mesh.scaling.z = radius * 2;
  87023. }
  87024. return mesh;
  87025. };
  87026. /** Releases all resources */
  87027. PhysicsViewer.prototype.dispose = function () {
  87028. for (var i = 0; i < this._numMeshes; i++) {
  87029. this.hideImpostor(this._impostors[i]);
  87030. }
  87031. if (this._debugBoxMesh) {
  87032. this._debugBoxMesh.dispose();
  87033. }
  87034. if (this._debugSphereMesh) {
  87035. this._debugSphereMesh.dispose();
  87036. }
  87037. if (this._debugMaterial) {
  87038. this._debugMaterial.dispose();
  87039. }
  87040. this._impostors.length = 0;
  87041. this._scene = null;
  87042. this._physicsEnginePlugin = null;
  87043. };
  87044. return PhysicsViewer;
  87045. }());
  87046. Debug.PhysicsViewer = PhysicsViewer;
  87047. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  87048. })(BABYLON || (BABYLON = {}));
  87049. //# sourceMappingURL=babylon.physicsViewer.js.map
  87050. var BABYLON;
  87051. (function (BABYLON) {
  87052. var BoundingBoxRenderer = /** @class */ (function () {
  87053. function BoundingBoxRenderer(scene) {
  87054. this.frontColor = new BABYLON.Color3(1, 1, 1);
  87055. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  87056. this.showBackLines = true;
  87057. this.renderList = new BABYLON.SmartArray(32);
  87058. this._vertexBuffers = {};
  87059. this._scene = scene;
  87060. }
  87061. BoundingBoxRenderer.prototype._prepareRessources = function () {
  87062. if (this._colorShader) {
  87063. return;
  87064. }
  87065. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  87066. attributes: [BABYLON.VertexBuffer.PositionKind],
  87067. uniforms: ["world", "viewProjection", "color"]
  87068. });
  87069. var engine = this._scene.getEngine();
  87070. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  87071. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  87072. this._createIndexBuffer();
  87073. };
  87074. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  87075. var engine = this._scene.getEngine();
  87076. 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]);
  87077. };
  87078. BoundingBoxRenderer.prototype._rebuild = function () {
  87079. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  87080. if (vb) {
  87081. vb._rebuild();
  87082. }
  87083. this._createIndexBuffer();
  87084. };
  87085. BoundingBoxRenderer.prototype.reset = function () {
  87086. this.renderList.reset();
  87087. };
  87088. BoundingBoxRenderer.prototype.render = function () {
  87089. if (this.renderList.length === 0) {
  87090. return;
  87091. }
  87092. this._prepareRessources();
  87093. if (!this._colorShader.isReady()) {
  87094. return;
  87095. }
  87096. var engine = this._scene.getEngine();
  87097. engine.setDepthWrite(false);
  87098. this._colorShader._preBind();
  87099. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  87100. var boundingBox = this.renderList.data[boundingBoxIndex];
  87101. var min = boundingBox.minimum;
  87102. var max = boundingBox.maximum;
  87103. var diff = max.subtract(min);
  87104. var median = min.add(diff.scale(0.5));
  87105. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  87106. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  87107. .multiply(boundingBox.getWorldMatrix());
  87108. // VBOs
  87109. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  87110. if (this.showBackLines) {
  87111. // Back
  87112. engine.setDepthFunctionToGreaterOrEqual();
  87113. this._scene.resetCachedMaterial();
  87114. this._colorShader.setColor4("color", this.backColor.toColor4());
  87115. this._colorShader.bind(worldMatrix);
  87116. // Draw order
  87117. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  87118. }
  87119. // Front
  87120. engine.setDepthFunctionToLess();
  87121. this._scene.resetCachedMaterial();
  87122. this._colorShader.setColor4("color", this.frontColor.toColor4());
  87123. this._colorShader.bind(worldMatrix);
  87124. // Draw order
  87125. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  87126. }
  87127. this._colorShader.unbind();
  87128. engine.setDepthFunctionToLessOrEqual();
  87129. engine.setDepthWrite(true);
  87130. };
  87131. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  87132. this._prepareRessources();
  87133. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  87134. return;
  87135. }
  87136. var engine = this._scene.getEngine();
  87137. engine.setDepthWrite(false);
  87138. engine.setColorWrite(false);
  87139. this._colorShader._preBind();
  87140. var boundingBox = mesh._boundingInfo.boundingBox;
  87141. var min = boundingBox.minimum;
  87142. var max = boundingBox.maximum;
  87143. var diff = max.subtract(min);
  87144. var median = min.add(diff.scale(0.5));
  87145. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  87146. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  87147. .multiply(boundingBox.getWorldMatrix());
  87148. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  87149. engine.setDepthFunctionToLess();
  87150. this._scene.resetCachedMaterial();
  87151. this._colorShader.bind(worldMatrix);
  87152. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  87153. this._colorShader.unbind();
  87154. engine.setDepthFunctionToLessOrEqual();
  87155. engine.setDepthWrite(true);
  87156. engine.setColorWrite(true);
  87157. };
  87158. BoundingBoxRenderer.prototype.dispose = function () {
  87159. if (!this._colorShader) {
  87160. return;
  87161. }
  87162. this.renderList.dispose();
  87163. this._colorShader.dispose();
  87164. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  87165. if (buffer) {
  87166. buffer.dispose();
  87167. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  87168. }
  87169. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  87170. };
  87171. return BoundingBoxRenderer;
  87172. }());
  87173. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  87174. })(BABYLON || (BABYLON = {}));
  87175. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  87176. var BABYLON;
  87177. (function (BABYLON) {
  87178. /**
  87179. * Renders a layer on top of an existing scene
  87180. */
  87181. var UtilityLayerRenderer = /** @class */ (function () {
  87182. /**
  87183. * Instantiates a UtilityLayerRenderer
  87184. * @param originalScene the original scene that will be rendered on top of
  87185. */
  87186. function UtilityLayerRenderer(/** the original scene that will be rendered on top of */ originalScene) {
  87187. var _this = this;
  87188. this.originalScene = originalScene;
  87189. this._pointerCaptures = {};
  87190. this._lastPointerEvents = {};
  87191. /**
  87192. * If the utility layer should automatically be rendered on top of existing scene
  87193. */
  87194. this.shouldRender = true;
  87195. /**
  87196. * If set to true, only pointer down onPointerObservable events will be blocked when picking is occluded by original scene
  87197. */
  87198. this.onlyCheckPointerDownEvents = true;
  87199. /**
  87200. * If set to false, only pointerUp, pointerDown and pointerMove will be sent to the utilityLayerScene (false by default)
  87201. */
  87202. this.processAllEvents = false;
  87203. /**
  87204. * Observable raised when the pointer move from the utility layer scene to the main scene
  87205. */
  87206. this.onPointerOutObservable = new BABYLON.Observable();
  87207. // Create scene which will be rendered in the foreground and remove it from being referenced by engine to avoid interfering with existing app
  87208. this.utilityLayerScene = new BABYLON.Scene(originalScene.getEngine());
  87209. originalScene.getEngine().scenes.pop();
  87210. // Detach controls on utility scene, events will be fired by logic below to handle picking priority
  87211. this.utilityLayerScene.detachControl();
  87212. this._originalPointerObserver = originalScene.onPrePointerObservable.add(function (prePointerInfo, eventState) {
  87213. if (!_this.processAllEvents) {
  87214. if (prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERMOVE
  87215. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERUP
  87216. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERDOWN) {
  87217. return;
  87218. }
  87219. }
  87220. var utilityScenePick = prePointerInfo.ray ? _this.utilityLayerScene.pickWithRay(prePointerInfo.ray) : _this.utilityLayerScene.pick(originalScene.pointerX, originalScene.pointerY);
  87221. if (!prePointerInfo.ray && utilityScenePick) {
  87222. prePointerInfo.ray = utilityScenePick.ray;
  87223. }
  87224. // always fire the prepointer oversvable
  87225. _this.utilityLayerScene.onPrePointerObservable.notifyObservers(prePointerInfo);
  87226. // allow every non pointer down event to flow to the utility layer
  87227. if (_this.onlyCheckPointerDownEvents && prePointerInfo.type != BABYLON.PointerEventTypes.POINTERDOWN) {
  87228. if (!prePointerInfo.skipOnPointerObservable) {
  87229. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  87230. }
  87231. var pointerEvent = (prePointerInfo.event);
  87232. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent.pointerId]) {
  87233. _this._pointerCaptures[pointerEvent.pointerId] = false;
  87234. }
  87235. return;
  87236. }
  87237. if (_this.utilityLayerScene.autoClearDepthAndStencil) {
  87238. // If this layer is an overlay, check if this layer was hit and if so, skip pointer events for the main scene
  87239. if (utilityScenePick && utilityScenePick.hit) {
  87240. if (!prePointerInfo.skipOnPointerObservable) {
  87241. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  87242. }
  87243. prePointerInfo.skipOnPointerObservable = true;
  87244. }
  87245. }
  87246. else {
  87247. var originalScenePick = prePointerInfo.ray ? originalScene.pickWithRay(prePointerInfo.ray) : originalScene.pick(originalScene.pointerX, originalScene.pointerY);
  87248. var pointerEvent = (prePointerInfo.event);
  87249. // If the layer can be occluded by the original scene, only fire pointer events to the first layer that hit they ray
  87250. if (originalScenePick && utilityScenePick) {
  87251. // No pick in utility scene
  87252. if (utilityScenePick.distance === 0) {
  87253. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  87254. // We touched an utility mesh present in the main scene
  87255. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent);
  87256. prePointerInfo.skipOnPointerObservable = true;
  87257. }
  87258. else if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  87259. _this._pointerCaptures[pointerEvent.pointerId] = true;
  87260. }
  87261. }
  87262. // We pick something in utility scene or the pick in utility is closer than the one in main scene
  87263. if (!_this._pointerCaptures[pointerEvent.pointerId] && (utilityScenePick.distance < originalScenePick.distance || originalScenePick.distance === 0)) {
  87264. _this._notifyObservers(prePointerInfo, utilityScenePick, pointerEvent);
  87265. prePointerInfo.skipOnPointerObservable = utilityScenePick.distance > 0;
  87266. }
  87267. else if (!_this._pointerCaptures[pointerEvent.pointerId] && (utilityScenePick.distance > originalScenePick.distance)) {
  87268. // We have a pick in both scenes but main is closer than utility
  87269. // We touched an utility mesh present in the main scene
  87270. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  87271. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent);
  87272. prePointerInfo.skipOnPointerObservable = true;
  87273. }
  87274. else if (_this._lastPointerEvents[pointerEvent.pointerId]) {
  87275. // We need to send a last pointerup to the utilityLayerScene to make sure animations can complete
  87276. _this.onPointerOutObservable.notifyObservers(pointerEvent.pointerId);
  87277. delete _this._lastPointerEvents[pointerEvent.pointerId];
  87278. }
  87279. }
  87280. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent.pointerId]) {
  87281. _this._pointerCaptures[pointerEvent.pointerId] = false;
  87282. }
  87283. }
  87284. }
  87285. });
  87286. // Render directly on top of existing scene without clearing
  87287. this.utilityLayerScene.autoClear = false;
  87288. this._afterRenderObserver = this.originalScene.onAfterRenderObservable.add(function () {
  87289. if (_this.shouldRender) {
  87290. _this.render();
  87291. }
  87292. });
  87293. this._sceneDisposeObserver = this.originalScene.onDisposeObservable.add(function () {
  87294. _this.dispose();
  87295. });
  87296. this._updateCamera();
  87297. }
  87298. UtilityLayerRenderer.prototype._notifyObservers = function (prePointerInfo, pickInfo, pointerEvent) {
  87299. if (!prePointerInfo.skipOnPointerObservable) {
  87300. this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, pickInfo));
  87301. this._lastPointerEvents[pointerEvent.pointerId] = pointerEvent.pointerType;
  87302. }
  87303. };
  87304. /**
  87305. * Renders the utility layers scene on top of the original scene
  87306. */
  87307. UtilityLayerRenderer.prototype.render = function () {
  87308. this._updateCamera();
  87309. this.utilityLayerScene.render(false);
  87310. };
  87311. /**
  87312. * Disposes of the renderer
  87313. */
  87314. UtilityLayerRenderer.prototype.dispose = function () {
  87315. this.onPointerOutObservable.clear();
  87316. if (this._afterRenderObserver) {
  87317. this.originalScene.onAfterRenderObservable.remove(this._afterRenderObserver);
  87318. }
  87319. if (this._sceneDisposeObserver) {
  87320. this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver);
  87321. }
  87322. if (this._originalPointerObserver) {
  87323. this.originalScene.onPrePointerObservable.remove(this._originalPointerObserver);
  87324. }
  87325. this.utilityLayerScene.dispose();
  87326. };
  87327. UtilityLayerRenderer.prototype._updateCamera = function () {
  87328. this.utilityLayerScene.activeCamera = this.originalScene.activeCamera;
  87329. };
  87330. return UtilityLayerRenderer;
  87331. }());
  87332. BABYLON.UtilityLayerRenderer = UtilityLayerRenderer;
  87333. })(BABYLON || (BABYLON = {}));
  87334. //# sourceMappingURL=babylon.utilityLayerRenderer.js.map
  87335. //# sourceMappingURL=babylon.behavior.js.map
  87336. var BABYLON;
  87337. (function (BABYLON) {
  87338. /**
  87339. * A behavior that when attached to a mesh will allow the mesh to be dragged around the screen based on pointer events
  87340. */
  87341. var PointerDragBehavior = /** @class */ (function () {
  87342. /**
  87343. * Creates a pointer drag behavior that can be attached to a mesh
  87344. * @param options The drag axis or normal of the plane that will be dragged across. If no options are specified the drag plane will always face the ray's origin (eg. camera)
  87345. */
  87346. function PointerDragBehavior(options) {
  87347. this.options = options;
  87348. this._draggingID = -1;
  87349. // Debug mode will display drag planes to help visualize behavior
  87350. this._debugMode = false;
  87351. this._maxDragAngle = Math.PI / 5;
  87352. /**
  87353. * Fires each time the attached mesh is dragged with the pointer
  87354. * * delta between last drag position and current drag position in world space
  87355. * * dragDistance along the drag axis
  87356. * * dragPlaneNormal normal of the current drag plane used during the drag
  87357. * * dragPlanePoint in world space where the drag intersects the drag plane
  87358. */
  87359. this.onDragObservable = new BABYLON.Observable();
  87360. /**
  87361. * Fires each time a drag begins (eg. mouse down on mesh)
  87362. */
  87363. this.onDragStartObservable = new BABYLON.Observable();
  87364. /**
  87365. * Fires each time a drag ends (eg. mouse release after drag)
  87366. */
  87367. this.onDragEndObservable = new BABYLON.Observable();
  87368. /**
  87369. * If the attached mesh should be moved when dragged
  87370. */
  87371. this.moveAttached = true;
  87372. /**
  87373. * Mesh with the position where the drag plane should be placed
  87374. */
  87375. this._dragPlaneParent = null;
  87376. /**
  87377. * If the drag behavior will react to drag events
  87378. */
  87379. this.enabled = true;
  87380. var optionCount = 0;
  87381. if (options === undefined) {
  87382. options = {};
  87383. }
  87384. if (options.dragAxis) {
  87385. optionCount++;
  87386. }
  87387. if (options.dragPlaneNormal) {
  87388. optionCount++;
  87389. }
  87390. if (optionCount > 1) {
  87391. throw "Multiple drag modes specified in dragBehavior options. Only one expected";
  87392. }
  87393. }
  87394. Object.defineProperty(PointerDragBehavior.prototype, "name", {
  87395. /**
  87396. * The name of the behavior
  87397. */
  87398. get: function () {
  87399. return "PointerDrag";
  87400. },
  87401. enumerable: true,
  87402. configurable: true
  87403. });
  87404. /**
  87405. * Initializes the behavior
  87406. */
  87407. PointerDragBehavior.prototype.init = function () { };
  87408. /**
  87409. * Attaches the drag behavior the passed in mesh
  87410. * @param ownerNode The mesh that will be dragged around once attached
  87411. */
  87412. PointerDragBehavior.prototype.attach = function (ownerNode) {
  87413. var _this = this;
  87414. this._scene = ownerNode.getScene();
  87415. this._attachedNode = ownerNode;
  87416. // Initialize drag plane to not interfere with existing scene
  87417. if (!PointerDragBehavior._planeScene) {
  87418. if (this._debugMode) {
  87419. PointerDragBehavior._planeScene = this._scene;
  87420. }
  87421. else {
  87422. PointerDragBehavior._planeScene = new BABYLON.Scene(this._scene.getEngine());
  87423. this._scene.getEngine().scenes.pop();
  87424. }
  87425. }
  87426. this._dragPlane = BABYLON.Mesh.CreatePlane("pointerDragPlane", this._debugMode ? 1 : 10000, PointerDragBehavior._planeScene, false, BABYLON.Mesh.DOUBLESIDE);
  87427. // State of the drag
  87428. var dragging = false;
  87429. var lastPosition = new BABYLON.Vector3(0, 0, 0);
  87430. var delta = new BABYLON.Vector3(0, 0, 0);
  87431. var dragLength = 0;
  87432. var pickPredicate = function (m) {
  87433. return _this._attachedNode == m || m.isDescendantOf(_this._attachedNode);
  87434. };
  87435. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  87436. if (!_this.enabled) {
  87437. return;
  87438. }
  87439. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  87440. if (!dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  87441. _this._updateDragPlanePosition(pointerInfo.pickInfo.ray);
  87442. var pickedPoint = _this._pickWithRayOnDragPlane(pointerInfo.pickInfo.ray);
  87443. if (pickedPoint) {
  87444. dragging = true;
  87445. _this._draggingID = pointerInfo.event.pointerId;
  87446. lastPosition.copyFrom(pickedPoint);
  87447. _this.onDragStartObservable.notifyObservers({ dragPlanePoint: pickedPoint });
  87448. }
  87449. }
  87450. }
  87451. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  87452. if (_this._draggingID == pointerInfo.event.pointerId) {
  87453. dragging = false;
  87454. _this._draggingID = -1;
  87455. _this.onDragEndObservable.notifyObservers({ dragPlanePoint: lastPosition });
  87456. }
  87457. }
  87458. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  87459. if (_this._draggingID == pointerInfo.event.pointerId && dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {
  87460. var pickedPoint = _this._pickWithRayOnDragPlane(pointerInfo.pickInfo.ray);
  87461. // Get angle between drag plane and ray. Only update the drag plane at non steep angles to avoid jumps in delta position
  87462. var angle = Math.acos(BABYLON.Vector3.Dot(_this._dragPlane.forward, pointerInfo.pickInfo.ray.direction));
  87463. if (angle < _this._maxDragAngle) {
  87464. _this._updateDragPlanePosition(pointerInfo.pickInfo.ray);
  87465. }
  87466. if (pickedPoint) {
  87467. // depending on the drag mode option drag accordingly
  87468. if (_this.options.dragAxis) {
  87469. // Convert local drag axis to world
  87470. var worldDragAxis = BABYLON.Vector3.TransformCoordinates(_this.options.dragAxis, _this._attachedNode.getWorldMatrix().getRotationMatrix());
  87471. // Project delta drag from the drag plane onto the drag axis
  87472. dragLength = BABYLON.Vector3.Dot(pickedPoint.subtract(lastPosition), worldDragAxis);
  87473. worldDragAxis.scaleToRef(dragLength, delta);
  87474. }
  87475. else {
  87476. dragLength = delta.length();
  87477. pickedPoint.subtractToRef(lastPosition, delta);
  87478. }
  87479. if (_this.moveAttached) {
  87480. _this._attachedNode.position.addInPlace(delta);
  87481. }
  87482. _this.onDragObservable.notifyObservers({ dragDistance: dragLength, delta: delta, dragPlanePoint: pickedPoint, dragPlaneNormal: _this._dragPlane.forward });
  87483. lastPosition.copyFrom(pickedPoint);
  87484. }
  87485. }
  87486. }
  87487. });
  87488. };
  87489. PointerDragBehavior.prototype._pickWithRayOnDragPlane = function (ray) {
  87490. var _this = this;
  87491. if (!ray) {
  87492. return null;
  87493. }
  87494. var pickResult = PointerDragBehavior._planeScene.pickWithRay(ray, function (m) { return m == _this._dragPlane; });
  87495. if (pickResult && pickResult.hit && pickResult.pickedMesh && pickResult.pickedPoint) {
  87496. return pickResult.pickedPoint;
  87497. }
  87498. else {
  87499. return null;
  87500. }
  87501. };
  87502. // Position the drag plane based on the attached mesh position, for single axis rotate the plane along the axis to face the camera
  87503. PointerDragBehavior.prototype._updateDragPlanePosition = function (ray) {
  87504. var pointA = this._dragPlaneParent ? this._dragPlaneParent.absolutePosition : this._attachedNode.absolutePosition;
  87505. if (this.options.dragAxis) {
  87506. var localAxis = BABYLON.Vector3.TransformCoordinates(this.options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix());
  87507. // Calculate plane normal in direction of camera but perpendicular to drag axis
  87508. var pointB = pointA.add(localAxis); // towards drag axis
  87509. var pointC = pointA.add(ray.origin.subtract(pointA).normalize()); // towards camera
  87510. // Get perpendicular line from direction to camera and drag axis
  87511. var lineA = pointB.subtract(pointA);
  87512. var lineB = pointC.subtract(pointA);
  87513. var perpLine = BABYLON.Vector3.Cross(lineA, lineB);
  87514. // Get perpendicular line from previous result and drag axis to adjust lineB to be perpendiculat to camera
  87515. var norm = BABYLON.Vector3.Cross(lineA, perpLine).normalize();
  87516. this._dragPlane.position.copyFrom(pointA);
  87517. this._dragPlane.lookAt(pointA.subtract(norm));
  87518. }
  87519. else if (this.options.dragPlaneNormal) {
  87520. this._dragPlane.position.copyFrom(pointA);
  87521. this._dragPlane.lookAt(pointA.subtract(this.options.dragPlaneNormal));
  87522. }
  87523. else {
  87524. this._dragPlane.position.copyFrom(pointA);
  87525. this._dragPlane.lookAt(ray.origin);
  87526. }
  87527. this._dragPlane.computeWorldMatrix(true);
  87528. };
  87529. /**
  87530. * Detaches the behavior from the mesh
  87531. */
  87532. PointerDragBehavior.prototype.detach = function () {
  87533. if (this._pointerObserver) {
  87534. this._scene.onPointerObservable.remove(this._pointerObserver);
  87535. }
  87536. };
  87537. return PointerDragBehavior;
  87538. }());
  87539. BABYLON.PointerDragBehavior = PointerDragBehavior;
  87540. })(BABYLON || (BABYLON = {}));
  87541. //# sourceMappingURL=babylon.pointerDragBehavior.js.map
  87542. var BABYLON;
  87543. (function (BABYLON) {
  87544. /**
  87545. * Renders gizmos on top of an existing scene which provide controls for position, rotation, etc.
  87546. */
  87547. var Gizmo = /** @class */ (function () {
  87548. /**
  87549. * Creates a gizmo
  87550. * @param gizmoLayer The utility layer the gizmo will be added to
  87551. */
  87552. function Gizmo(/** The utility layer the gizmo will be added to */ gizmoLayer) {
  87553. var _this = this;
  87554. this.gizmoLayer = gizmoLayer;
  87555. /**
  87556. * When set, the gizmo will always appear the same size no matter where the camera is (default: false)
  87557. */
  87558. this._updateScale = true;
  87559. this._interactionsEnabled = true;
  87560. this._rootMesh = new BABYLON.Mesh("gizmoRootNode", gizmoLayer.utilityLayerScene);
  87561. this._beforeRenderObserver = this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add(function () {
  87562. if (_this._updateScale && _this.gizmoLayer.utilityLayerScene.activeCamera && _this.attachedMesh) {
  87563. var dist = _this.attachedMesh.position.subtract(_this.gizmoLayer.utilityLayerScene.activeCamera.position).length() / 3;
  87564. _this._rootMesh.scaling.set(dist, dist, dist);
  87565. }
  87566. if (_this.attachedMesh) {
  87567. _this._rootMesh.position.copyFrom(_this.attachedMesh.position);
  87568. }
  87569. });
  87570. }
  87571. Gizmo.prototype._onInteractionsEnabledChanged = function (value) {
  87572. };
  87573. Object.defineProperty(Gizmo.prototype, "interactionsEnabled", {
  87574. get: function () {
  87575. return this._interactionsEnabled;
  87576. },
  87577. /**
  87578. * If interactions are enabled with this gizmo. (eg. dragging/rotation)
  87579. */
  87580. set: function (value) {
  87581. this._interactionsEnabled = value;
  87582. this._onInteractionsEnabledChanged(value);
  87583. },
  87584. enumerable: true,
  87585. configurable: true
  87586. });
  87587. /**
  87588. * Disposes of the gizmo
  87589. */
  87590. Gizmo.prototype.dispose = function () {
  87591. this._rootMesh.dispose();
  87592. if (this._beforeRenderObserver) {
  87593. this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  87594. }
  87595. };
  87596. return Gizmo;
  87597. }());
  87598. BABYLON.Gizmo = Gizmo;
  87599. })(BABYLON || (BABYLON = {}));
  87600. //# sourceMappingURL=babylon.gizmo.js.map
  87601. var BABYLON;
  87602. (function (BABYLON) {
  87603. /**
  87604. * Single axis drag gizmo
  87605. */
  87606. var AxisDragGizmo = /** @class */ (function (_super) {
  87607. __extends(AxisDragGizmo, _super);
  87608. /**
  87609. * Creates an AxisDragGizmo
  87610. * @param gizmoLayer The utility layer the gizmo will be added to
  87611. * @param dragAxis The axis which the gizmo will be able to drag on
  87612. * @param color The color of the gizmo
  87613. */
  87614. function AxisDragGizmo(gizmoLayer, dragAxis, color) {
  87615. var _this = _super.call(this, gizmoLayer) || this;
  87616. // Create Material
  87617. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  87618. coloredMaterial.disableLighting = true;
  87619. coloredMaterial.emissiveColor = color;
  87620. // Build mesh on root node
  87621. var arrowMesh = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameterTop: 0, height: 2, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  87622. var arrowTail = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameter: 0.03, height: 0.2, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  87623. _this._rootMesh.addChild(arrowMesh);
  87624. _this._rootMesh.addChild(arrowTail);
  87625. // Position arrow pointing in its drag axis
  87626. arrowMesh.scaling.scaleInPlace(0.1);
  87627. arrowMesh.material = coloredMaterial;
  87628. arrowMesh.rotation.x = Math.PI / 2;
  87629. arrowMesh.position.z += 0.3;
  87630. arrowTail.rotation.x = Math.PI / 2;
  87631. arrowTail.material = coloredMaterial;
  87632. arrowTail.position.z += 0.2;
  87633. _this._rootMesh.lookAt(_this._rootMesh.position.subtract(dragAxis));
  87634. // Add drag behavior to handle events when the gizmo is dragged
  87635. _this._dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: new BABYLON.Vector3(0, 0, 1) });
  87636. _this._dragBehavior.moveAttached = false;
  87637. _this._rootMesh.addBehavior(_this._dragBehavior);
  87638. _this._dragBehavior.onDragObservable.add(function (event) {
  87639. if (!_this.interactionsEnabled) {
  87640. return;
  87641. }
  87642. if (_this.attachedMesh) {
  87643. _this.attachedMesh.position.addInPlace(event.delta);
  87644. }
  87645. });
  87646. return _this;
  87647. }
  87648. AxisDragGizmo.prototype._onInteractionsEnabledChanged = function (value) {
  87649. this._dragBehavior.enabled = value;
  87650. };
  87651. /**
  87652. * Disposes of the gizmo
  87653. */
  87654. AxisDragGizmo.prototype.dispose = function () {
  87655. this._dragBehavior.detach();
  87656. _super.prototype.dispose.call(this);
  87657. };
  87658. return AxisDragGizmo;
  87659. }(BABYLON.Gizmo));
  87660. BABYLON.AxisDragGizmo = AxisDragGizmo;
  87661. })(BABYLON || (BABYLON = {}));
  87662. //# sourceMappingURL=babylon.axisDragGizmo.js.map
  87663. var BABYLON;
  87664. (function (BABYLON) {
  87665. /**
  87666. * Single axis scale gizmo
  87667. */
  87668. var AxisScaleGizmo = /** @class */ (function (_super) {
  87669. __extends(AxisScaleGizmo, _super);
  87670. /**
  87671. * Creates an AxisScaleGizmo
  87672. * @param gizmoLayer The utility layer the gizmo will be added to
  87673. * @param dragAxis The axis which the gizmo will be able to scale on
  87674. * @param color The color of the gizmo
  87675. */
  87676. function AxisScaleGizmo(gizmoLayer, dragAxis, color) {
  87677. var _this = _super.call(this, gizmoLayer) || this;
  87678. // Create Material
  87679. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  87680. coloredMaterial.disableLighting = true;
  87681. coloredMaterial.emissiveColor = color;
  87682. // Build mesh on root node
  87683. var arrowMesh = BABYLON.MeshBuilder.CreateBox("yPosMesh", { size: 1 }, gizmoLayer.utilityLayerScene);
  87684. var arrowTail = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameter: 0.03, height: 0.2, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  87685. _this._rootMesh.addChild(arrowMesh);
  87686. _this._rootMesh.addChild(arrowTail);
  87687. // Position arrow pointing in its drag axis
  87688. arrowMesh.scaling.scaleInPlace(0.1);
  87689. arrowMesh.material = coloredMaterial;
  87690. arrowMesh.rotation.x = Math.PI / 2;
  87691. arrowMesh.position.z += 0.3;
  87692. arrowTail.rotation.x = Math.PI / 2;
  87693. arrowTail.material = coloredMaterial;
  87694. arrowTail.position.z += 0.2;
  87695. _this._rootMesh.lookAt(_this._rootMesh.position.subtract(dragAxis));
  87696. // Add drag behavior to handle events when the gizmo is dragged
  87697. _this._dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: new BABYLON.Vector3(0, 0, 1) });
  87698. _this._dragBehavior.moveAttached = false;
  87699. _this._rootMesh.addBehavior(_this._dragBehavior);
  87700. _this._dragBehavior.onDragObservable.add(function (event) {
  87701. if (!_this.interactionsEnabled) {
  87702. return;
  87703. }
  87704. if (_this.attachedMesh) {
  87705. _this.attachedMesh.scaling.addInPlace(event.delta);
  87706. }
  87707. });
  87708. return _this;
  87709. }
  87710. AxisScaleGizmo.prototype._onInteractionsEnabledChanged = function (value) {
  87711. this._dragBehavior.enabled = value;
  87712. };
  87713. /**
  87714. * Disposes of the gizmo
  87715. */
  87716. AxisScaleGizmo.prototype.dispose = function () {
  87717. this._dragBehavior.detach();
  87718. _super.prototype.dispose.call(this);
  87719. };
  87720. return AxisScaleGizmo;
  87721. }(BABYLON.Gizmo));
  87722. BABYLON.AxisScaleGizmo = AxisScaleGizmo;
  87723. })(BABYLON || (BABYLON = {}));
  87724. //# sourceMappingURL=babylon.axisScaleGizmo.js.map
  87725. var BABYLON;
  87726. (function (BABYLON) {
  87727. /**
  87728. * Single plane rotation gizmo
  87729. */
  87730. var PlaneRotationGizmo = /** @class */ (function (_super) {
  87731. __extends(PlaneRotationGizmo, _super);
  87732. /**
  87733. * Creates a PlaneRotationGizmo
  87734. * @param gizmoLayer The utility layer the gizmo will be added to
  87735. * @param planeNormal The normal of the plane which the gizmo will be able to rotate on
  87736. * @param color The color of the gizmo
  87737. */
  87738. function PlaneRotationGizmo(gizmoLayer, planeNormal, color) {
  87739. var _this = _super.call(this, gizmoLayer) || this;
  87740. // Create Material
  87741. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  87742. coloredMaterial.disableLighting = true;
  87743. coloredMaterial.emissiveColor = color;
  87744. // Build mesh on root node
  87745. var rotationMesh = BABYLON.Mesh.CreateTorus("torus", 3, 0.3, 20, gizmoLayer.utilityLayerScene, false);
  87746. _this._rootMesh.addChild(rotationMesh);
  87747. // Position arrow pointing in its drag axis
  87748. rotationMesh.scaling.scaleInPlace(0.1);
  87749. rotationMesh.material = coloredMaterial;
  87750. rotationMesh.rotation.x = Math.PI / 2;
  87751. _this._rootMesh.lookAt(_this._rootMesh.position.subtract(planeNormal));
  87752. // Add drag behavior to handle events when the gizmo is dragged
  87753. _this._dragBehavior = new BABYLON.PointerDragBehavior({ dragPlaneNormal: planeNormal });
  87754. _this._dragBehavior.moveAttached = false;
  87755. _this._rootMesh.addBehavior(_this._dragBehavior);
  87756. var lastDragPosition = null;
  87757. _this._dragBehavior.onDragStartObservable.add(function (e) {
  87758. if (!_this.interactionsEnabled) {
  87759. return;
  87760. }
  87761. lastDragPosition = e.dragPlanePoint;
  87762. });
  87763. _this._dragBehavior.onDragObservable.add(function (event) {
  87764. if (!_this.interactionsEnabled) {
  87765. return;
  87766. }
  87767. if (_this.attachedMesh && lastDragPosition) {
  87768. if (!_this.attachedMesh.rotationQuaternion) {
  87769. _this.attachedMesh.rotationQuaternion = new BABYLON.Quaternion();
  87770. }
  87771. // Calc angle over full 360 degree (https://stackoverflow.com/questions/43493711/the-angle-between-two-3d-vectors-with-a-result-range-0-360)
  87772. var newVector = event.dragPlanePoint.subtract(_this.attachedMesh.position).normalize();
  87773. var originalVector = lastDragPosition.subtract(_this.attachedMesh.position).normalize();
  87774. var cross = BABYLON.Vector3.Cross(newVector, originalVector);
  87775. var dot = BABYLON.Vector3.Dot(newVector, originalVector);
  87776. var angle = Math.atan2(cross.length(), dot);
  87777. var up = planeNormal.clone();
  87778. // Flip up vector depending on which side the camera is on
  87779. if (gizmoLayer.utilityLayerScene.activeCamera) {
  87780. var camVec = gizmoLayer.utilityLayerScene.activeCamera.position.subtract(_this.attachedMesh.position);
  87781. if (BABYLON.Vector3.Dot(camVec, up) > 0) {
  87782. up.scaleInPlace(-1);
  87783. }
  87784. }
  87785. var halfCircleSide = BABYLON.Vector3.Dot(up, cross) > 0.0;
  87786. if (halfCircleSide)
  87787. angle = -angle;
  87788. // Convert angle and axis to quaternion (http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm)
  87789. var quaternionCoefficient = Math.sin(angle / 2);
  87790. var amountToRotate = new BABYLON.Quaternion(up.x * quaternionCoefficient, up.y * quaternionCoefficient, up.z * quaternionCoefficient, Math.cos(angle / 2));
  87791. // Rotate selected mesh quaternion over fixed axis
  87792. amountToRotate.multiplyToRef(_this.attachedMesh.rotationQuaternion, _this.attachedMesh.rotationQuaternion);
  87793. lastDragPosition = event.dragPlanePoint;
  87794. }
  87795. });
  87796. return _this;
  87797. }
  87798. PlaneRotationGizmo.prototype._onInteractionsEnabledChanged = function (value) {
  87799. this._dragBehavior.enabled = value;
  87800. };
  87801. /**
  87802. * Disposes of the gizmo
  87803. */
  87804. PlaneRotationGizmo.prototype.dispose = function () {
  87805. this._dragBehavior.detach();
  87806. _super.prototype.dispose.call(this);
  87807. };
  87808. return PlaneRotationGizmo;
  87809. }(BABYLON.Gizmo));
  87810. BABYLON.PlaneRotationGizmo = PlaneRotationGizmo;
  87811. })(BABYLON || (BABYLON = {}));
  87812. //# sourceMappingURL=babylon.planeRotationGizmo.js.map
  87813. var BABYLON;
  87814. (function (BABYLON) {
  87815. /**
  87816. * Gizmo that enables dragging a mesh along 3 axis
  87817. */
  87818. var PositionGizmo = /** @class */ (function (_super) {
  87819. __extends(PositionGizmo, _super);
  87820. /**
  87821. * Creates a PositionGizmo
  87822. * @param gizmoLayer The utility layer the gizmo will be added to
  87823. */
  87824. function PositionGizmo(gizmoLayer) {
  87825. var _this = _super.call(this, gizmoLayer) || this;
  87826. _this._xDrag = new BABYLON.AxisDragGizmo(gizmoLayer, new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.FromHexString("#00b894"));
  87827. _this._yDrag = new BABYLON.AxisDragGizmo(gizmoLayer, new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.FromHexString("#d63031"));
  87828. _this._zDrag = new BABYLON.AxisDragGizmo(gizmoLayer, new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.FromHexString("#0984e3"));
  87829. return _this;
  87830. }
  87831. Object.defineProperty(PositionGizmo.prototype, "attachedMesh", {
  87832. set: function (mesh) {
  87833. this._xDrag.attachedMesh = mesh;
  87834. this._yDrag.attachedMesh = mesh;
  87835. this._zDrag.attachedMesh = mesh;
  87836. },
  87837. enumerable: true,
  87838. configurable: true
  87839. });
  87840. PositionGizmo.prototype._onInteractionsEnabledChanged = function (value) {
  87841. this._xDrag.interactionsEnabled = value;
  87842. this._yDrag.interactionsEnabled = value;
  87843. this._zDrag.interactionsEnabled = value;
  87844. };
  87845. /**
  87846. * Disposes of the gizmo
  87847. */
  87848. PositionGizmo.prototype.dispose = function () {
  87849. this._xDrag.dispose();
  87850. this._yDrag.dispose();
  87851. this._zDrag.dispose();
  87852. };
  87853. return PositionGizmo;
  87854. }(BABYLON.Gizmo));
  87855. BABYLON.PositionGizmo = PositionGizmo;
  87856. })(BABYLON || (BABYLON = {}));
  87857. //# sourceMappingURL=babylon.positionGizmo.js.map
  87858. var BABYLON;
  87859. (function (BABYLON) {
  87860. /**
  87861. * Gizmo that enables rotating a mesh along 3 axis
  87862. */
  87863. var RotationGizmo = /** @class */ (function (_super) {
  87864. __extends(RotationGizmo, _super);
  87865. /**
  87866. * Creates a RotationGizmo
  87867. * @param gizmoLayer The utility layer the gizmo will be added to
  87868. */
  87869. function RotationGizmo(gizmoLayer) {
  87870. var _this = _super.call(this, gizmoLayer) || this;
  87871. _this._xDrag = new BABYLON.PlaneRotationGizmo(gizmoLayer, new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.FromHexString("#00b894"));
  87872. _this._yDrag = new BABYLON.PlaneRotationGizmo(gizmoLayer, new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.FromHexString("#d63031"));
  87873. _this._zDrag = new BABYLON.PlaneRotationGizmo(gizmoLayer, new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.FromHexString("#0984e3"));
  87874. return _this;
  87875. }
  87876. Object.defineProperty(RotationGizmo.prototype, "attachedMesh", {
  87877. set: function (mesh) {
  87878. this._xDrag.attachedMesh = mesh;
  87879. this._yDrag.attachedMesh = mesh;
  87880. this._zDrag.attachedMesh = mesh;
  87881. },
  87882. enumerable: true,
  87883. configurable: true
  87884. });
  87885. RotationGizmo.prototype._onInteractionsEnabledChanged = function (value) {
  87886. this._xDrag.interactionsEnabled = value;
  87887. this._yDrag.interactionsEnabled = value;
  87888. this._zDrag.interactionsEnabled = value;
  87889. };
  87890. /**
  87891. * Disposes of the gizmo
  87892. */
  87893. RotationGizmo.prototype.dispose = function () {
  87894. this._xDrag.dispose();
  87895. this._yDrag.dispose();
  87896. this._zDrag.dispose();
  87897. };
  87898. return RotationGizmo;
  87899. }(BABYLON.Gizmo));
  87900. BABYLON.RotationGizmo = RotationGizmo;
  87901. })(BABYLON || (BABYLON = {}));
  87902. //# sourceMappingURL=babylon.rotationGizmo.js.map
  87903. var BABYLON;
  87904. (function (BABYLON) {
  87905. /**
  87906. * Gizmo that enables scaling a mesh along 3 axis
  87907. */
  87908. var ScaleGizmo = /** @class */ (function (_super) {
  87909. __extends(ScaleGizmo, _super);
  87910. /**
  87911. * Creates a ScaleGizmo
  87912. * @param gizmoLayer The utility layer the gizmo will be added to
  87913. */
  87914. function ScaleGizmo(gizmoLayer) {
  87915. var _this = _super.call(this, gizmoLayer) || this;
  87916. _this._xDrag = new BABYLON.AxisScaleGizmo(gizmoLayer, new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.FromHexString("#00b894"));
  87917. _this._yDrag = new BABYLON.AxisScaleGizmo(gizmoLayer, new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.FromHexString("#d63031"));
  87918. _this._zDrag = new BABYLON.AxisScaleGizmo(gizmoLayer, new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.FromHexString("#0984e3"));
  87919. return _this;
  87920. }
  87921. Object.defineProperty(ScaleGizmo.prototype, "attachedMesh", {
  87922. set: function (mesh) {
  87923. this._xDrag.attachedMesh = mesh;
  87924. this._yDrag.attachedMesh = mesh;
  87925. this._zDrag.attachedMesh = mesh;
  87926. },
  87927. enumerable: true,
  87928. configurable: true
  87929. });
  87930. ScaleGizmo.prototype._onInteractionsEnabledChanged = function (value) {
  87931. this._xDrag.interactionsEnabled = value;
  87932. this._yDrag.interactionsEnabled = value;
  87933. this._zDrag.interactionsEnabled = value;
  87934. };
  87935. /**
  87936. * Disposes of the gizmo
  87937. */
  87938. ScaleGizmo.prototype.dispose = function () {
  87939. this._xDrag.dispose();
  87940. this._yDrag.dispose();
  87941. this._zDrag.dispose();
  87942. };
  87943. return ScaleGizmo;
  87944. }(BABYLON.Gizmo));
  87945. BABYLON.ScaleGizmo = ScaleGizmo;
  87946. })(BABYLON || (BABYLON = {}));
  87947. //# sourceMappingURL=babylon.scaleGizmo.js.map
  87948. var BABYLON;
  87949. (function (BABYLON) {
  87950. /**
  87951. * Bounding box gizmo
  87952. */
  87953. var BoundingBoxGizmo = /** @class */ (function (_super) {
  87954. __extends(BoundingBoxGizmo, _super);
  87955. /**
  87956. * Creates an BoundingBoxGizmo
  87957. * @param gizmoLayer The utility layer the gizmo will be added to
  87958. * @param color The color of the gizmo
  87959. */
  87960. function BoundingBoxGizmo(gizmoLayer, color) {
  87961. var _this = _super.call(this, gizmoLayer) || this;
  87962. _this._boundingDimensions = new BABYLON.Vector3(1, 1, 1);
  87963. _this._renderObserver = null;
  87964. // Do not update the gizmo's scale so it has a fixed size to the object its attached to
  87965. _this._updateScale = false;
  87966. // Create Material
  87967. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  87968. coloredMaterial.disableLighting = true;
  87969. coloredMaterial.emissiveColor = color;
  87970. // Build bounding box out of lines
  87971. _this._lineBoundingBox = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  87972. _this._lineBoundingBox.rotationQuaternion = new BABYLON.Quaternion();
  87973. var lines = [];
  87974. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0)] }, gizmoLayer.utilityLayerScene));
  87975. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  87976. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  87977. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  87978. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  87979. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, _this._boundingDimensions.y, 0), new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  87980. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, _this._boundingDimensions.y, 0), new BABYLON.Vector3(0, _this._boundingDimensions.y, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  87981. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, _this._boundingDimensions.z), new BABYLON.Vector3(_this._boundingDimensions.x, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  87982. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, _this._boundingDimensions.z), new BABYLON.Vector3(0, _this._boundingDimensions.y, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  87983. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, _this._boundingDimensions.z), new BABYLON.Vector3(0, _this._boundingDimensions.y, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  87984. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, _this._boundingDimensions.z), new BABYLON.Vector3(_this._boundingDimensions.x, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  87985. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, _this._boundingDimensions.z), new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  87986. lines.forEach(function (l) {
  87987. l.color = color;
  87988. l.position.addInPlace(new BABYLON.Vector3(-_this._boundingDimensions.x / 2, -_this._boundingDimensions.y / 2, -_this._boundingDimensions.z / 2));
  87989. l.isPickable = false;
  87990. _this._lineBoundingBox.addChild(l);
  87991. });
  87992. _this._rootMesh.addChild(_this._lineBoundingBox);
  87993. // Create rotation spheres
  87994. _this._rotateSpheresParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  87995. _this._rotateSpheresParent.rotationQuaternion = new BABYLON.Quaternion();
  87996. var _loop_1 = function (i_1) {
  87997. var sphere = BABYLON.MeshBuilder.CreateSphere("", { diameter: 0.1 }, gizmoLayer.utilityLayerScene);
  87998. sphere.rotationQuaternion = new BABYLON.Quaternion();
  87999. sphere.material = coloredMaterial;
  88000. // Drag behavior
  88001. _dragBehavior = new BABYLON.PointerDragBehavior({});
  88002. _dragBehavior.moveAttached = false;
  88003. sphere.addBehavior(_dragBehavior);
  88004. _dragBehavior.onDragObservable.add(function (event) {
  88005. if (_this.attachedMesh) {
  88006. var worldDragDirection = sphere.forward;
  88007. // Project the world right on to the drag plane
  88008. var toSub = event.dragPlaneNormal.scale(BABYLON.Vector3.Dot(event.dragPlaneNormal, worldDragDirection));
  88009. var dragAxis = worldDragDirection.subtract(toSub).normalizeToNew();
  88010. // project drag delta on to the resulting drag axis and rotate based on that
  88011. var projectDist = BABYLON.Vector3.Dot(dragAxis, event.delta);
  88012. // Rotate based on axis
  88013. if (i_1 >= 8) {
  88014. _this.attachedMesh.rotation.z -= projectDist;
  88015. }
  88016. else if (i_1 >= 4) {
  88017. _this.attachedMesh.rotation.y -= projectDist;
  88018. }
  88019. else {
  88020. _this.attachedMesh.rotation.x -= projectDist;
  88021. }
  88022. }
  88023. });
  88024. // Selection/deselection
  88025. _dragBehavior.onDragStartObservable.add(function () {
  88026. _this._selectNode(sphere);
  88027. });
  88028. _dragBehavior.onDragEndObservable.add(function () {
  88029. _this._selectNode(null);
  88030. });
  88031. this_1._rotateSpheresParent.addChild(sphere);
  88032. };
  88033. var this_1 = this, _dragBehavior;
  88034. for (var i_1 = 0; i_1 < 12; i_1++) {
  88035. _loop_1(i_1);
  88036. }
  88037. _this._rootMesh.addChild(_this._rotateSpheresParent);
  88038. // Create scale cubes
  88039. _this._scaleBoxesParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  88040. _this._scaleBoxesParent.rotationQuaternion = new BABYLON.Quaternion();
  88041. for (var i = 0; i < 2; i++) {
  88042. for (var j = 0; j < 2; j++) {
  88043. var _loop_2 = function () {
  88044. var box = BABYLON.MeshBuilder.CreateBox("", { size: 0.1 }, gizmoLayer.utilityLayerScene);
  88045. box.material = coloredMaterial;
  88046. // Dragging logic
  88047. var dragAxis = new BABYLON.Vector3(i == 0 ? -1 : 1, j == 0 ? -1 : 1, k == 0 ? -1 : 1);
  88048. _dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  88049. _dragBehavior.moveAttached = false;
  88050. box.addBehavior(_dragBehavior);
  88051. _dragBehavior.onDragObservable.add(function (event) {
  88052. if (_this.attachedMesh) {
  88053. // Current boudning box dimensions
  88054. var boundingInfo = _this.attachedMesh.getBoundingInfo().boundingBox;
  88055. var boundBoxDimensions = boundingInfo.maximum.subtract(boundingInfo.minimum).multiplyInPlace(_this.attachedMesh.scaling);
  88056. // Get the change in bounding box size/2 and add this to the mesh's position to offset from scaling with center pivot point
  88057. var deltaScale = new BABYLON.Vector3(event.dragDistance, event.dragDistance, event.dragDistance);
  88058. var scaleRatio = deltaScale.divide(_this.attachedMesh.scaling).scaleInPlace(0.5);
  88059. var moveDirection = boundBoxDimensions.multiply(scaleRatio).multiplyInPlace(dragAxis);
  88060. var worldMoveDirection = BABYLON.Vector3.TransformCoordinates(moveDirection, _this.attachedMesh.getWorldMatrix().getRotationMatrix());
  88061. // Update scale and position
  88062. _this.attachedMesh.scaling.addInPlace(deltaScale);
  88063. _this.attachedMesh.position.addInPlace(worldMoveDirection);
  88064. }
  88065. });
  88066. // Selection/deselection
  88067. _dragBehavior.onDragStartObservable.add(function () {
  88068. _this._selectNode(box);
  88069. });
  88070. _dragBehavior.onDragEndObservable.add(function () {
  88071. _this._selectNode(null);
  88072. });
  88073. this_2._scaleBoxesParent.addChild(box);
  88074. };
  88075. var this_2 = this, _dragBehavior;
  88076. for (var k = 0; k < 2; k++) {
  88077. _loop_2();
  88078. }
  88079. }
  88080. }
  88081. _this._rootMesh.addChild(_this._scaleBoxesParent);
  88082. // Update bounding box positions
  88083. _this._renderObserver = _this.gizmoLayer.originalScene.onBeforeRenderObservable.add(function () {
  88084. _this._updateBoundingBox();
  88085. });
  88086. _this._updateBoundingBox();
  88087. return _this;
  88088. }
  88089. BoundingBoxGizmo.prototype._selectNode = function (selectedMesh) {
  88090. this._rotateSpheresParent.getChildMeshes()
  88091. .concat(this._scaleBoxesParent.getChildMeshes()).forEach(function (m, i) {
  88092. m.isVisible = (!selectedMesh || m == selectedMesh);
  88093. });
  88094. };
  88095. BoundingBoxGizmo.prototype._updateBoundingBox = function () {
  88096. if (this.attachedMesh) {
  88097. // Update bounding dimensions/positions
  88098. var boundingInfo = this.attachedMesh.getBoundingInfo().boundingBox;
  88099. var boundBoxDimensions = boundingInfo.maximum.subtract(boundingInfo.minimum).multiplyInPlace(this.attachedMesh.scaling);
  88100. this._boundingDimensions.copyFrom(boundBoxDimensions);
  88101. this._lineBoundingBox.scaling.copyFrom(this._boundingDimensions);
  88102. if (!this.attachedMesh.rotationQuaternion) {
  88103. this.attachedMesh.rotationQuaternion = new BABYLON.Quaternion();
  88104. }
  88105. this._lineBoundingBox.rotationQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  88106. this._rotateSpheresParent.rotationQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  88107. this._scaleBoxesParent.rotationQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  88108. }
  88109. // Update rotation sphere locations
  88110. var rotateSpheres = this._rotateSpheresParent.getChildMeshes();
  88111. for (var i = 0; i < 3; i++) {
  88112. for (var j = 0; j < 2; j++) {
  88113. for (var k = 0; k < 2; k++) {
  88114. var index = ((i * 4) + (j * 2)) + k;
  88115. if (i == 0) {
  88116. rotateSpheres[index].position.set(this._boundingDimensions.x / 2, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  88117. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  88118. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Right(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  88119. }
  88120. if (i == 1) {
  88121. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y / 2, this._boundingDimensions.z * k);
  88122. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  88123. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Up(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  88124. }
  88125. if (i == 2) {
  88126. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y * k, this._boundingDimensions.z / 2);
  88127. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  88128. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Forward(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  88129. }
  88130. }
  88131. }
  88132. }
  88133. // Update scale box locations
  88134. var scaleBoxes = this._scaleBoxesParent.getChildMeshes();
  88135. for (var i = 0; i < 2; i++) {
  88136. for (var j = 0; j < 2; j++) {
  88137. for (var k = 0; k < 2; k++) {
  88138. var index = ((i * 4) + (j * 2)) + k;
  88139. if (scaleBoxes[index]) {
  88140. scaleBoxes[index].position.set(this._boundingDimensions.x * i, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  88141. scaleBoxes[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  88142. }
  88143. }
  88144. }
  88145. }
  88146. };
  88147. /**
  88148. * Disposes of the gizmo
  88149. */
  88150. BoundingBoxGizmo.prototype.dispose = function () {
  88151. this.gizmoLayer.originalScene.onBeforeRenderObservable.remove(this._renderObserver);
  88152. this._lineBoundingBox.dispose();
  88153. this._rotateSpheresParent.dispose();
  88154. this._scaleBoxesParent.dispose();
  88155. _super.prototype.dispose.call(this);
  88156. };
  88157. return BoundingBoxGizmo;
  88158. }(BABYLON.Gizmo));
  88159. BABYLON.BoundingBoxGizmo = BoundingBoxGizmo;
  88160. })(BABYLON || (BABYLON = {}));
  88161. //# sourceMappingURL=babylon.boundingBoxGizmo.js.map
  88162. var BABYLON;
  88163. (function (BABYLON) {
  88164. /**
  88165. * Helps setup gizmo's in the scene to rotate/scale/position meshes
  88166. */
  88167. var GizmoManager = /** @class */ (function () {
  88168. /**
  88169. * Instatiates a gizmo manager
  88170. * @param scene the scene to overlay the gizmos on top of
  88171. * @param options If only a single gizmo should exist at one time
  88172. */
  88173. function GizmoManager(scene, options) {
  88174. var _this = this;
  88175. this.scene = scene;
  88176. // Set of gizmos that are currently in the scene for each mesh
  88177. this._gizmoSet = {};
  88178. this._pointerObserver = null;
  88179. this._gizmoLayer = new BABYLON.UtilityLayerRenderer(scene);
  88180. // Options parsing
  88181. if (!options) {
  88182. options = {};
  88183. }
  88184. if (options.singleGizmo === undefined) {
  88185. options.singleGizmo = true;
  88186. }
  88187. // Instatiate/dispose gizmos based on pointer actions
  88188. this._pointerObserver = scene.onPointerObservable.add(function (pointerInfo, state) {
  88189. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  88190. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh) {
  88191. if (!_this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId]) {
  88192. if (options.singleGizmo) {
  88193. _this._clearGizmos();
  88194. }
  88195. // Enable gizmo when mesh is selected
  88196. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId] = { positionGizmo: new BABYLON.PositionGizmo(_this._gizmoLayer), rotationGizmo: new BABYLON.RotationGizmo(_this._gizmoLayer) };
  88197. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId].positionGizmo.attachedMesh = pointerInfo.pickInfo.pickedMesh;
  88198. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId].rotationGizmo.attachedMesh = pointerInfo.pickInfo.pickedMesh;
  88199. }
  88200. else {
  88201. if (!options.singleGizmo) {
  88202. // Disable gizmo when clicked again
  88203. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId].positionGizmo.dispose();
  88204. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId].rotationGizmo.dispose();
  88205. delete _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId];
  88206. }
  88207. }
  88208. }
  88209. else {
  88210. if (options.singleGizmo) {
  88211. // Disable gizmo when clicked away
  88212. if (pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {
  88213. var gizmoPick = _this._gizmoLayer.utilityLayerScene.pickWithRay(pointerInfo.pickInfo.ray);
  88214. if (gizmoPick && !gizmoPick.hit) {
  88215. _this._clearGizmos();
  88216. }
  88217. }
  88218. }
  88219. }
  88220. }
  88221. });
  88222. }
  88223. /**
  88224. * Disposes of the gizmo manager
  88225. */
  88226. GizmoManager.prototype.dispose = function () {
  88227. this.scene.onPointerObservable.remove(this._pointerObserver);
  88228. this._clearGizmos();
  88229. this._gizmoLayer.dispose();
  88230. };
  88231. GizmoManager.prototype._clearGizmos = function () {
  88232. for (var key in this._gizmoSet) {
  88233. if (this._gizmoSet.hasOwnProperty(key)) {
  88234. this._gizmoSet[key].positionGizmo.dispose();
  88235. this._gizmoSet[key].rotationGizmo.dispose();
  88236. delete this._gizmoSet[key];
  88237. }
  88238. }
  88239. };
  88240. return GizmoManager;
  88241. }());
  88242. BABYLON.GizmoManager = GizmoManager;
  88243. })(BABYLON || (BABYLON = {}));
  88244. //# sourceMappingURL=babylon.gizmoManager.js.map
  88245. var BABYLON;
  88246. (function (BABYLON) {
  88247. /**
  88248. * Defines a target to use with MorphTargetManager
  88249. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  88250. */
  88251. var MorphTarget = /** @class */ (function () {
  88252. /**
  88253. * Creates a new MorphTarget
  88254. * @param name defines the name of the target
  88255. * @param influence defines the influence to use
  88256. */
  88257. function MorphTarget(
  88258. /** defines the name of the target */
  88259. name, influence, scene) {
  88260. if (influence === void 0) { influence = 0; }
  88261. if (scene === void 0) { scene = null; }
  88262. this.name = name;
  88263. /**
  88264. * Gets or sets the list of animations
  88265. */
  88266. this.animations = new Array();
  88267. this._positions = null;
  88268. this._normals = null;
  88269. this._tangents = null;
  88270. /**
  88271. * Observable raised when the influence changes
  88272. */
  88273. this.onInfluenceChanged = new BABYLON.Observable();
  88274. this._animationPropertiesOverride = null;
  88275. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  88276. this.influence = influence;
  88277. }
  88278. Object.defineProperty(MorphTarget.prototype, "influence", {
  88279. /**
  88280. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  88281. */
  88282. get: function () {
  88283. return this._influence;
  88284. },
  88285. set: function (influence) {
  88286. if (this._influence === influence) {
  88287. return;
  88288. }
  88289. var previous = this._influence;
  88290. this._influence = influence;
  88291. if (this.onInfluenceChanged.hasObservers) {
  88292. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  88293. }
  88294. },
  88295. enumerable: true,
  88296. configurable: true
  88297. });
  88298. Object.defineProperty(MorphTarget.prototype, "animationPropertiesOverride", {
  88299. /**
  88300. * Gets or sets the animation properties override
  88301. */
  88302. get: function () {
  88303. if (!this._animationPropertiesOverride && this._scene) {
  88304. return this._scene.animationPropertiesOverride;
  88305. }
  88306. return this._animationPropertiesOverride;
  88307. },
  88308. set: function (value) {
  88309. this._animationPropertiesOverride = value;
  88310. },
  88311. enumerable: true,
  88312. configurable: true
  88313. });
  88314. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  88315. /**
  88316. * Gets a boolean defining if the target contains position data
  88317. */
  88318. get: function () {
  88319. return !!this._positions;
  88320. },
  88321. enumerable: true,
  88322. configurable: true
  88323. });
  88324. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  88325. /**
  88326. * Gets a boolean defining if the target contains normal data
  88327. */
  88328. get: function () {
  88329. return !!this._normals;
  88330. },
  88331. enumerable: true,
  88332. configurable: true
  88333. });
  88334. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  88335. /**
  88336. * Gets a boolean defining if the target contains tangent data
  88337. */
  88338. get: function () {
  88339. return !!this._tangents;
  88340. },
  88341. enumerable: true,
  88342. configurable: true
  88343. });
  88344. /**
  88345. * Affects position data to this target
  88346. * @param data defines the position data to use
  88347. */
  88348. MorphTarget.prototype.setPositions = function (data) {
  88349. this._positions = data;
  88350. };
  88351. /**
  88352. * Gets the position data stored in this target
  88353. * @returns a FloatArray containing the position data (or null if not present)
  88354. */
  88355. MorphTarget.prototype.getPositions = function () {
  88356. return this._positions;
  88357. };
  88358. /**
  88359. * Affects normal data to this target
  88360. * @param data defines the normal data to use
  88361. */
  88362. MorphTarget.prototype.setNormals = function (data) {
  88363. this._normals = data;
  88364. };
  88365. /**
  88366. * Gets the normal data stored in this target
  88367. * @returns a FloatArray containing the normal data (or null if not present)
  88368. */
  88369. MorphTarget.prototype.getNormals = function () {
  88370. return this._normals;
  88371. };
  88372. /**
  88373. * Affects tangent data to this target
  88374. * @param data defines the tangent data to use
  88375. */
  88376. MorphTarget.prototype.setTangents = function (data) {
  88377. this._tangents = data;
  88378. };
  88379. /**
  88380. * Gets the tangent data stored in this target
  88381. * @returns a FloatArray containing the tangent data (or null if not present)
  88382. */
  88383. MorphTarget.prototype.getTangents = function () {
  88384. return this._tangents;
  88385. };
  88386. /**
  88387. * Serializes the current target into a Serialization object
  88388. * @returns the serialized object
  88389. */
  88390. MorphTarget.prototype.serialize = function () {
  88391. var serializationObject = {};
  88392. serializationObject.name = this.name;
  88393. serializationObject.influence = this.influence;
  88394. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  88395. if (this.hasNormals) {
  88396. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  88397. }
  88398. if (this.hasTangents) {
  88399. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  88400. }
  88401. // Animations
  88402. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  88403. return serializationObject;
  88404. };
  88405. // Statics
  88406. /**
  88407. * Creates a new target from serialized data
  88408. * @param serializationObject defines the serialized data to use
  88409. * @returns a new MorphTarget
  88410. */
  88411. MorphTarget.Parse = function (serializationObject) {
  88412. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  88413. result.setPositions(serializationObject.positions);
  88414. if (serializationObject.normals) {
  88415. result.setNormals(serializationObject.normals);
  88416. }
  88417. if (serializationObject.tangents) {
  88418. result.setTangents(serializationObject.tangents);
  88419. }
  88420. // Animations
  88421. if (serializationObject.animations) {
  88422. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  88423. var parsedAnimation = serializationObject.animations[animationIndex];
  88424. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  88425. }
  88426. }
  88427. return result;
  88428. };
  88429. /**
  88430. * Creates a MorphTarget from mesh data
  88431. * @param mesh defines the source mesh
  88432. * @param name defines the name to use for the new target
  88433. * @param influence defines the influence to attach to the target
  88434. * @returns a new MorphTarget
  88435. */
  88436. MorphTarget.FromMesh = function (mesh, name, influence) {
  88437. if (!name) {
  88438. name = mesh.name;
  88439. }
  88440. var result = new MorphTarget(name, influence, mesh.getScene());
  88441. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  88442. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  88443. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  88444. }
  88445. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  88446. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  88447. }
  88448. return result;
  88449. };
  88450. return MorphTarget;
  88451. }());
  88452. BABYLON.MorphTarget = MorphTarget;
  88453. })(BABYLON || (BABYLON = {}));
  88454. //# sourceMappingURL=babylon.morphTarget.js.map
  88455. var BABYLON;
  88456. (function (BABYLON) {
  88457. /**
  88458. * This class is used to deform meshes using morphing between different targets
  88459. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  88460. */
  88461. var MorphTargetManager = /** @class */ (function () {
  88462. /**
  88463. * Creates a new MorphTargetManager
  88464. * @param scene defines the current scene
  88465. */
  88466. function MorphTargetManager(scene) {
  88467. if (scene === void 0) { scene = null; }
  88468. this._targets = new Array();
  88469. this._targetObservable = new Array();
  88470. this._activeTargets = new BABYLON.SmartArray(16);
  88471. this._supportsNormals = false;
  88472. this._supportsTangents = false;
  88473. this._vertexCount = 0;
  88474. this._uniqueId = 0;
  88475. this._tempInfluences = new Array();
  88476. if (!scene) {
  88477. scene = BABYLON.Engine.LastCreatedScene;
  88478. }
  88479. this._scene = scene;
  88480. if (this._scene) {
  88481. this._scene.morphTargetManagers.push(this);
  88482. this._uniqueId = this._scene.getUniqueId();
  88483. }
  88484. }
  88485. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  88486. /**
  88487. * Gets the unique ID of this manager
  88488. */
  88489. get: function () {
  88490. return this._uniqueId;
  88491. },
  88492. enumerable: true,
  88493. configurable: true
  88494. });
  88495. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  88496. /**
  88497. * Gets the number of vertices handled by this manager
  88498. */
  88499. get: function () {
  88500. return this._vertexCount;
  88501. },
  88502. enumerable: true,
  88503. configurable: true
  88504. });
  88505. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  88506. /**
  88507. * Gets a boolean indicating if this manager supports morphing of normals
  88508. */
  88509. get: function () {
  88510. return this._supportsNormals;
  88511. },
  88512. enumerable: true,
  88513. configurable: true
  88514. });
  88515. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  88516. /**
  88517. * Gets a boolean indicating if this manager supports morphing of tangents
  88518. */
  88519. get: function () {
  88520. return this._supportsTangents;
  88521. },
  88522. enumerable: true,
  88523. configurable: true
  88524. });
  88525. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  88526. /**
  88527. * Gets the number of targets stored in this manager
  88528. */
  88529. get: function () {
  88530. return this._targets.length;
  88531. },
  88532. enumerable: true,
  88533. configurable: true
  88534. });
  88535. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  88536. /**
  88537. * Gets the number of influencers (ie. the number of targets with influences > 0)
  88538. */
  88539. get: function () {
  88540. return this._activeTargets.length;
  88541. },
  88542. enumerable: true,
  88543. configurable: true
  88544. });
  88545. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  88546. /**
  88547. * Gets the list of influences (one per target)
  88548. */
  88549. get: function () {
  88550. return this._influences;
  88551. },
  88552. enumerable: true,
  88553. configurable: true
  88554. });
  88555. /**
  88556. * Gets the active target at specified index. An active target is a target with an influence > 0
  88557. * @param index defines the index to check
  88558. * @returns the requested target
  88559. */
  88560. MorphTargetManager.prototype.getActiveTarget = function (index) {
  88561. return this._activeTargets.data[index];
  88562. };
  88563. /**
  88564. * Gets the target at specified index
  88565. * @param index defines the index to check
  88566. * @returns the requested target
  88567. */
  88568. MorphTargetManager.prototype.getTarget = function (index) {
  88569. return this._targets[index];
  88570. };
  88571. /**
  88572. * Add a new target to this manager
  88573. * @param target defines the target to add
  88574. */
  88575. MorphTargetManager.prototype.addTarget = function (target) {
  88576. var _this = this;
  88577. this._targets.push(target);
  88578. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  88579. _this._syncActiveTargets(needUpdate);
  88580. }));
  88581. this._syncActiveTargets(true);
  88582. };
  88583. /**
  88584. * Removes a target from the manager
  88585. * @param target defines the target to remove
  88586. */
  88587. MorphTargetManager.prototype.removeTarget = function (target) {
  88588. var index = this._targets.indexOf(target);
  88589. if (index >= 0) {
  88590. this._targets.splice(index, 1);
  88591. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  88592. this._syncActiveTargets(true);
  88593. }
  88594. };
  88595. /**
  88596. * Serializes the current manager into a Serialization object
  88597. * @returns the serialized object
  88598. */
  88599. MorphTargetManager.prototype.serialize = function () {
  88600. var serializationObject = {};
  88601. serializationObject.id = this.uniqueId;
  88602. serializationObject.targets = [];
  88603. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  88604. var target = _a[_i];
  88605. serializationObject.targets.push(target.serialize());
  88606. }
  88607. return serializationObject;
  88608. };
  88609. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  88610. var influenceCount = 0;
  88611. this._activeTargets.reset();
  88612. this._supportsNormals = true;
  88613. this._supportsTangents = true;
  88614. this._vertexCount = 0;
  88615. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  88616. var target = _a[_i];
  88617. this._activeTargets.push(target);
  88618. this._tempInfluences[influenceCount++] = target.influence;
  88619. var positions = target.getPositions();
  88620. if (positions) {
  88621. this._supportsNormals = this._supportsNormals && target.hasNormals;
  88622. this._supportsTangents = this._supportsTangents && target.hasTangents;
  88623. var vertexCount = positions.length / 3;
  88624. if (this._vertexCount === 0) {
  88625. this._vertexCount = vertexCount;
  88626. }
  88627. else if (this._vertexCount !== vertexCount) {
  88628. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  88629. return;
  88630. }
  88631. }
  88632. }
  88633. if (!this._influences || this._influences.length !== influenceCount) {
  88634. this._influences = new Float32Array(influenceCount);
  88635. }
  88636. for (var index = 0; index < influenceCount; index++) {
  88637. this._influences[index] = this._tempInfluences[index];
  88638. }
  88639. if (needUpdate) {
  88640. this.synchronize();
  88641. }
  88642. };
  88643. /**
  88644. * Syncrhonize the targets with all the meshes using this morph target manager
  88645. */
  88646. MorphTargetManager.prototype.synchronize = function () {
  88647. if (!this._scene) {
  88648. return;
  88649. }
  88650. // Flag meshes as dirty to resync with the active targets
  88651. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  88652. var mesh = _a[_i];
  88653. if (mesh.morphTargetManager === this) {
  88654. mesh._syncGeometryWithMorphTargetManager();
  88655. }
  88656. }
  88657. };
  88658. // Statics
  88659. /**
  88660. * Creates a new MorphTargetManager from serialized data
  88661. * @param serializationObject defines the serialized data
  88662. * @param scene defines the hosting scene
  88663. * @returns the new MorphTargetManager
  88664. */
  88665. MorphTargetManager.Parse = function (serializationObject, scene) {
  88666. var result = new MorphTargetManager(scene);
  88667. result._uniqueId = serializationObject.id;
  88668. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  88669. var targetData = _a[_i];
  88670. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  88671. }
  88672. return result;
  88673. };
  88674. return MorphTargetManager;
  88675. }());
  88676. BABYLON.MorphTargetManager = MorphTargetManager;
  88677. })(BABYLON || (BABYLON = {}));
  88678. //# sourceMappingURL=babylon.morphTargetManager.js.map
  88679. var BABYLON;
  88680. (function (BABYLON) {
  88681. var Octree = /** @class */ (function () {
  88682. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  88683. if (maxDepth === void 0) { maxDepth = 2; }
  88684. this.maxDepth = maxDepth;
  88685. this.dynamicContent = new Array();
  88686. this._maxBlockCapacity = maxBlockCapacity || 64;
  88687. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  88688. this._creationFunc = creationFunc;
  88689. }
  88690. // Methods
  88691. Octree.prototype.update = function (worldMin, worldMax, entries) {
  88692. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  88693. };
  88694. Octree.prototype.addMesh = function (entry) {
  88695. for (var index = 0; index < this.blocks.length; index++) {
  88696. var block = this.blocks[index];
  88697. block.addEntry(entry);
  88698. }
  88699. };
  88700. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  88701. this._selectionContent.reset();
  88702. for (var index = 0; index < this.blocks.length; index++) {
  88703. var block = this.blocks[index];
  88704. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  88705. }
  88706. if (allowDuplicate) {
  88707. this._selectionContent.concat(this.dynamicContent);
  88708. }
  88709. else {
  88710. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  88711. }
  88712. return this._selectionContent;
  88713. };
  88714. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  88715. this._selectionContent.reset();
  88716. for (var index = 0; index < this.blocks.length; index++) {
  88717. var block = this.blocks[index];
  88718. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  88719. }
  88720. if (allowDuplicate) {
  88721. this._selectionContent.concat(this.dynamicContent);
  88722. }
  88723. else {
  88724. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  88725. }
  88726. return this._selectionContent;
  88727. };
  88728. Octree.prototype.intersectsRay = function (ray) {
  88729. this._selectionContent.reset();
  88730. for (var index = 0; index < this.blocks.length; index++) {
  88731. var block = this.blocks[index];
  88732. block.intersectsRay(ray, this._selectionContent);
  88733. }
  88734. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  88735. return this._selectionContent;
  88736. };
  88737. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  88738. target.blocks = new Array();
  88739. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  88740. // Segmenting space
  88741. for (var x = 0; x < 2; x++) {
  88742. for (var y = 0; y < 2; y++) {
  88743. for (var z = 0; z < 2; z++) {
  88744. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  88745. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  88746. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  88747. block.addEntries(entries);
  88748. target.blocks.push(block);
  88749. }
  88750. }
  88751. }
  88752. };
  88753. Octree.CreationFuncForMeshes = function (entry, block) {
  88754. var boundingInfo = entry.getBoundingInfo();
  88755. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  88756. block.entries.push(entry);
  88757. }
  88758. };
  88759. Octree.CreationFuncForSubMeshes = function (entry, block) {
  88760. var boundingInfo = entry.getBoundingInfo();
  88761. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  88762. block.entries.push(entry);
  88763. }
  88764. };
  88765. return Octree;
  88766. }());
  88767. BABYLON.Octree = Octree;
  88768. })(BABYLON || (BABYLON = {}));
  88769. //# sourceMappingURL=babylon.octree.js.map
  88770. var BABYLON;
  88771. (function (BABYLON) {
  88772. var OctreeBlock = /** @class */ (function () {
  88773. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  88774. this.entries = new Array();
  88775. this._boundingVectors = new Array();
  88776. this._capacity = capacity;
  88777. this._depth = depth;
  88778. this._maxDepth = maxDepth;
  88779. this._creationFunc = creationFunc;
  88780. this._minPoint = minPoint;
  88781. this._maxPoint = maxPoint;
  88782. this._boundingVectors.push(minPoint.clone());
  88783. this._boundingVectors.push(maxPoint.clone());
  88784. this._boundingVectors.push(minPoint.clone());
  88785. this._boundingVectors[2].x = maxPoint.x;
  88786. this._boundingVectors.push(minPoint.clone());
  88787. this._boundingVectors[3].y = maxPoint.y;
  88788. this._boundingVectors.push(minPoint.clone());
  88789. this._boundingVectors[4].z = maxPoint.z;
  88790. this._boundingVectors.push(maxPoint.clone());
  88791. this._boundingVectors[5].z = minPoint.z;
  88792. this._boundingVectors.push(maxPoint.clone());
  88793. this._boundingVectors[6].x = minPoint.x;
  88794. this._boundingVectors.push(maxPoint.clone());
  88795. this._boundingVectors[7].y = minPoint.y;
  88796. }
  88797. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  88798. // Property
  88799. get: function () {
  88800. return this._capacity;
  88801. },
  88802. enumerable: true,
  88803. configurable: true
  88804. });
  88805. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  88806. get: function () {
  88807. return this._minPoint;
  88808. },
  88809. enumerable: true,
  88810. configurable: true
  88811. });
  88812. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  88813. get: function () {
  88814. return this._maxPoint;
  88815. },
  88816. enumerable: true,
  88817. configurable: true
  88818. });
  88819. // Methods
  88820. OctreeBlock.prototype.addEntry = function (entry) {
  88821. if (this.blocks) {
  88822. for (var index = 0; index < this.blocks.length; index++) {
  88823. var block = this.blocks[index];
  88824. block.addEntry(entry);
  88825. }
  88826. return;
  88827. }
  88828. this._creationFunc(entry, this);
  88829. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  88830. this.createInnerBlocks();
  88831. }
  88832. };
  88833. OctreeBlock.prototype.addEntries = function (entries) {
  88834. for (var index = 0; index < entries.length; index++) {
  88835. var mesh = entries[index];
  88836. this.addEntry(mesh);
  88837. }
  88838. };
  88839. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  88840. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  88841. if (this.blocks) {
  88842. for (var index = 0; index < this.blocks.length; index++) {
  88843. var block = this.blocks[index];
  88844. block.select(frustumPlanes, selection, allowDuplicate);
  88845. }
  88846. return;
  88847. }
  88848. if (allowDuplicate) {
  88849. selection.concat(this.entries);
  88850. }
  88851. else {
  88852. selection.concatWithNoDuplicate(this.entries);
  88853. }
  88854. }
  88855. };
  88856. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  88857. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  88858. if (this.blocks) {
  88859. for (var index = 0; index < this.blocks.length; index++) {
  88860. var block = this.blocks[index];
  88861. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  88862. }
  88863. return;
  88864. }
  88865. if (allowDuplicate) {
  88866. selection.concat(this.entries);
  88867. }
  88868. else {
  88869. selection.concatWithNoDuplicate(this.entries);
  88870. }
  88871. }
  88872. };
  88873. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  88874. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  88875. if (this.blocks) {
  88876. for (var index = 0; index < this.blocks.length; index++) {
  88877. var block = this.blocks[index];
  88878. block.intersectsRay(ray, selection);
  88879. }
  88880. return;
  88881. }
  88882. selection.concatWithNoDuplicate(this.entries);
  88883. }
  88884. };
  88885. OctreeBlock.prototype.createInnerBlocks = function () {
  88886. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  88887. };
  88888. return OctreeBlock;
  88889. }());
  88890. BABYLON.OctreeBlock = OctreeBlock;
  88891. })(BABYLON || (BABYLON = {}));
  88892. //# sourceMappingURL=babylon.octreeBlock.js.map
  88893. var BABYLON;
  88894. (function (BABYLON) {
  88895. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  88896. __extends(VRDistortionCorrectionPostProcess, _super);
  88897. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  88898. var _this = _super.call(this, name, "vrDistortionCorrection", [
  88899. 'LensCenter',
  88900. 'Scale',
  88901. 'ScaleIn',
  88902. 'HmdWarpParam'
  88903. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  88904. _this._isRightEye = isRightEye;
  88905. _this._distortionFactors = vrMetrics.distortionK;
  88906. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  88907. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  88908. _this.adaptScaleToCurrentViewport = true;
  88909. _this.onSizeChangedObservable.add(function () {
  88910. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  88911. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  88912. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  88913. });
  88914. _this.onApplyObservable.add(function (effect) {
  88915. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  88916. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  88917. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  88918. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  88919. });
  88920. return _this;
  88921. }
  88922. return VRDistortionCorrectionPostProcess;
  88923. }(BABYLON.PostProcess));
  88924. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  88925. })(BABYLON || (BABYLON = {}));
  88926. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  88927. var BABYLON;
  88928. (function (BABYLON) {
  88929. /**
  88930. * Postprocess used to generate anaglyphic rendering
  88931. */
  88932. var AnaglyphPostProcess = /** @class */ (function (_super) {
  88933. __extends(AnaglyphPostProcess, _super);
  88934. /**
  88935. * Creates a new AnaglyphPostProcess
  88936. * @param name defines postprocess name
  88937. * @param options defines creation options or target ratio scale
  88938. * @param rigCameras defines cameras using this postprocess
  88939. * @param samplingMode defines required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  88940. * @param engine defines hosting engine
  88941. * @param reusable defines if the postprocess will be reused multiple times per frame
  88942. */
  88943. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  88944. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  88945. _this._passedProcess = rigCameras[0]._rigPostProcess;
  88946. _this.onApplyObservable.add(function (effect) {
  88947. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  88948. });
  88949. return _this;
  88950. }
  88951. return AnaglyphPostProcess;
  88952. }(BABYLON.PostProcess));
  88953. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  88954. })(BABYLON || (BABYLON = {}));
  88955. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  88956. var BABYLON;
  88957. (function (BABYLON) {
  88958. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  88959. __extends(StereoscopicInterlacePostProcess, _super);
  88960. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  88961. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  88962. _this._passedProcess = rigCameras[0]._rigPostProcess;
  88963. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  88964. _this.onSizeChangedObservable.add(function () {
  88965. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  88966. });
  88967. _this.onApplyObservable.add(function (effect) {
  88968. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  88969. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  88970. });
  88971. return _this;
  88972. }
  88973. return StereoscopicInterlacePostProcess;
  88974. }(BABYLON.PostProcess));
  88975. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  88976. })(BABYLON || (BABYLON = {}));
  88977. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  88978. var BABYLON;
  88979. (function (BABYLON) {
  88980. /**
  88981. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  88982. * Screen rotation is taken into account.
  88983. */
  88984. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  88985. function FreeCameraDeviceOrientationInput() {
  88986. var _this = this;
  88987. this._screenOrientationAngle = 0;
  88988. this._screenQuaternion = new BABYLON.Quaternion();
  88989. this._alpha = 0;
  88990. this._beta = 0;
  88991. this._gamma = 0;
  88992. this._orientationChanged = function () {
  88993. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  88994. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  88995. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  88996. };
  88997. this._deviceOrientation = function (evt) {
  88998. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  88999. _this._beta = evt.beta !== null ? evt.beta : 0;
  89000. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  89001. };
  89002. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  89003. this._orientationChanged();
  89004. }
  89005. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  89006. get: function () {
  89007. return this._camera;
  89008. },
  89009. set: function (camera) {
  89010. this._camera = camera;
  89011. if (this._camera != null && !this._camera.rotationQuaternion) {
  89012. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  89013. }
  89014. },
  89015. enumerable: true,
  89016. configurable: true
  89017. });
  89018. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  89019. window.addEventListener("orientationchange", this._orientationChanged);
  89020. window.addEventListener("deviceorientation", this._deviceOrientation);
  89021. //In certain cases, the attach control is called AFTER orientation was changed,
  89022. //So this is needed.
  89023. this._orientationChanged();
  89024. };
  89025. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  89026. window.removeEventListener("orientationchange", this._orientationChanged);
  89027. window.removeEventListener("deviceorientation", this._deviceOrientation);
  89028. };
  89029. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  89030. //if no device orientation provided, don't update the rotation.
  89031. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  89032. if (!this._alpha)
  89033. return;
  89034. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  89035. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  89036. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  89037. //Mirror on XY Plane
  89038. this._camera.rotationQuaternion.z *= -1;
  89039. this._camera.rotationQuaternion.w *= -1;
  89040. };
  89041. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  89042. return "FreeCameraDeviceOrientationInput";
  89043. };
  89044. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  89045. return "deviceOrientation";
  89046. };
  89047. return FreeCameraDeviceOrientationInput;
  89048. }());
  89049. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  89050. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  89051. })(BABYLON || (BABYLON = {}));
  89052. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  89053. var BABYLON;
  89054. (function (BABYLON) {
  89055. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  89056. function ArcRotateCameraVRDeviceOrientationInput() {
  89057. this.alphaCorrection = 1;
  89058. this.betaCorrection = 1;
  89059. this.gammaCorrection = 1;
  89060. this._alpha = 0;
  89061. this._gamma = 0;
  89062. this._dirty = false;
  89063. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  89064. }
  89065. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  89066. this.camera.attachControl(element, noPreventDefault);
  89067. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  89068. };
  89069. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  89070. if (evt.alpha !== null) {
  89071. this._alpha = +evt.alpha | 0;
  89072. }
  89073. if (evt.gamma !== null) {
  89074. this._gamma = +evt.gamma | 0;
  89075. }
  89076. this._dirty = true;
  89077. };
  89078. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  89079. if (this._dirty) {
  89080. this._dirty = false;
  89081. if (this._gamma < 0) {
  89082. this._gamma = 180 + this._gamma;
  89083. }
  89084. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  89085. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  89086. }
  89087. };
  89088. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  89089. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  89090. };
  89091. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  89092. return "ArcRotateCameraVRDeviceOrientationInput";
  89093. };
  89094. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  89095. return "VRDeviceOrientation";
  89096. };
  89097. return ArcRotateCameraVRDeviceOrientationInput;
  89098. }());
  89099. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  89100. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  89101. })(BABYLON || (BABYLON = {}));
  89102. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  89103. var BABYLON;
  89104. (function (BABYLON) {
  89105. var VRCameraMetrics = /** @class */ (function () {
  89106. function VRCameraMetrics() {
  89107. this.compensateDistortion = true;
  89108. }
  89109. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  89110. get: function () {
  89111. return this.hResolution / (2 * this.vResolution);
  89112. },
  89113. enumerable: true,
  89114. configurable: true
  89115. });
  89116. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  89117. get: function () {
  89118. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  89119. },
  89120. enumerable: true,
  89121. configurable: true
  89122. });
  89123. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  89124. get: function () {
  89125. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  89126. var h = (4 * meters) / this.hScreenSize;
  89127. return BABYLON.Matrix.Translation(h, 0, 0);
  89128. },
  89129. enumerable: true,
  89130. configurable: true
  89131. });
  89132. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  89133. get: function () {
  89134. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  89135. var h = (4 * meters) / this.hScreenSize;
  89136. return BABYLON.Matrix.Translation(-h, 0, 0);
  89137. },
  89138. enumerable: true,
  89139. configurable: true
  89140. });
  89141. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  89142. get: function () {
  89143. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  89144. },
  89145. enumerable: true,
  89146. configurable: true
  89147. });
  89148. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  89149. get: function () {
  89150. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  89151. },
  89152. enumerable: true,
  89153. configurable: true
  89154. });
  89155. VRCameraMetrics.GetDefault = function () {
  89156. var result = new VRCameraMetrics();
  89157. result.hResolution = 1280;
  89158. result.vResolution = 800;
  89159. result.hScreenSize = 0.149759993;
  89160. result.vScreenSize = 0.0935999975;
  89161. result.vScreenCenter = 0.0467999987;
  89162. result.eyeToScreenDistance = 0.0410000011;
  89163. result.lensSeparationDistance = 0.0635000020;
  89164. result.interpupillaryDistance = 0.0640000030;
  89165. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  89166. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  89167. result.postProcessScaleFactor = 1.714605507808412;
  89168. result.lensCenterOffset = 0.151976421;
  89169. return result;
  89170. };
  89171. return VRCameraMetrics;
  89172. }());
  89173. BABYLON.VRCameraMetrics = VRCameraMetrics;
  89174. })(BABYLON || (BABYLON = {}));
  89175. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  89176. var BABYLON;
  89177. (function (BABYLON) {
  89178. /**
  89179. * This represents a WebVR camera.
  89180. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  89181. * @example http://doc.babylonjs.com/how_to/webvr_camera
  89182. */
  89183. var WebVRFreeCamera = /** @class */ (function (_super) {
  89184. __extends(WebVRFreeCamera, _super);
  89185. /**
  89186. * Instantiates a WebVRFreeCamera.
  89187. * @param name The name of the WebVRFreeCamera
  89188. * @param position The starting anchor position for the camera
  89189. * @param scene The scene the camera belongs to
  89190. * @param webVROptions a set of customizable options for the webVRCamera
  89191. */
  89192. function WebVRFreeCamera(name, position, scene, webVROptions) {
  89193. if (webVROptions === void 0) { webVROptions = {}; }
  89194. var _this = _super.call(this, name, position, scene) || this;
  89195. _this.webVROptions = webVROptions;
  89196. /**
  89197. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  89198. */
  89199. _this._vrDevice = null;
  89200. /**
  89201. * The rawPose of the vrDevice.
  89202. */
  89203. _this.rawPose = null;
  89204. _this._specsVersion = "1.1";
  89205. _this._attached = false;
  89206. _this._descendants = [];
  89207. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  89208. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  89209. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  89210. _this._standingMatrix = null;
  89211. /**
  89212. * Represents device position in babylon space.
  89213. */
  89214. _this.devicePosition = BABYLON.Vector3.Zero();
  89215. /**
  89216. * Represents device rotation in babylon space.
  89217. */
  89218. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  89219. /**
  89220. * The scale of the device to be used when translating from device space to babylon space.
  89221. */
  89222. _this.deviceScaleFactor = 1;
  89223. _this._deviceToWorld = BABYLON.Matrix.Identity();
  89224. _this._worldToDevice = BABYLON.Matrix.Identity();
  89225. /**
  89226. * References to the webVR controllers for the vrDevice.
  89227. */
  89228. _this.controllers = [];
  89229. /**
  89230. * Emits an event when a controller is attached.
  89231. */
  89232. _this.onControllersAttachedObservable = new BABYLON.Observable();
  89233. /**
  89234. * Emits an event when a controller's mesh has been loaded;
  89235. */
  89236. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  89237. /**
  89238. * If the rig cameras be used as parent instead of this camera.
  89239. */
  89240. _this.rigParenting = true;
  89241. _this._defaultHeight = undefined;
  89242. _this._workingVector = BABYLON.Vector3.Zero();
  89243. _this._oneVector = BABYLON.Vector3.One();
  89244. _this._workingMatrix = BABYLON.Matrix.Identity();
  89245. _this._cache.position = BABYLON.Vector3.Zero();
  89246. if (webVROptions.defaultHeight) {
  89247. _this._defaultHeight = webVROptions.defaultHeight;
  89248. _this.position.y = _this._defaultHeight;
  89249. }
  89250. _this.minZ = 0.1;
  89251. //legacy support - the compensation boolean was removed.
  89252. if (arguments.length === 5) {
  89253. _this.webVROptions = arguments[4];
  89254. }
  89255. // default webVR options
  89256. if (_this.webVROptions.trackPosition == undefined) {
  89257. _this.webVROptions.trackPosition = true;
  89258. }
  89259. if (_this.webVROptions.controllerMeshes == undefined) {
  89260. _this.webVROptions.controllerMeshes = true;
  89261. }
  89262. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  89263. _this.webVROptions.defaultLightingOnControllers = true;
  89264. }
  89265. _this.rotationQuaternion = new BABYLON.Quaternion();
  89266. if (_this.webVROptions && _this.webVROptions.positionScale) {
  89267. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  89268. }
  89269. //enable VR
  89270. var engine = _this.getEngine();
  89271. _this._onVREnabled = function (success) { if (success) {
  89272. _this.initControllers();
  89273. } };
  89274. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  89275. engine.initWebVR().add(function (event) {
  89276. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  89277. return;
  89278. }
  89279. _this._vrDevice = event.vrDisplay;
  89280. //reset the rig parameters.
  89281. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  89282. if (_this._attached) {
  89283. _this.getEngine().enableVR();
  89284. }
  89285. });
  89286. if (typeof (VRFrameData) !== "undefined")
  89287. _this._frameData = new VRFrameData();
  89288. /**
  89289. * The idea behind the following lines:
  89290. * objects that have the camera as parent should actually have the rig cameras as a parent.
  89291. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  89292. * the second will not show it correctly.
  89293. *
  89294. * To solve this - each object that has the camera as parent will be added to a protected array.
  89295. * When the rig camera renders, it will take this array and set all of those to be its children.
  89296. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  89297. * Amazing!
  89298. */
  89299. scene.onBeforeCameraRenderObservable.add(function (camera) {
  89300. if (camera.parent === _this && _this.rigParenting) {
  89301. _this._descendants = _this.getDescendants(true, function (n) {
  89302. // don't take the cameras or the controllers!
  89303. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  89304. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  89305. return !isController && !isRigCamera;
  89306. });
  89307. _this._descendants.forEach(function (node) {
  89308. node.parent = camera;
  89309. });
  89310. }
  89311. });
  89312. scene.onAfterCameraRenderObservable.add(function (camera) {
  89313. if (camera.parent === _this && _this.rigParenting) {
  89314. _this._descendants.forEach(function (node) {
  89315. node.parent = _this;
  89316. });
  89317. }
  89318. });
  89319. return _this;
  89320. }
  89321. /**
  89322. * Gets the device distance from the ground in meters.
  89323. * @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.
  89324. */
  89325. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  89326. if (this._standingMatrix) {
  89327. // Add standing matrix offset to get real offset from ground in room
  89328. this._standingMatrix.getTranslationToRef(this._workingVector);
  89329. return this._deviceRoomPosition.y + this._workingVector.y;
  89330. }
  89331. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  89332. return this._defaultHeight || 0;
  89333. };
  89334. /**
  89335. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  89336. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  89337. */
  89338. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  89339. var _this = this;
  89340. if (callback === void 0) { callback = function (bool) { }; }
  89341. // Use standing matrix if available
  89342. this.getEngine().initWebVRAsync().then(function (result) {
  89343. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  89344. callback(false);
  89345. }
  89346. else {
  89347. _this._standingMatrix = new BABYLON.Matrix();
  89348. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  89349. if (!_this.getScene().useRightHandedSystem) {
  89350. [2, 6, 8, 9, 14].forEach(function (num) {
  89351. if (_this._standingMatrix) {
  89352. _this._standingMatrix.m[num] *= -1;
  89353. }
  89354. });
  89355. }
  89356. callback(true);
  89357. }
  89358. });
  89359. };
  89360. /**
  89361. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  89362. * @returns A promise with a boolean set to if the standing matrix is supported.
  89363. */
  89364. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  89365. var _this = this;
  89366. return new Promise(function (res, rej) {
  89367. _this.useStandingMatrix(function (supported) {
  89368. res(supported);
  89369. });
  89370. });
  89371. };
  89372. /**
  89373. * Disposes the camera
  89374. */
  89375. WebVRFreeCamera.prototype.dispose = function () {
  89376. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  89377. _super.prototype.dispose.call(this);
  89378. };
  89379. /**
  89380. * Gets a vrController by name.
  89381. * @param name The name of the controller to retreive
  89382. * @returns the controller matching the name specified or null if not found
  89383. */
  89384. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  89385. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  89386. var gp = _a[_i];
  89387. if (gp.hand === name) {
  89388. return gp;
  89389. }
  89390. }
  89391. return null;
  89392. };
  89393. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  89394. /**
  89395. * The controller corrisponding to the users left hand.
  89396. */
  89397. get: function () {
  89398. if (!this._leftController) {
  89399. this._leftController = this.getControllerByName("left");
  89400. }
  89401. return this._leftController;
  89402. },
  89403. enumerable: true,
  89404. configurable: true
  89405. });
  89406. ;
  89407. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  89408. /**
  89409. * The controller corrisponding to the users right hand.
  89410. */
  89411. get: function () {
  89412. if (!this._rightController) {
  89413. this._rightController = this.getControllerByName("right");
  89414. }
  89415. return this._rightController;
  89416. },
  89417. enumerable: true,
  89418. configurable: true
  89419. });
  89420. ;
  89421. /**
  89422. * Casts a ray forward from the vrCamera's gaze.
  89423. * @param length Length of the ray (default: 100)
  89424. * @returns the ray corrisponding to the gaze
  89425. */
  89426. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  89427. if (length === void 0) { length = 100; }
  89428. if (this.leftCamera) {
  89429. // Use left eye to avoid computation to compute center on every call
  89430. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  89431. }
  89432. else {
  89433. return _super.prototype.getForwardRay.call(this, length);
  89434. }
  89435. };
  89436. /**
  89437. * Updates the camera based on device's frame data
  89438. */
  89439. WebVRFreeCamera.prototype._checkInputs = function () {
  89440. if (this._vrDevice && this._vrDevice.isPresenting) {
  89441. this._vrDevice.getFrameData(this._frameData);
  89442. this.updateFromDevice(this._frameData.pose);
  89443. }
  89444. _super.prototype._checkInputs.call(this);
  89445. };
  89446. /**
  89447. * Updates the poseControlled values based on the input device pose.
  89448. * @param poseData Pose coming from the device
  89449. */
  89450. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  89451. if (poseData && poseData.orientation) {
  89452. this.rawPose = poseData;
  89453. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  89454. if (this.getScene().useRightHandedSystem) {
  89455. this._deviceRoomRotationQuaternion.z *= -1;
  89456. this._deviceRoomRotationQuaternion.w *= -1;
  89457. }
  89458. if (this.webVROptions.trackPosition && this.rawPose.position) {
  89459. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  89460. if (this.getScene().useRightHandedSystem) {
  89461. this._deviceRoomPosition.z *= -1;
  89462. }
  89463. }
  89464. }
  89465. };
  89466. /**
  89467. * WebVR's attach control will start broadcasting frames to the device.
  89468. * Note that in certain browsers (chrome for example) this function must be called
  89469. * within a user-interaction callback. Example:
  89470. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  89471. *
  89472. * @param element html element to attach the vrDevice to
  89473. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  89474. */
  89475. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  89476. _super.prototype.attachControl.call(this, element, noPreventDefault);
  89477. this._attached = true;
  89478. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  89479. if (this._vrDevice) {
  89480. this.getEngine().enableVR();
  89481. }
  89482. };
  89483. /**
  89484. * Detaches the camera from the html element and disables VR
  89485. *
  89486. * @param element html element to detach from
  89487. */
  89488. WebVRFreeCamera.prototype.detachControl = function (element) {
  89489. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  89490. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  89491. _super.prototype.detachControl.call(this, element);
  89492. this._attached = false;
  89493. this.getEngine().disableVR();
  89494. };
  89495. /**
  89496. * @returns the name of this class
  89497. */
  89498. WebVRFreeCamera.prototype.getClassName = function () {
  89499. return "WebVRFreeCamera";
  89500. };
  89501. /**
  89502. * Calls resetPose on the vrDisplay
  89503. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  89504. */
  89505. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  89506. //uses the vrDisplay's "resetPose()".
  89507. //pitch and roll won't be affected.
  89508. this._vrDevice.resetPose();
  89509. };
  89510. /**
  89511. * Updates the rig cameras (left and right eye)
  89512. */
  89513. WebVRFreeCamera.prototype._updateRigCameras = function () {
  89514. var camLeft = this._rigCameras[0];
  89515. var camRight = this._rigCameras[1];
  89516. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  89517. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  89518. camLeft.position.copyFrom(this._deviceRoomPosition);
  89519. camRight.position.copyFrom(this._deviceRoomPosition);
  89520. };
  89521. /**
  89522. * Updates the cached values of the camera
  89523. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  89524. */
  89525. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  89526. var _this = this;
  89527. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  89528. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  89529. if (!this.updateCacheCalled) {
  89530. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  89531. this.updateCacheCalled = true;
  89532. this.update();
  89533. }
  89534. // Set working vector to the device position in room space rotated by the new rotation
  89535. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  89536. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  89537. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  89538. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  89539. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  89540. // Add translation from anchor position
  89541. this._deviceToWorld.getTranslationToRef(this._workingVector);
  89542. this._workingVector.addInPlace(this.position);
  89543. this._workingVector.subtractInPlace(this._cache.position);
  89544. this._deviceToWorld.setTranslation(this._workingVector);
  89545. // Set an inverted matrix to be used when updating the camera
  89546. this._deviceToWorld.invertToRef(this._worldToDevice);
  89547. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  89548. this.controllers.forEach(function (controller) {
  89549. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  89550. controller.update();
  89551. });
  89552. }
  89553. if (!ignoreParentClass) {
  89554. _super.prototype._updateCache.call(this);
  89555. }
  89556. this.updateCacheCalled = false;
  89557. };
  89558. /**
  89559. * Updates the current device position and rotation in the babylon world
  89560. */
  89561. WebVRFreeCamera.prototype.update = function () {
  89562. // Get current device position in babylon world
  89563. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  89564. // Get current device rotation in babylon world
  89565. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  89566. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  89567. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  89568. _super.prototype.update.call(this);
  89569. };
  89570. /**
  89571. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  89572. * @returns an identity matrix
  89573. */
  89574. WebVRFreeCamera.prototype._getViewMatrix = function () {
  89575. return BABYLON.Matrix.Identity();
  89576. };
  89577. /**
  89578. * This function is called by the two RIG cameras.
  89579. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  89580. */
  89581. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  89582. var _this = this;
  89583. // Update the parent camera prior to using a child camera to avoid desynchronization
  89584. var parentCamera = this._cameraRigParams["parentCamera"];
  89585. parentCamera._updateCache();
  89586. //WebVR 1.1
  89587. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  89588. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  89589. if (!this.getScene().useRightHandedSystem) {
  89590. [2, 6, 8, 9, 14].forEach(function (num) {
  89591. _this._webvrViewMatrix.m[num] *= -1;
  89592. });
  89593. }
  89594. // update the camera rotation matrix
  89595. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  89596. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  89597. // Computing target and final matrix
  89598. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  89599. // should the view matrix be updated with scale and position offset?
  89600. if (parentCamera.deviceScaleFactor !== 1) {
  89601. this._webvrViewMatrix.invert();
  89602. // scale the position, if set
  89603. if (parentCamera.deviceScaleFactor) {
  89604. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  89605. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  89606. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  89607. }
  89608. this._webvrViewMatrix.invert();
  89609. }
  89610. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  89611. // Compute global position
  89612. this._workingMatrix = this._workingMatrix || BABYLON.Matrix.Identity();
  89613. this._webvrViewMatrix.invertToRef(this._workingMatrix);
  89614. this._workingMatrix.multiplyToRef(parentCamera.getWorldMatrix(), this._workingMatrix);
  89615. this._workingMatrix.getTranslationToRef(this._globalPosition);
  89616. this._markSyncedWithParent();
  89617. return this._webvrViewMatrix;
  89618. };
  89619. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  89620. var _this = this;
  89621. var parentCamera = this.parent;
  89622. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  89623. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  89624. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  89625. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  89626. //babylon compatible matrix
  89627. if (!this.getScene().useRightHandedSystem) {
  89628. [8, 9, 10, 11].forEach(function (num) {
  89629. _this._projectionMatrix.m[num] *= -1;
  89630. });
  89631. }
  89632. return this._projectionMatrix;
  89633. };
  89634. /**
  89635. * Initializes the controllers and their meshes
  89636. */
  89637. WebVRFreeCamera.prototype.initControllers = function () {
  89638. var _this = this;
  89639. this.controllers = [];
  89640. var manager = this.getScene().gamepadManager;
  89641. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  89642. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  89643. var webVrController = gamepad;
  89644. if (webVrController.defaultModel) {
  89645. webVrController.defaultModel.setEnabled(false);
  89646. }
  89647. if (webVrController.hand === "right") {
  89648. _this._rightController = null;
  89649. }
  89650. if (webVrController.hand === "left") {
  89651. _this._leftController = null;
  89652. }
  89653. var controllerIndex = _this.controllers.indexOf(webVrController);
  89654. if (controllerIndex !== -1) {
  89655. _this.controllers.splice(controllerIndex, 1);
  89656. }
  89657. }
  89658. });
  89659. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  89660. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  89661. var webVrController_1 = gamepad;
  89662. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  89663. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  89664. if (_this.webVROptions.controllerMeshes) {
  89665. if (webVrController_1.defaultModel) {
  89666. webVrController_1.defaultModel.setEnabled(true);
  89667. }
  89668. else {
  89669. // Load the meshes
  89670. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  89671. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  89672. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  89673. if (_this.webVROptions.defaultLightingOnControllers) {
  89674. if (!_this._lightOnControllers) {
  89675. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  89676. }
  89677. var activateLightOnSubMeshes_1 = function (mesh, light) {
  89678. var children = mesh.getChildren();
  89679. if (children.length !== 0) {
  89680. children.forEach(function (mesh) {
  89681. light.includedOnlyMeshes.push(mesh);
  89682. activateLightOnSubMeshes_1(mesh, light);
  89683. });
  89684. }
  89685. };
  89686. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  89687. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  89688. }
  89689. });
  89690. }
  89691. }
  89692. webVrController_1.attachToPoseControlledCamera(_this);
  89693. // since this is async - sanity check. Is the controller already stored?
  89694. if (_this.controllers.indexOf(webVrController_1) === -1) {
  89695. //add to the controllers array
  89696. _this.controllers.push(webVrController_1);
  89697. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  89698. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  89699. // So we're overriding setting left & right manually to be sure
  89700. var firstViveWandDetected = false;
  89701. for (var i = 0; i < _this.controllers.length; i++) {
  89702. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  89703. if (!firstViveWandDetected) {
  89704. firstViveWandDetected = true;
  89705. _this.controllers[i].hand = "left";
  89706. }
  89707. else {
  89708. _this.controllers[i].hand = "right";
  89709. }
  89710. }
  89711. }
  89712. //did we find enough controllers? Great! let the developer know.
  89713. if (_this.controllers.length >= 2) {
  89714. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  89715. }
  89716. }
  89717. }
  89718. });
  89719. };
  89720. return WebVRFreeCamera;
  89721. }(BABYLON.FreeCamera));
  89722. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  89723. })(BABYLON || (BABYLON = {}));
  89724. //# sourceMappingURL=babylon.webVRCamera.js.map
  89725. var BABYLON;
  89726. (function (BABYLON) {
  89727. // We're mainly based on the logic defined into the FreeCamera code
  89728. /**
  89729. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  89730. * being tilted forward or back and left or right.
  89731. */
  89732. var DeviceOrientationCamera = /** @class */ (function (_super) {
  89733. __extends(DeviceOrientationCamera, _super);
  89734. /**
  89735. * Creates a new device orientation camera
  89736. * @param name The name of the camera
  89737. * @param position The start position camera
  89738. * @param scene The scene the camera belongs to
  89739. */
  89740. function DeviceOrientationCamera(name, position, scene) {
  89741. var _this = _super.call(this, name, position, scene) || this;
  89742. _this._quaternionCache = new BABYLON.Quaternion();
  89743. _this.inputs.addDeviceOrientation();
  89744. return _this;
  89745. }
  89746. /**
  89747. * Gets the current instance class name ("DeviceOrientationCamera").
  89748. * This helps avoiding instanceof at run time.
  89749. * @returns the class name
  89750. */
  89751. DeviceOrientationCamera.prototype.getClassName = function () {
  89752. return "DeviceOrientationCamera";
  89753. };
  89754. /**
  89755. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  89756. */
  89757. DeviceOrientationCamera.prototype._checkInputs = function () {
  89758. _super.prototype._checkInputs.call(this);
  89759. this._quaternionCache.copyFrom(this.rotationQuaternion);
  89760. if (this._initialQuaternion) {
  89761. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  89762. }
  89763. };
  89764. /**
  89765. * Reset the camera to its default orientation on the specified axis only.
  89766. * @param axis The axis to reset
  89767. */
  89768. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  89769. var _this = this;
  89770. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  89771. //can only work if this camera has a rotation quaternion already.
  89772. if (!this.rotationQuaternion)
  89773. return;
  89774. if (!this._initialQuaternion) {
  89775. this._initialQuaternion = new BABYLON.Quaternion();
  89776. }
  89777. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  89778. ['x', 'y', 'z'].forEach(function (axisName) {
  89779. if (!axis[axisName]) {
  89780. _this._initialQuaternion[axisName] = 0;
  89781. }
  89782. else {
  89783. _this._initialQuaternion[axisName] *= -1;
  89784. }
  89785. });
  89786. this._initialQuaternion.normalize();
  89787. //force rotation update
  89788. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  89789. };
  89790. return DeviceOrientationCamera;
  89791. }(BABYLON.FreeCamera));
  89792. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  89793. })(BABYLON || (BABYLON = {}));
  89794. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  89795. var BABYLON;
  89796. (function (BABYLON) {
  89797. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  89798. __extends(VRDeviceOrientationFreeCamera, _super);
  89799. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  89800. if (compensateDistortion === void 0) { compensateDistortion = true; }
  89801. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  89802. var _this = _super.call(this, name, position, scene) || this;
  89803. vrCameraMetrics.compensateDistortion = compensateDistortion;
  89804. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  89805. return _this;
  89806. }
  89807. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  89808. return "VRDeviceOrientationFreeCamera";
  89809. };
  89810. return VRDeviceOrientationFreeCamera;
  89811. }(BABYLON.DeviceOrientationCamera));
  89812. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  89813. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  89814. __extends(VRDeviceOrientationGamepadCamera, _super);
  89815. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  89816. if (compensateDistortion === void 0) { compensateDistortion = true; }
  89817. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  89818. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  89819. _this.inputs.addGamepad();
  89820. return _this;
  89821. }
  89822. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  89823. return "VRDeviceOrientationGamepadCamera";
  89824. };
  89825. return VRDeviceOrientationGamepadCamera;
  89826. }(VRDeviceOrientationFreeCamera));
  89827. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  89828. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  89829. __extends(VRDeviceOrientationArcRotateCamera, _super);
  89830. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  89831. if (compensateDistortion === void 0) { compensateDistortion = true; }
  89832. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  89833. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  89834. vrCameraMetrics.compensateDistortion = compensateDistortion;
  89835. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  89836. _this.inputs.addVRDeviceOrientation();
  89837. return _this;
  89838. }
  89839. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  89840. return "VRDeviceOrientationArcRotateCamera";
  89841. };
  89842. return VRDeviceOrientationArcRotateCamera;
  89843. }(BABYLON.ArcRotateCamera));
  89844. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  89845. })(BABYLON || (BABYLON = {}));
  89846. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  89847. var BABYLON;
  89848. (function (BABYLON) {
  89849. /**
  89850. * Camera used to simulate anaglyphic rendering (based on FreeCamera)
  89851. */
  89852. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  89853. __extends(AnaglyphFreeCamera, _super);
  89854. /**
  89855. * Creates a new AnaglyphFreeCamera
  89856. * @param name defines camera name
  89857. * @param position defines initial position
  89858. * @param interaxialDistance defines distance between each color axis
  89859. * @param scene defines the hosting scene
  89860. */
  89861. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  89862. var _this = _super.call(this, name, position, scene) || this;
  89863. _this.interaxialDistance = interaxialDistance;
  89864. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  89865. return _this;
  89866. }
  89867. /**
  89868. * Gets camera class name
  89869. * @returns AnaglyphFreeCamera
  89870. */
  89871. AnaglyphFreeCamera.prototype.getClassName = function () {
  89872. return "AnaglyphFreeCamera";
  89873. };
  89874. return AnaglyphFreeCamera;
  89875. }(BABYLON.FreeCamera));
  89876. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  89877. /**
  89878. * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera)
  89879. */
  89880. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  89881. __extends(AnaglyphArcRotateCamera, _super);
  89882. /**
  89883. * Creates a new AnaglyphArcRotateCamera
  89884. * @param name defines camera name
  89885. * @param alpha defines alpha angle (in radians)
  89886. * @param beta defines beta angle (in radians)
  89887. * @param radius defines radius
  89888. * @param target defines camera target
  89889. * @param interaxialDistance defines distance between each color axis
  89890. * @param scene defines the hosting scene
  89891. */
  89892. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  89893. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  89894. _this.interaxialDistance = interaxialDistance;
  89895. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  89896. return _this;
  89897. }
  89898. /**
  89899. * Gets camera class name
  89900. * @returns AnaglyphArcRotateCamera
  89901. */
  89902. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  89903. return "AnaglyphArcRotateCamera";
  89904. };
  89905. return AnaglyphArcRotateCamera;
  89906. }(BABYLON.ArcRotateCamera));
  89907. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  89908. /**
  89909. * Camera used to simulate anaglyphic rendering (based on GamepadCamera)
  89910. */
  89911. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  89912. __extends(AnaglyphGamepadCamera, _super);
  89913. /**
  89914. * Creates a new AnaglyphGamepadCamera
  89915. * @param name defines camera name
  89916. * @param position defines initial position
  89917. * @param interaxialDistance defines distance between each color axis
  89918. * @param scene defines the hosting scene
  89919. */
  89920. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  89921. var _this = _super.call(this, name, position, scene) || this;
  89922. _this.interaxialDistance = interaxialDistance;
  89923. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  89924. return _this;
  89925. }
  89926. /**
  89927. * Gets camera class name
  89928. * @returns AnaglyphGamepadCamera
  89929. */
  89930. AnaglyphGamepadCamera.prototype.getClassName = function () {
  89931. return "AnaglyphGamepadCamera";
  89932. };
  89933. return AnaglyphGamepadCamera;
  89934. }(BABYLON.GamepadCamera));
  89935. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  89936. /**
  89937. * Camera used to simulate anaglyphic rendering (based on UniversalCamera)
  89938. */
  89939. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  89940. __extends(AnaglyphUniversalCamera, _super);
  89941. /**
  89942. * Creates a new AnaglyphUniversalCamera
  89943. * @param name defines camera name
  89944. * @param position defines initial position
  89945. * @param interaxialDistance defines distance between each color axis
  89946. * @param scene defines the hosting scene
  89947. */
  89948. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  89949. var _this = _super.call(this, name, position, scene) || this;
  89950. _this.interaxialDistance = interaxialDistance;
  89951. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  89952. return _this;
  89953. }
  89954. /**
  89955. * Gets camera class name
  89956. * @returns AnaglyphUniversalCamera
  89957. */
  89958. AnaglyphUniversalCamera.prototype.getClassName = function () {
  89959. return "AnaglyphUniversalCamera";
  89960. };
  89961. return AnaglyphUniversalCamera;
  89962. }(BABYLON.UniversalCamera));
  89963. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  89964. /**
  89965. * Camera used to simulate stereoscopic rendering (based on FreeCamera)
  89966. */
  89967. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  89968. __extends(StereoscopicFreeCamera, _super);
  89969. /**
  89970. * Creates a new StereoscopicFreeCamera
  89971. * @param name defines camera name
  89972. * @param position defines initial position
  89973. * @param interaxialDistance defines distance between each color axis
  89974. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  89975. * @param scene defines the hosting scene
  89976. */
  89977. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  89978. var _this = _super.call(this, name, position, scene) || this;
  89979. _this.interaxialDistance = interaxialDistance;
  89980. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  89981. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  89982. return _this;
  89983. }
  89984. /**
  89985. * Gets camera class name
  89986. * @returns StereoscopicFreeCamera
  89987. */
  89988. StereoscopicFreeCamera.prototype.getClassName = function () {
  89989. return "StereoscopicFreeCamera";
  89990. };
  89991. return StereoscopicFreeCamera;
  89992. }(BABYLON.FreeCamera));
  89993. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  89994. /**
  89995. * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera)
  89996. */
  89997. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  89998. __extends(StereoscopicArcRotateCamera, _super);
  89999. /**
  90000. * Creates a new StereoscopicArcRotateCamera
  90001. * @param name defines camera name
  90002. * @param alpha defines alpha angle (in radians)
  90003. * @param beta defines beta angle (in radians)
  90004. * @param radius defines radius
  90005. * @param target defines camera target
  90006. * @param interaxialDistance defines distance between each color axis
  90007. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  90008. * @param scene defines the hosting scene
  90009. */
  90010. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  90011. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  90012. _this.interaxialDistance = interaxialDistance;
  90013. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  90014. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  90015. return _this;
  90016. }
  90017. /**
  90018. * Gets camera class name
  90019. * @returns StereoscopicArcRotateCamera
  90020. */
  90021. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  90022. return "StereoscopicArcRotateCamera";
  90023. };
  90024. return StereoscopicArcRotateCamera;
  90025. }(BABYLON.ArcRotateCamera));
  90026. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  90027. /**
  90028. * Camera used to simulate stereoscopic rendering (based on GamepadCamera)
  90029. */
  90030. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  90031. __extends(StereoscopicGamepadCamera, _super);
  90032. /**
  90033. * Creates a new StereoscopicGamepadCamera
  90034. * @param name defines camera name
  90035. * @param position defines initial position
  90036. * @param interaxialDistance defines distance between each color axis
  90037. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  90038. * @param scene defines the hosting scene
  90039. */
  90040. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  90041. var _this = _super.call(this, name, position, scene) || this;
  90042. _this.interaxialDistance = interaxialDistance;
  90043. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  90044. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  90045. return _this;
  90046. }
  90047. /**
  90048. * Gets camera class name
  90049. * @returns StereoscopicGamepadCamera
  90050. */
  90051. StereoscopicGamepadCamera.prototype.getClassName = function () {
  90052. return "StereoscopicGamepadCamera";
  90053. };
  90054. return StereoscopicGamepadCamera;
  90055. }(BABYLON.GamepadCamera));
  90056. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  90057. /**
  90058. * Camera used to simulate stereoscopic rendering (based on UniversalCamera)
  90059. */
  90060. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  90061. __extends(StereoscopicUniversalCamera, _super);
  90062. /**
  90063. * Creates a new StereoscopicUniversalCamera
  90064. * @param name defines camera name
  90065. * @param position defines initial position
  90066. * @param interaxialDistance defines distance between each color axis
  90067. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  90068. * @param scene defines the hosting scene
  90069. */
  90070. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  90071. var _this = _super.call(this, name, position, scene) || this;
  90072. _this.interaxialDistance = interaxialDistance;
  90073. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  90074. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  90075. return _this;
  90076. }
  90077. /**
  90078. * Gets camera class name
  90079. * @returns StereoscopicUniversalCamera
  90080. */
  90081. StereoscopicUniversalCamera.prototype.getClassName = function () {
  90082. return "StereoscopicUniversalCamera";
  90083. };
  90084. return StereoscopicUniversalCamera;
  90085. }(BABYLON.UniversalCamera));
  90086. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  90087. })(BABYLON || (BABYLON = {}));
  90088. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  90089. var BABYLON;
  90090. (function (BABYLON) {
  90091. var VRExperienceHelperGazer = /** @class */ (function () {
  90092. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  90093. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  90094. this.scene = scene;
  90095. this._pointerDownOnMeshAsked = false;
  90096. this._isActionableMesh = false;
  90097. this._teleportationRequestInitiated = false;
  90098. this._teleportationBackRequestInitiated = false;
  90099. this._rotationRightAsked = false;
  90100. this._rotationLeftAsked = false;
  90101. this._dpadPressed = true;
  90102. this._activePointer = false;
  90103. this._id = VRExperienceHelperGazer._idCounter++;
  90104. // Gaze tracker
  90105. if (!gazeTrackerToClone) {
  90106. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  90107. this._gazeTracker.bakeCurrentTransformIntoVertices();
  90108. this._gazeTracker.isPickable = false;
  90109. this._gazeTracker.isVisible = false;
  90110. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  90111. targetMat.specularColor = BABYLON.Color3.Black();
  90112. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  90113. targetMat.backFaceCulling = false;
  90114. this._gazeTracker.material = targetMat;
  90115. }
  90116. else {
  90117. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  90118. }
  90119. }
  90120. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  90121. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  90122. };
  90123. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  90124. this._pointerDownOnMeshAsked = true;
  90125. if (this._currentHit) {
  90126. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  90127. }
  90128. };
  90129. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  90130. if (this._currentHit) {
  90131. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  90132. }
  90133. this._pointerDownOnMeshAsked = false;
  90134. };
  90135. VRExperienceHelperGazer.prototype._activatePointer = function () {
  90136. this._activePointer = true;
  90137. };
  90138. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  90139. this._activePointer = false;
  90140. };
  90141. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  90142. if (distance === void 0) { distance = 100; }
  90143. };
  90144. VRExperienceHelperGazer.prototype.dispose = function () {
  90145. this._interactionsEnabled = false;
  90146. this._teleportationEnabled = false;
  90147. if (this._gazeTracker) {
  90148. this._gazeTracker.dispose();
  90149. }
  90150. };
  90151. VRExperienceHelperGazer._idCounter = 0;
  90152. return VRExperienceHelperGazer;
  90153. }());
  90154. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  90155. __extends(VRExperienceHelperControllerGazer, _super);
  90156. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  90157. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  90158. _this.webVRController = webVRController;
  90159. // Laser pointer
  90160. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  90161. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  90162. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  90163. laserPointerMaterial.alpha = 0.6;
  90164. _this._laserPointer.material = laserPointerMaterial;
  90165. _this._laserPointer.rotation.x = Math.PI / 2;
  90166. _this._laserPointer.position.z = -0.5;
  90167. _this._laserPointer.isVisible = false;
  90168. if (!webVRController.mesh) {
  90169. // Create an empty mesh that is used prior to loading the high quality model
  90170. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  90171. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  90172. preloadPointerPose.rotation.x = -0.7;
  90173. preloadMesh.addChild(preloadPointerPose);
  90174. webVRController.attachToMesh(preloadMesh);
  90175. }
  90176. _this._setLaserPointerParent(webVRController.mesh);
  90177. _this._meshAttachedObserver = webVRController._meshAttachedObservable.add(function (mesh) {
  90178. _this._setLaserPointerParent(mesh);
  90179. });
  90180. return _this;
  90181. }
  90182. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  90183. return this.webVRController.getForwardRay(length);
  90184. };
  90185. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  90186. _super.prototype._activatePointer.call(this);
  90187. this._laserPointer.isVisible = true;
  90188. };
  90189. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  90190. _super.prototype._deactivatePointer.call(this);
  90191. this._laserPointer.isVisible = false;
  90192. };
  90193. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  90194. this._laserPointer.material.emissiveColor = color;
  90195. };
  90196. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  90197. var makeNotPick = function (root) {
  90198. root.name += " laserPointer";
  90199. root.getChildMeshes().forEach(function (c) {
  90200. makeNotPick(c);
  90201. });
  90202. };
  90203. makeNotPick(mesh);
  90204. var childMeshes = mesh.getChildMeshes();
  90205. this.webVRController._pointingPoseNode = null;
  90206. for (var i = 0; i < childMeshes.length; i++) {
  90207. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  90208. mesh = childMeshes[i];
  90209. this.webVRController._pointingPoseNode = mesh;
  90210. break;
  90211. }
  90212. }
  90213. this._laserPointer.parent = mesh;
  90214. };
  90215. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  90216. if (distance === void 0) { distance = 100; }
  90217. this._laserPointer.scaling.y = distance;
  90218. this._laserPointer.position.z = -distance / 2;
  90219. };
  90220. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  90221. _super.prototype.dispose.call(this);
  90222. this._laserPointer.dispose();
  90223. if (this._meshAttachedObserver) {
  90224. this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver);
  90225. }
  90226. };
  90227. return VRExperienceHelperControllerGazer;
  90228. }(VRExperienceHelperGazer));
  90229. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  90230. __extends(VRExperienceHelperCameraGazer, _super);
  90231. function VRExperienceHelperCameraGazer(getCamera, scene) {
  90232. var _this = _super.call(this, scene) || this;
  90233. _this.getCamera = getCamera;
  90234. return _this;
  90235. }
  90236. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  90237. var camera = this.getCamera();
  90238. if (camera) {
  90239. return camera.getForwardRay(length);
  90240. }
  90241. else {
  90242. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  90243. }
  90244. };
  90245. return VRExperienceHelperCameraGazer;
  90246. }(VRExperienceHelperGazer));
  90247. /**
  90248. * Helps to quickly add VR support to an existing scene.
  90249. * See http://doc.babylonjs.com/how_to/webvr_helper
  90250. */
  90251. var VRExperienceHelper = /** @class */ (function () {
  90252. /**
  90253. * Instantiates a VRExperienceHelper.
  90254. * Helps to quickly add VR support to an existing scene.
  90255. * @param scene The scene the VRExperienceHelper belongs to.
  90256. * @param webVROptions Options to modify the vr experience helper's behavior.
  90257. */
  90258. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  90259. if (webVROptions === void 0) { webVROptions = {}; }
  90260. var _this = this;
  90261. this.webVROptions = webVROptions;
  90262. // Can the system support WebVR, even if a headset isn't plugged in?
  90263. this._webVRsupported = false;
  90264. // If WebVR is supported, is a headset plugged in and are we ready to present?
  90265. this._webVRready = false;
  90266. // Are we waiting for the requestPresent callback to complete?
  90267. this._webVRrequesting = false;
  90268. // Are we presenting to the headset right now?
  90269. this._webVRpresenting = false;
  90270. // Are we presenting in the fullscreen fallback?
  90271. this._fullscreenVRpresenting = false;
  90272. /**
  90273. * Observable raised when entering VR.
  90274. */
  90275. this.onEnteringVRObservable = new BABYLON.Observable();
  90276. /**
  90277. * Observable raised when exiting VR.
  90278. */
  90279. this.onExitingVRObservable = new BABYLON.Observable();
  90280. /**
  90281. * Observable raised when controller mesh is loaded.
  90282. */
  90283. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  90284. this._useCustomVRButton = false;
  90285. this._teleportationRequested = false;
  90286. this._teleportActive = false;
  90287. this._floorMeshesCollection = [];
  90288. this._rotationAllowed = true;
  90289. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  90290. this._isDefaultTeleportationTarget = true;
  90291. this._teleportationFillColor = "#444444";
  90292. this._teleportationBorderColor = "#FFFFFF";
  90293. this._rotationAngle = 0;
  90294. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  90295. this._padSensibilityUp = 0.65;
  90296. this._padSensibilityDown = 0.35;
  90297. this.leftController = null;
  90298. this.rightController = null;
  90299. /**
  90300. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  90301. */
  90302. this.onNewMeshSelected = new BABYLON.Observable();
  90303. /**
  90304. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  90305. */
  90306. this.onNewMeshPicked = new BABYLON.Observable();
  90307. /**
  90308. * Observable raised before camera teleportation
  90309. */
  90310. this.onBeforeCameraTeleport = new BABYLON.Observable();
  90311. /**
  90312. * Observable raised after camera teleportation
  90313. */
  90314. this.onAfterCameraTeleport = new BABYLON.Observable();
  90315. /**
  90316. * Observable raised when current selected mesh gets unselected
  90317. */
  90318. this.onSelectedMeshUnselected = new BABYLON.Observable();
  90319. /**
  90320. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  90321. */
  90322. this.teleportationEnabled = true;
  90323. this._teleportationInitialized = false;
  90324. this._interactionsEnabled = false;
  90325. this._interactionsRequested = false;
  90326. this._displayGaze = true;
  90327. this._displayLaserPointer = true;
  90328. this._onResize = function () {
  90329. _this.moveButtonToBottomRight();
  90330. if (_this._fullscreenVRpresenting && _this._webVRready) {
  90331. _this.exitVR();
  90332. }
  90333. };
  90334. this._onFullscreenChange = function () {
  90335. if (document.fullscreen !== undefined) {
  90336. _this._fullscreenVRpresenting = document.fullscreen;
  90337. }
  90338. else if (document.mozFullScreen !== undefined) {
  90339. _this._fullscreenVRpresenting = document.mozFullScreen;
  90340. }
  90341. else if (document.webkitIsFullScreen !== undefined) {
  90342. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  90343. }
  90344. else if (document.msIsFullScreen !== undefined) {
  90345. _this._fullscreenVRpresenting = document.msIsFullScreen;
  90346. }
  90347. if (!_this._fullscreenVRpresenting && _this._canvas) {
  90348. _this.exitVR();
  90349. if (!_this._useCustomVRButton) {
  90350. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  90351. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  90352. }
  90353. }
  90354. };
  90355. this.beforeRender = function () {
  90356. if (_this.leftController && _this.leftController._activePointer) {
  90357. _this._castRayAndSelectObject(_this.leftController);
  90358. }
  90359. if (_this.rightController && _this.rightController._activePointer) {
  90360. _this._castRayAndSelectObject(_this.rightController);
  90361. }
  90362. if (!(_this.leftController && _this.leftController._activePointer) && !(_this.rightController && _this.rightController._activePointer)) {
  90363. _this._castRayAndSelectObject(_this._cameraGazer);
  90364. }
  90365. else {
  90366. _this._cameraGazer._gazeTracker.isVisible = false;
  90367. }
  90368. };
  90369. this._onNewGamepadConnected = function (gamepad) {
  90370. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  90371. if (gamepad.leftStick) {
  90372. gamepad.onleftstickchanged(function (stickValues) {
  90373. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  90374. // Listening to classic/xbox gamepad only if no VR controller is active
  90375. if ((!_this.leftController && !_this.rightController) ||
  90376. ((_this.leftController && !_this.leftController._activePointer) &&
  90377. (_this.rightController && !_this.rightController._activePointer))) {
  90378. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  90379. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  90380. }
  90381. }
  90382. });
  90383. }
  90384. if (gamepad.rightStick) {
  90385. gamepad.onrightstickchanged(function (stickValues) {
  90386. if (_this._teleportationInitialized) {
  90387. _this._checkRotate(stickValues, _this._cameraGazer);
  90388. }
  90389. });
  90390. }
  90391. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  90392. gamepad.onbuttondown(function (buttonPressed) {
  90393. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  90394. _this._cameraGazer._selectionPointerDown();
  90395. }
  90396. });
  90397. gamepad.onbuttonup(function (buttonPressed) {
  90398. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  90399. _this._cameraGazer._selectionPointerUp();
  90400. }
  90401. });
  90402. }
  90403. }
  90404. else {
  90405. var webVRController = gamepad;
  90406. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  90407. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  90408. _this.rightController = controller;
  90409. }
  90410. else {
  90411. _this.leftController = controller;
  90412. }
  90413. _this._tryEnableInteractionOnController(controller);
  90414. }
  90415. };
  90416. // 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
  90417. this._tryEnableInteractionOnController = function (controller) {
  90418. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  90419. _this._enableInteractionOnController(controller);
  90420. }
  90421. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  90422. _this._enableTeleportationOnController(controller);
  90423. }
  90424. };
  90425. this._onNewGamepadDisconnected = function (gamepad) {
  90426. if (gamepad instanceof BABYLON.WebVRController) {
  90427. if (gamepad.hand === "left" && _this.leftController != null) {
  90428. _this.leftController.dispose();
  90429. _this.leftController = null;
  90430. }
  90431. if (gamepad.hand === "right" && _this.rightController != null) {
  90432. _this.rightController.dispose();
  90433. _this.rightController = null;
  90434. }
  90435. }
  90436. };
  90437. this._workingVector = BABYLON.Vector3.Zero();
  90438. this._workingQuaternion = BABYLON.Quaternion.Identity();
  90439. this._workingMatrix = BABYLON.Matrix.Identity();
  90440. this._scene = scene;
  90441. this._canvas = scene.getEngine().getRenderingCanvas();
  90442. // Parse options
  90443. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  90444. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  90445. }
  90446. if (webVROptions.createDeviceOrientationCamera === undefined) {
  90447. webVROptions.createDeviceOrientationCamera = true;
  90448. }
  90449. if (webVROptions.laserToggle === undefined) {
  90450. webVROptions.laserToggle = true;
  90451. }
  90452. if (webVROptions.defaultHeight === undefined) {
  90453. webVROptions.defaultHeight = 1.7;
  90454. }
  90455. if (webVROptions.useCustomVRButton) {
  90456. this._useCustomVRButton = true;
  90457. if (webVROptions.customVRButton) {
  90458. this._btnVR = webVROptions.customVRButton;
  90459. }
  90460. }
  90461. if (webVROptions.rayLength) {
  90462. this._rayLength = webVROptions.rayLength;
  90463. }
  90464. this._defaultHeight = webVROptions.defaultHeight;
  90465. if (webVROptions.positionScale) {
  90466. this._rayLength *= webVROptions.positionScale;
  90467. this._defaultHeight *= webVROptions.positionScale;
  90468. }
  90469. // Set position
  90470. if (this._scene.activeCamera) {
  90471. this._position = this._scene.activeCamera.position.clone();
  90472. }
  90473. else {
  90474. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  90475. }
  90476. // Set non-vr camera
  90477. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  90478. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  90479. // Copy data from existing camera
  90480. if (this._scene.activeCamera) {
  90481. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  90482. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  90483. // Set rotation from previous camera
  90484. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  90485. var targetCamera = this._scene.activeCamera;
  90486. if (targetCamera.rotationQuaternion) {
  90487. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  90488. }
  90489. else {
  90490. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  90491. }
  90492. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  90493. }
  90494. }
  90495. this._scene.activeCamera = this._deviceOrientationCamera;
  90496. if (this._canvas) {
  90497. this._scene.activeCamera.attachControl(this._canvas);
  90498. }
  90499. }
  90500. else {
  90501. this._existingCamera = this._scene.activeCamera;
  90502. }
  90503. // Create VR cameras
  90504. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  90505. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  90506. }
  90507. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  90508. this._webVRCamera.useStandingMatrix();
  90509. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  90510. // Create default button
  90511. if (!this._useCustomVRButton) {
  90512. this._btnVR = document.createElement("BUTTON");
  90513. this._btnVR.className = "babylonVRicon";
  90514. this._btnVR.id = "babylonVRiconbtn";
  90515. this._btnVR.title = "Click to switch to VR";
  90516. 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) }";
  90517. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  90518. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  90519. // css += ".babylonVRicon.vrdisplaysupported { }";
  90520. // css += ".babylonVRicon.vrdisplayready { }";
  90521. // css += ".babylonVRicon.vrdisplayrequesting { }";
  90522. var style = document.createElement('style');
  90523. style.appendChild(document.createTextNode(css));
  90524. document.getElementsByTagName('head')[0].appendChild(style);
  90525. this.moveButtonToBottomRight();
  90526. }
  90527. // VR button click event
  90528. if (this._btnVR) {
  90529. this._btnVR.addEventListener("click", function () {
  90530. if (!_this.isInVRMode) {
  90531. _this.enterVR();
  90532. }
  90533. else {
  90534. _this.exitVR();
  90535. }
  90536. });
  90537. }
  90538. // Window events
  90539. window.addEventListener("resize", this._onResize);
  90540. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  90541. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  90542. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  90543. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  90544. // Display vr button when headset is connected
  90545. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  90546. this.displayVRButton();
  90547. }
  90548. else {
  90549. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  90550. if (e.vrDisplay) {
  90551. _this.displayVRButton();
  90552. }
  90553. });
  90554. }
  90555. // Exiting VR mode using 'ESC' key on desktop
  90556. this._onKeyDown = function (event) {
  90557. if (event.keyCode === 27 && _this.isInVRMode) {
  90558. _this.exitVR();
  90559. }
  90560. };
  90561. document.addEventListener("keydown", this._onKeyDown);
  90562. // Exiting VR mode double tapping the touch screen
  90563. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  90564. if (_this.isInVRMode) {
  90565. _this.exitVR();
  90566. if (_this._fullscreenVRpresenting) {
  90567. _this._scene.getEngine().switchFullscreen(true);
  90568. }
  90569. }
  90570. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  90571. // Listen for WebVR display changes
  90572. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  90573. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  90574. this._onVRRequestPresentStart = function () {
  90575. _this._webVRrequesting = true;
  90576. _this.updateButtonVisibility();
  90577. };
  90578. this._onVRRequestPresentComplete = function (success) {
  90579. _this._webVRrequesting = false;
  90580. _this.updateButtonVisibility();
  90581. };
  90582. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  90583. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  90584. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  90585. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  90586. scene.onDisposeObservable.add(function () {
  90587. _this.dispose();
  90588. });
  90589. // Gamepad connection events
  90590. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  90591. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  90592. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  90593. this.updateButtonVisibility();
  90594. //create easing functions
  90595. this._circleEase = new BABYLON.CircleEase();
  90596. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  90597. if (this.webVROptions.floorMeshes) {
  90598. this.enableTeleportation({ floorMeshes: this.webVROptions.floorMeshes });
  90599. }
  90600. }
  90601. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  90602. /** Return this.onEnteringVRObservable
  90603. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  90604. */
  90605. get: function () {
  90606. return this.onEnteringVRObservable;
  90607. },
  90608. enumerable: true,
  90609. configurable: true
  90610. });
  90611. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  90612. /** Return this.onExitingVRObservable
  90613. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  90614. */
  90615. get: function () {
  90616. return this.onExitingVRObservable;
  90617. },
  90618. enumerable: true,
  90619. configurable: true
  90620. });
  90621. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  90622. /** Return this.onControllerMeshLoadedObservable
  90623. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  90624. */
  90625. get: function () {
  90626. return this.onControllerMeshLoadedObservable;
  90627. },
  90628. enumerable: true,
  90629. configurable: true
  90630. });
  90631. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  90632. /**
  90633. * The mesh used to display where the user is going to teleport.
  90634. */
  90635. get: function () {
  90636. return this._teleportationTarget;
  90637. },
  90638. /**
  90639. * Sets the mesh to be used to display where the user is going to teleport.
  90640. */
  90641. set: function (value) {
  90642. if (value) {
  90643. value.name = "teleportationTarget";
  90644. this._isDefaultTeleportationTarget = false;
  90645. this._teleportationTarget = value;
  90646. }
  90647. },
  90648. enumerable: true,
  90649. configurable: true
  90650. });
  90651. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  90652. /**
  90653. * The mesh used to display where the user is selecting,
  90654. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  90655. * See http://doc.babylonjs.com/resources/baking_transformations
  90656. */
  90657. get: function () {
  90658. return this._cameraGazer._gazeTracker;
  90659. },
  90660. set: function (value) {
  90661. if (value) {
  90662. this._cameraGazer._gazeTracker = value;
  90663. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  90664. this._cameraGazer._gazeTracker.isPickable = false;
  90665. this._cameraGazer._gazeTracker.isVisible = false;
  90666. this._cameraGazer._gazeTracker.name = "gazeTracker";
  90667. if (this.leftController) {
  90668. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  90669. }
  90670. if (this.rightController) {
  90671. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  90672. }
  90673. }
  90674. },
  90675. enumerable: true,
  90676. configurable: true
  90677. });
  90678. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  90679. /**
  90680. * If the ray of the gaze should be displayed.
  90681. */
  90682. get: function () {
  90683. return this._displayGaze;
  90684. },
  90685. /**
  90686. * Sets if the ray of the gaze should be displayed.
  90687. */
  90688. set: function (value) {
  90689. this._displayGaze = value;
  90690. if (!value) {
  90691. this._cameraGazer._gazeTracker.isVisible = false;
  90692. if (this.leftController) {
  90693. this.leftController._gazeTracker.isVisible = false;
  90694. }
  90695. if (this.rightController) {
  90696. this.rightController._gazeTracker.isVisible = false;
  90697. }
  90698. }
  90699. },
  90700. enumerable: true,
  90701. configurable: true
  90702. });
  90703. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  90704. /**
  90705. * If the ray of the LaserPointer should be displayed.
  90706. */
  90707. get: function () {
  90708. return this._displayLaserPointer;
  90709. },
  90710. /**
  90711. * Sets if the ray of the LaserPointer should be displayed.
  90712. */
  90713. set: function (value) {
  90714. this._displayLaserPointer = value;
  90715. if (!value) {
  90716. if (this.rightController) {
  90717. this.rightController._deactivatePointer();
  90718. this.rightController._gazeTracker.isVisible = false;
  90719. }
  90720. if (this.leftController) {
  90721. this.leftController._deactivatePointer();
  90722. this.leftController._gazeTracker.isVisible = false;
  90723. }
  90724. }
  90725. else {
  90726. if (this.rightController) {
  90727. this.rightController._activatePointer();
  90728. }
  90729. if (this.leftController) {
  90730. this.leftController._activatePointer();
  90731. }
  90732. }
  90733. },
  90734. enumerable: true,
  90735. configurable: true
  90736. });
  90737. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  90738. /**
  90739. * The deviceOrientationCamera used as the camera when not in VR.
  90740. */
  90741. get: function () {
  90742. return this._deviceOrientationCamera;
  90743. },
  90744. enumerable: true,
  90745. configurable: true
  90746. });
  90747. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  90748. /**
  90749. * Based on the current WebVR support, returns the current VR camera used.
  90750. */
  90751. get: function () {
  90752. if (this._webVRready) {
  90753. return this._webVRCamera;
  90754. }
  90755. else {
  90756. return this._scene.activeCamera;
  90757. }
  90758. },
  90759. enumerable: true,
  90760. configurable: true
  90761. });
  90762. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  90763. /**
  90764. * The webVRCamera which is used when in VR.
  90765. */
  90766. get: function () {
  90767. return this._webVRCamera;
  90768. },
  90769. enumerable: true,
  90770. configurable: true
  90771. });
  90772. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  90773. /**
  90774. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  90775. */
  90776. get: function () {
  90777. return this._vrDeviceOrientationCamera;
  90778. },
  90779. enumerable: true,
  90780. configurable: true
  90781. });
  90782. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  90783. get: function () {
  90784. var result = this._cameraGazer._teleportationRequestInitiated
  90785. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  90786. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  90787. return result;
  90788. },
  90789. enumerable: true,
  90790. configurable: true
  90791. });
  90792. // Raised when one of the controller has loaded successfully its associated default mesh
  90793. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  90794. if (this.leftController && this.leftController.webVRController == webVRController) {
  90795. if (webVRController.mesh) {
  90796. this.leftController._setLaserPointerParent(webVRController.mesh);
  90797. }
  90798. }
  90799. if (this.rightController && this.rightController.webVRController == webVRController) {
  90800. if (webVRController.mesh) {
  90801. this.rightController._setLaserPointerParent(webVRController.mesh);
  90802. }
  90803. }
  90804. try {
  90805. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  90806. }
  90807. catch (err) {
  90808. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  90809. }
  90810. };
  90811. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  90812. /**
  90813. * Gets a value indicating if we are currently in VR mode.
  90814. */
  90815. get: function () {
  90816. return this._webVRpresenting || this._fullscreenVRpresenting;
  90817. },
  90818. enumerable: true,
  90819. configurable: true
  90820. });
  90821. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  90822. var vrDisplay = this._scene.getEngine().getVRDevice();
  90823. if (vrDisplay) {
  90824. var wasPresenting = this._webVRpresenting;
  90825. // A VR display is connected
  90826. this._webVRpresenting = vrDisplay.isPresenting;
  90827. if (wasPresenting && !this._webVRpresenting)
  90828. this.exitVR();
  90829. }
  90830. else {
  90831. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  90832. }
  90833. this.updateButtonVisibility();
  90834. };
  90835. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  90836. this._webVRsupported = eventArgs.vrSupported;
  90837. this._webVRready = !!eventArgs.vrDisplay;
  90838. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  90839. this.updateButtonVisibility();
  90840. };
  90841. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  90842. if (this._canvas && !this._useCustomVRButton) {
  90843. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  90844. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  90845. }
  90846. };
  90847. VRExperienceHelper.prototype.displayVRButton = function () {
  90848. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  90849. document.body.appendChild(this._btnVR);
  90850. this._btnVRDisplayed = true;
  90851. }
  90852. };
  90853. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  90854. if (!this._btnVR || this._useCustomVRButton) {
  90855. return;
  90856. }
  90857. this._btnVR.className = "babylonVRicon";
  90858. if (this.isInVRMode) {
  90859. this._btnVR.className += " vrdisplaypresenting";
  90860. }
  90861. else {
  90862. if (this._webVRready)
  90863. this._btnVR.className += " vrdisplayready";
  90864. if (this._webVRsupported)
  90865. this._btnVR.className += " vrdisplaysupported";
  90866. if (this._webVRrequesting)
  90867. this._btnVR.className += " vrdisplayrequesting";
  90868. }
  90869. };
  90870. /**
  90871. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  90872. * Otherwise, will use the fullscreen API.
  90873. */
  90874. VRExperienceHelper.prototype.enterVR = function () {
  90875. if (this.onEnteringVRObservable) {
  90876. try {
  90877. this.onEnteringVRObservable.notifyObservers(this);
  90878. }
  90879. catch (err) {
  90880. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  90881. }
  90882. }
  90883. if (this._scene.activeCamera) {
  90884. this._position = this._scene.activeCamera.position.clone();
  90885. // make sure that we return to the last active camera
  90886. this._existingCamera = this._scene.activeCamera;
  90887. }
  90888. if (this._webVRrequesting)
  90889. return;
  90890. // If WebVR is supported and a headset is connected
  90891. if (this._webVRready) {
  90892. if (!this._webVRpresenting) {
  90893. this._webVRCamera.position = this._position;
  90894. this._scene.activeCamera = this._webVRCamera;
  90895. }
  90896. }
  90897. else if (this._vrDeviceOrientationCamera) {
  90898. this._vrDeviceOrientationCamera.position = this._position;
  90899. if (this._scene.activeCamera) {
  90900. this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  90901. }
  90902. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  90903. this._scene.getEngine().switchFullscreen(true);
  90904. this.updateButtonVisibility();
  90905. }
  90906. if (this._scene.activeCamera && this._canvas) {
  90907. this._scene.activeCamera.attachControl(this._canvas);
  90908. }
  90909. if (this._interactionsEnabled) {
  90910. this._scene.registerBeforeRender(this.beforeRender);
  90911. }
  90912. };
  90913. /**
  90914. * Attempt to exit VR, or fullscreen.
  90915. */
  90916. VRExperienceHelper.prototype.exitVR = function () {
  90917. if (this.onExitingVRObservable) {
  90918. try {
  90919. this.onExitingVRObservable.notifyObservers(this);
  90920. }
  90921. catch (err) {
  90922. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  90923. }
  90924. }
  90925. if (this._webVRpresenting) {
  90926. this._scene.getEngine().disableVR();
  90927. }
  90928. if (this._scene.activeCamera) {
  90929. this._position = this._scene.activeCamera.position.clone();
  90930. }
  90931. if (this._deviceOrientationCamera) {
  90932. this._deviceOrientationCamera.position = this._position;
  90933. this._scene.activeCamera = this._deviceOrientationCamera;
  90934. if (this._canvas) {
  90935. this._scene.activeCamera.attachControl(this._canvas);
  90936. }
  90937. }
  90938. else if (this._existingCamera) {
  90939. this._existingCamera.position = this._position;
  90940. this._scene.activeCamera = this._existingCamera;
  90941. }
  90942. this.updateButtonVisibility();
  90943. if (this._interactionsEnabled) {
  90944. this._scene.unregisterBeforeRender(this.beforeRender);
  90945. }
  90946. // resize to update width and height when exiting vr exits fullscreen
  90947. this._scene.getEngine().resize();
  90948. };
  90949. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  90950. /**
  90951. * The position of the vr experience helper.
  90952. */
  90953. get: function () {
  90954. return this._position;
  90955. },
  90956. /**
  90957. * Sets the position of the vr experience helper.
  90958. */
  90959. set: function (value) {
  90960. this._position = value;
  90961. if (this._scene.activeCamera) {
  90962. this._scene.activeCamera.position = value;
  90963. }
  90964. },
  90965. enumerable: true,
  90966. configurable: true
  90967. });
  90968. /**
  90969. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  90970. */
  90971. VRExperienceHelper.prototype.enableInteractions = function () {
  90972. var _this = this;
  90973. if (!this._interactionsEnabled) {
  90974. this._interactionsRequested = true;
  90975. if (this.leftController) {
  90976. this._enableInteractionOnController(this.leftController);
  90977. }
  90978. if (this.rightController) {
  90979. this._enableInteractionOnController(this.rightController);
  90980. }
  90981. this.raySelectionPredicate = function (mesh) {
  90982. return mesh.isVisible;
  90983. };
  90984. this.meshSelectionPredicate = function (mesh) {
  90985. return true;
  90986. };
  90987. this._raySelectionPredicate = function (mesh) {
  90988. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  90989. && mesh.name.indexOf("teleportationTarget") === -1
  90990. && mesh.name.indexOf("torusTeleportation") === -1
  90991. && mesh.name.indexOf("laserPointer") === -1)) {
  90992. return _this.raySelectionPredicate(mesh);
  90993. }
  90994. return false;
  90995. };
  90996. this._interactionsEnabled = true;
  90997. }
  90998. };
  90999. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  91000. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  91001. if (this._floorMeshesCollection[i].id === mesh.id) {
  91002. return true;
  91003. }
  91004. }
  91005. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  91006. return true;
  91007. }
  91008. return false;
  91009. };
  91010. /**
  91011. * Adds a floor mesh to be used for teleportation.
  91012. * @param floorMesh the mesh to be used for teleportation.
  91013. */
  91014. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  91015. if (!this._floorMeshesCollection) {
  91016. return;
  91017. }
  91018. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  91019. return;
  91020. }
  91021. this._floorMeshesCollection.push(floorMesh);
  91022. };
  91023. /**
  91024. * Removes a floor mesh from being used for teleportation.
  91025. * @param floorMesh the mesh to be removed.
  91026. */
  91027. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  91028. if (!this._floorMeshesCollection) {
  91029. return;
  91030. }
  91031. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  91032. if (meshIndex !== -1) {
  91033. this._floorMeshesCollection.splice(meshIndex, 1);
  91034. }
  91035. };
  91036. /**
  91037. * Enables interactions and teleportation using the VR controllers and gaze.
  91038. * @param vrTeleportationOptions options to modify teleportation behavior.
  91039. */
  91040. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  91041. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  91042. if (!this._teleportationInitialized) {
  91043. this._teleportationRequested = true;
  91044. this.enableInteractions();
  91045. if (vrTeleportationOptions.floorMeshName) {
  91046. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  91047. }
  91048. if (vrTeleportationOptions.floorMeshes) {
  91049. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  91050. }
  91051. if (this.leftController != null) {
  91052. this._enableTeleportationOnController(this.leftController);
  91053. }
  91054. if (this.rightController != null) {
  91055. this._enableTeleportationOnController(this.rightController);
  91056. }
  91057. // Creates an image processing post process for the vignette not relying
  91058. // on the main scene configuration for image processing to reduce setup and spaces
  91059. // (gamma/linear) conflicts.
  91060. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  91061. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  91062. imageProcessingConfiguration.vignetteEnabled = true;
  91063. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  91064. this._webVRCamera.detachPostProcess(this._postProcessMove);
  91065. this._teleportationInitialized = true;
  91066. if (this._isDefaultTeleportationTarget) {
  91067. this._createTeleportationCircles();
  91068. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  91069. }
  91070. }
  91071. };
  91072. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  91073. var _this = this;
  91074. var controllerMesh = controller.webVRController.mesh;
  91075. if (controllerMesh) {
  91076. controller._interactionsEnabled = true;
  91077. controller._activatePointer();
  91078. if (this.webVROptions.laserToggle) {
  91079. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  91080. // Enabling / disabling laserPointer
  91081. if (_this._displayLaserPointer && stateObject.value === 1) {
  91082. if (controller._activePointer) {
  91083. controller._deactivatePointer();
  91084. }
  91085. else {
  91086. controller._activatePointer();
  91087. }
  91088. if (_this.displayGaze) {
  91089. controller._gazeTracker.isVisible = controller._activePointer;
  91090. }
  91091. }
  91092. });
  91093. }
  91094. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  91095. if (!controller._pointerDownOnMeshAsked) {
  91096. if (stateObject.value > _this._padSensibilityUp) {
  91097. controller._selectionPointerDown();
  91098. }
  91099. }
  91100. else if (stateObject.value < _this._padSensibilityDown) {
  91101. controller._selectionPointerUp();
  91102. }
  91103. });
  91104. }
  91105. };
  91106. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  91107. // Dont teleport if another gaze already requested teleportation
  91108. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  91109. return;
  91110. }
  91111. if (!gazer._teleportationRequestInitiated) {
  91112. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  91113. gazer._activatePointer();
  91114. gazer._teleportationRequestInitiated = true;
  91115. }
  91116. }
  91117. else {
  91118. // Listening to the proper controller values changes to confirm teleportation
  91119. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  91120. if (this._teleportActive) {
  91121. this._teleportCamera(this._haloCenter);
  91122. }
  91123. gazer._teleportationRequestInitiated = false;
  91124. }
  91125. }
  91126. };
  91127. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  91128. // Only rotate when user is not currently selecting a teleportation location
  91129. if (gazer._teleportationRequestInitiated) {
  91130. return;
  91131. }
  91132. if (!gazer._rotationLeftAsked) {
  91133. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  91134. gazer._rotationLeftAsked = true;
  91135. if (this._rotationAllowed) {
  91136. this._rotateCamera(false);
  91137. }
  91138. }
  91139. }
  91140. else {
  91141. if (stateObject.x > -this._padSensibilityDown) {
  91142. gazer._rotationLeftAsked = false;
  91143. }
  91144. }
  91145. if (!gazer._rotationRightAsked) {
  91146. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  91147. gazer._rotationRightAsked = true;
  91148. if (this._rotationAllowed) {
  91149. this._rotateCamera(true);
  91150. }
  91151. }
  91152. }
  91153. else {
  91154. if (stateObject.x < this._padSensibilityDown) {
  91155. gazer._rotationRightAsked = false;
  91156. }
  91157. }
  91158. };
  91159. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  91160. // Only teleport backwards when user is not currently selecting a teleportation location
  91161. if (gazer._teleportationRequestInitiated) {
  91162. return;
  91163. }
  91164. // Teleport backwards
  91165. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  91166. if (!gazer._teleportationBackRequestInitiated) {
  91167. if (!this.currentVRCamera) {
  91168. return;
  91169. }
  91170. // Get rotation and position of the current camera
  91171. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  91172. var position = this.currentVRCamera.position;
  91173. // If the camera has device position, use that instead
  91174. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  91175. rotation = this.currentVRCamera.deviceRotationQuaternion;
  91176. position = this.currentVRCamera.devicePosition;
  91177. }
  91178. // Get matrix with only the y rotation of the device rotation
  91179. rotation.toEulerAnglesToRef(this._workingVector);
  91180. this._workingVector.z = 0;
  91181. this._workingVector.x = 0;
  91182. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  91183. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  91184. // Rotate backwards ray by device rotation to cast at the ground behind the user
  91185. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  91186. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  91187. var ray = new BABYLON.Ray(position, this._workingVector);
  91188. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  91189. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  91190. this._teleportCamera(hit.pickedPoint);
  91191. }
  91192. gazer._teleportationBackRequestInitiated = true;
  91193. }
  91194. }
  91195. else {
  91196. gazer._teleportationBackRequestInitiated = false;
  91197. }
  91198. };
  91199. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  91200. var _this = this;
  91201. var controllerMesh = controller.webVRController.mesh;
  91202. if (controllerMesh) {
  91203. if (!controller._interactionsEnabled) {
  91204. this._enableInteractionOnController(controller);
  91205. }
  91206. controller._interactionsEnabled = true;
  91207. controller._teleportationEnabled = true;
  91208. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  91209. controller._dpadPressed = false;
  91210. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  91211. controller._dpadPressed = stateObject.pressed;
  91212. if (!controller._dpadPressed) {
  91213. controller._rotationLeftAsked = false;
  91214. controller._rotationRightAsked = false;
  91215. controller._teleportationBackRequestInitiated = false;
  91216. }
  91217. });
  91218. }
  91219. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  91220. if (_this.teleportationEnabled) {
  91221. _this._checkTeleportBackwards(stateObject, controller);
  91222. _this._checkTeleportWithRay(stateObject, controller);
  91223. }
  91224. _this._checkRotate(stateObject, controller);
  91225. });
  91226. }
  91227. };
  91228. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  91229. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  91230. this._teleportationTarget.isPickable = false;
  91231. var length = 512;
  91232. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  91233. dynamicTexture.hasAlpha = true;
  91234. var context = dynamicTexture.getContext();
  91235. var centerX = length / 2;
  91236. var centerY = length / 2;
  91237. var radius = 200;
  91238. context.beginPath();
  91239. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  91240. context.fillStyle = this._teleportationFillColor;
  91241. context.fill();
  91242. context.lineWidth = 10;
  91243. context.strokeStyle = this._teleportationBorderColor;
  91244. context.stroke();
  91245. context.closePath();
  91246. dynamicTexture.update();
  91247. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  91248. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  91249. this._teleportationTarget.material = teleportationCircleMaterial;
  91250. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  91251. torus.isPickable = false;
  91252. torus.parent = this._teleportationTarget;
  91253. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  91254. var keys = [];
  91255. keys.push({
  91256. frame: 0,
  91257. value: 0
  91258. });
  91259. keys.push({
  91260. frame: 30,
  91261. value: 0.4
  91262. });
  91263. keys.push({
  91264. frame: 60,
  91265. value: 0
  91266. });
  91267. animationInnerCircle.setKeys(keys);
  91268. var easingFunction = new BABYLON.SineEase();
  91269. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  91270. animationInnerCircle.setEasingFunction(easingFunction);
  91271. torus.animations = [];
  91272. torus.animations.push(animationInnerCircle);
  91273. this._scene.beginAnimation(torus, 0, 60, true);
  91274. this._hideTeleportationTarget();
  91275. };
  91276. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  91277. this._teleportActive = true;
  91278. if (this._teleportationInitialized) {
  91279. this._teleportationTarget.isVisible = true;
  91280. if (this._isDefaultTeleportationTarget) {
  91281. this._teleportationTarget.getChildren()[0].isVisible = true;
  91282. }
  91283. }
  91284. };
  91285. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  91286. this._teleportActive = false;
  91287. if (this._teleportationInitialized) {
  91288. this._teleportationTarget.isVisible = false;
  91289. if (this._isDefaultTeleportationTarget) {
  91290. this._teleportationTarget.getChildren()[0].isVisible = false;
  91291. }
  91292. }
  91293. };
  91294. VRExperienceHelper.prototype._rotateCamera = function (right) {
  91295. var _this = this;
  91296. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  91297. return;
  91298. }
  91299. if (right) {
  91300. this._rotationAngle++;
  91301. }
  91302. else {
  91303. this._rotationAngle--;
  91304. }
  91305. this.currentVRCamera.animations = [];
  91306. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  91307. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  91308. var animationRotationKeys = [];
  91309. animationRotationKeys.push({
  91310. frame: 0,
  91311. value: this.currentVRCamera.rotationQuaternion
  91312. });
  91313. animationRotationKeys.push({
  91314. frame: 6,
  91315. value: target
  91316. });
  91317. animationRotation.setKeys(animationRotationKeys);
  91318. animationRotation.setEasingFunction(this._circleEase);
  91319. this.currentVRCamera.animations.push(animationRotation);
  91320. this._postProcessMove.animations = [];
  91321. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  91322. var vignetteWeightKeys = [];
  91323. vignetteWeightKeys.push({
  91324. frame: 0,
  91325. value: 0
  91326. });
  91327. vignetteWeightKeys.push({
  91328. frame: 3,
  91329. value: 4
  91330. });
  91331. vignetteWeightKeys.push({
  91332. frame: 6,
  91333. value: 0
  91334. });
  91335. animationPP.setKeys(vignetteWeightKeys);
  91336. animationPP.setEasingFunction(this._circleEase);
  91337. this._postProcessMove.animations.push(animationPP);
  91338. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  91339. var vignetteStretchKeys = [];
  91340. vignetteStretchKeys.push({
  91341. frame: 0,
  91342. value: 0
  91343. });
  91344. vignetteStretchKeys.push({
  91345. frame: 3,
  91346. value: 10
  91347. });
  91348. vignetteStretchKeys.push({
  91349. frame: 6,
  91350. value: 0
  91351. });
  91352. animationPP2.setKeys(vignetteStretchKeys);
  91353. animationPP2.setEasingFunction(this._circleEase);
  91354. this._postProcessMove.animations.push(animationPP2);
  91355. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  91356. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  91357. this._postProcessMove.samples = 4;
  91358. this._webVRCamera.attachPostProcess(this._postProcessMove);
  91359. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  91360. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  91361. });
  91362. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  91363. };
  91364. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer, ray) {
  91365. if (hit.pickedPoint) {
  91366. if (gazer._teleportationRequestInitiated) {
  91367. this._displayTeleportationTarget();
  91368. this._haloCenter.copyFrom(hit.pickedPoint);
  91369. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  91370. }
  91371. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(true, false), ray);
  91372. if (pickNormal) {
  91373. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  91374. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  91375. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  91376. }
  91377. this._teleportationTarget.position.y += 0.1;
  91378. }
  91379. };
  91380. VRExperienceHelper.prototype._teleportCamera = function (location) {
  91381. var _this = this;
  91382. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  91383. return;
  91384. }
  91385. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  91386. // offset of the headset from the anchor.
  91387. if (this.webVRCamera.leftCamera) {
  91388. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  91389. this._workingVector.subtractInPlace(this.webVRCamera.position);
  91390. location.subtractToRef(this._workingVector, this._workingVector);
  91391. }
  91392. else {
  91393. this._workingVector.copyFrom(location);
  91394. }
  91395. // Add height to account for user's height offset
  91396. if (this.isInVRMode) {
  91397. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  91398. }
  91399. else {
  91400. this._workingVector.y += this._defaultHeight;
  91401. }
  91402. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  91403. // Create animation from the camera's position to the new location
  91404. this.currentVRCamera.animations = [];
  91405. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  91406. var animationCameraTeleportationKeys = [{
  91407. frame: 0,
  91408. value: this.currentVRCamera.position
  91409. },
  91410. {
  91411. frame: 11,
  91412. value: this._workingVector
  91413. }
  91414. ];
  91415. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  91416. animationCameraTeleportation.setEasingFunction(this._circleEase);
  91417. this.currentVRCamera.animations.push(animationCameraTeleportation);
  91418. this._postProcessMove.animations = [];
  91419. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  91420. var vignetteWeightKeys = [];
  91421. vignetteWeightKeys.push({
  91422. frame: 0,
  91423. value: 0
  91424. });
  91425. vignetteWeightKeys.push({
  91426. frame: 5,
  91427. value: 8
  91428. });
  91429. vignetteWeightKeys.push({
  91430. frame: 11,
  91431. value: 0
  91432. });
  91433. animationPP.setKeys(vignetteWeightKeys);
  91434. this._postProcessMove.animations.push(animationPP);
  91435. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  91436. var vignetteStretchKeys = [];
  91437. vignetteStretchKeys.push({
  91438. frame: 0,
  91439. value: 0
  91440. });
  91441. vignetteStretchKeys.push({
  91442. frame: 5,
  91443. value: 10
  91444. });
  91445. vignetteStretchKeys.push({
  91446. frame: 11,
  91447. value: 0
  91448. });
  91449. animationPP2.setKeys(vignetteStretchKeys);
  91450. this._postProcessMove.animations.push(animationPP2);
  91451. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  91452. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  91453. this._webVRCamera.attachPostProcess(this._postProcessMove);
  91454. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  91455. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  91456. });
  91457. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  91458. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  91459. });
  91460. this._hideTeleportationTarget();
  91461. };
  91462. VRExperienceHelper.prototype._convertNormalToDirectionOfRay = function (normal, ray) {
  91463. if (normal) {
  91464. var angle = Math.acos(BABYLON.Vector3.Dot(normal, ray.direction));
  91465. if (angle < Math.PI / 2) {
  91466. normal.scaleInPlace(-1);
  91467. }
  91468. }
  91469. return normal;
  91470. };
  91471. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  91472. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  91473. return;
  91474. }
  91475. var ray = gazer._getForwardRay(this._rayLength);
  91476. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  91477. if (hit) {
  91478. // Populate the contrllers mesh that can be used for drag/drop
  91479. if (gazer._laserPointer) {
  91480. hit.originMesh = gazer._laserPointer.parent;
  91481. }
  91482. this._scene.simulatePointerMove(hit, { pointerId: gazer._id });
  91483. }
  91484. gazer._currentHit = hit;
  91485. // Moving the gazeTracker on the mesh face targetted
  91486. if (hit && hit.pickedPoint) {
  91487. if (this._displayGaze) {
  91488. var multiplier = 1;
  91489. gazer._gazeTracker.isVisible = true;
  91490. if (gazer._isActionableMesh) {
  91491. multiplier = 3;
  91492. }
  91493. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  91494. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  91495. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  91496. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(), ray);
  91497. // To avoid z-fighting
  91498. var deltaFighting = 0.002;
  91499. if (pickNormal) {
  91500. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  91501. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  91502. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  91503. }
  91504. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  91505. if (gazer._gazeTracker.position.x < 0) {
  91506. gazer._gazeTracker.position.x += deltaFighting;
  91507. }
  91508. else {
  91509. gazer._gazeTracker.position.x -= deltaFighting;
  91510. }
  91511. if (gazer._gazeTracker.position.y < 0) {
  91512. gazer._gazeTracker.position.y += deltaFighting;
  91513. }
  91514. else {
  91515. gazer._gazeTracker.position.y -= deltaFighting;
  91516. }
  91517. if (gazer._gazeTracker.position.z < 0) {
  91518. gazer._gazeTracker.position.z += deltaFighting;
  91519. }
  91520. else {
  91521. gazer._gazeTracker.position.z -= deltaFighting;
  91522. }
  91523. }
  91524. // Changing the size of the laser pointer based on the distance from the targetted point
  91525. gazer._updatePointerDistance(hit.distance);
  91526. }
  91527. else {
  91528. gazer._updatePointerDistance();
  91529. gazer._gazeTracker.isVisible = false;
  91530. }
  91531. if (hit && hit.pickedMesh) {
  91532. // The object selected is the floor, we're in a teleportation scenario
  91533. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  91534. // Moving the teleportation area to this targetted point
  91535. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  91536. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  91537. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  91538. }
  91539. gazer._currentMeshSelected = null;
  91540. if (gazer._teleportationRequestInitiated) {
  91541. this._moveTeleportationSelectorTo(hit, gazer, ray);
  91542. }
  91543. return;
  91544. }
  91545. // If not, we're in a selection scenario
  91546. //this._teleportationAllowed = false;
  91547. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  91548. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  91549. this.onNewMeshPicked.notifyObservers(hit);
  91550. gazer._currentMeshSelected = hit.pickedMesh;
  91551. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  91552. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  91553. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  91554. gazer._isActionableMesh = true;
  91555. }
  91556. else {
  91557. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  91558. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  91559. gazer._isActionableMesh = false;
  91560. }
  91561. try {
  91562. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  91563. }
  91564. catch (err) {
  91565. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  91566. }
  91567. }
  91568. else {
  91569. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  91570. gazer._currentMeshSelected = null;
  91571. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  91572. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  91573. }
  91574. }
  91575. }
  91576. else {
  91577. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  91578. gazer._currentMeshSelected = null;
  91579. //this._teleportationAllowed = false;
  91580. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  91581. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  91582. }
  91583. };
  91584. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  91585. if (mesh) {
  91586. this.onSelectedMeshUnselected.notifyObservers(mesh);
  91587. }
  91588. };
  91589. /**
  91590. * Sets the color of the laser ray from the vr controllers.
  91591. * @param color new color for the ray.
  91592. */
  91593. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  91594. if (this.leftController) {
  91595. this.leftController._setLaserPointerColor(color);
  91596. }
  91597. if (this.rightController) {
  91598. this.rightController._setLaserPointerColor(color);
  91599. }
  91600. };
  91601. /**
  91602. * Sets the color of the ray from the vr headsets gaze.
  91603. * @param color new color for the ray.
  91604. */
  91605. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  91606. if (!this._cameraGazer._gazeTracker.material) {
  91607. return;
  91608. }
  91609. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  91610. if (this.leftController) {
  91611. this.leftController._gazeTracker.material.emissiveColor = color;
  91612. }
  91613. if (this.rightController) {
  91614. this.rightController._gazeTracker.material.emissiveColor = color;
  91615. }
  91616. };
  91617. /**
  91618. * Exits VR and disposes of the vr experience helper
  91619. */
  91620. VRExperienceHelper.prototype.dispose = function () {
  91621. if (this.isInVRMode) {
  91622. this.exitVR();
  91623. }
  91624. if (this._postProcessMove) {
  91625. this._postProcessMove.dispose();
  91626. }
  91627. if (this._webVRCamera) {
  91628. this._webVRCamera.dispose();
  91629. }
  91630. if (this._vrDeviceOrientationCamera) {
  91631. this._vrDeviceOrientationCamera.dispose();
  91632. }
  91633. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  91634. document.body.removeChild(this._btnVR);
  91635. }
  91636. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  91637. this._deviceOrientationCamera.dispose();
  91638. }
  91639. if (this._cameraGazer) {
  91640. this._cameraGazer.dispose();
  91641. }
  91642. if (this.leftController) {
  91643. this.leftController.dispose();
  91644. }
  91645. if (this.rightController) {
  91646. this.rightController.dispose();
  91647. }
  91648. if (this._teleportationTarget) {
  91649. this._teleportationTarget.dispose();
  91650. }
  91651. this._floorMeshesCollection = [];
  91652. document.removeEventListener("keydown", this._onKeyDown);
  91653. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  91654. window.removeEventListener("resize", this._onResize);
  91655. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  91656. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  91657. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  91658. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  91659. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  91660. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  91661. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  91662. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  91663. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  91664. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  91665. this._scene.unregisterBeforeRender(this.beforeRender);
  91666. };
  91667. /**
  91668. * Gets the name of the VRExperienceHelper class
  91669. * @returns "VRExperienceHelper"
  91670. */
  91671. VRExperienceHelper.prototype.getClassName = function () {
  91672. return "VRExperienceHelper";
  91673. };
  91674. return VRExperienceHelper;
  91675. }());
  91676. BABYLON.VRExperienceHelper = VRExperienceHelper;
  91677. })(BABYLON || (BABYLON = {}));
  91678. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  91679. // Mainly based on these 2 articles :
  91680. // 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
  91681. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  91682. var BABYLON;
  91683. (function (BABYLON) {
  91684. /**
  91685. * Defines the potential axis of a Joystick
  91686. */
  91687. var JoystickAxis;
  91688. (function (JoystickAxis) {
  91689. /** X axis */
  91690. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  91691. /** Y axis */
  91692. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  91693. /** Z axis */
  91694. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  91695. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  91696. /**
  91697. * Class used to define virtual joystick (used in touch mode)
  91698. */
  91699. var VirtualJoystick = /** @class */ (function () {
  91700. /**
  91701. * Creates a new virtual joystick
  91702. * @param leftJoystick defines that the joystick is for left hand (false by default)
  91703. */
  91704. function VirtualJoystick(leftJoystick) {
  91705. var _this = this;
  91706. if (leftJoystick) {
  91707. this._leftJoystick = true;
  91708. }
  91709. else {
  91710. this._leftJoystick = false;
  91711. }
  91712. VirtualJoystick._globalJoystickIndex++;
  91713. // By default left & right arrow keys are moving the X
  91714. // and up & down keys are moving the Y
  91715. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  91716. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  91717. this.reverseLeftRight = false;
  91718. this.reverseUpDown = false;
  91719. // collections of pointers
  91720. this._touches = new BABYLON.StringDictionary();
  91721. this.deltaPosition = BABYLON.Vector3.Zero();
  91722. this._joystickSensibility = 25;
  91723. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  91724. this._onResize = function (evt) {
  91725. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  91726. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  91727. if (VirtualJoystick.vjCanvas) {
  91728. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  91729. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  91730. }
  91731. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  91732. };
  91733. // injecting a canvas element on top of the canvas 3D game
  91734. if (!VirtualJoystick.vjCanvas) {
  91735. window.addEventListener("resize", this._onResize, false);
  91736. VirtualJoystick.vjCanvas = document.createElement("canvas");
  91737. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  91738. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  91739. VirtualJoystick.vjCanvas.width = window.innerWidth;
  91740. VirtualJoystick.vjCanvas.height = window.innerHeight;
  91741. VirtualJoystick.vjCanvas.style.width = "100%";
  91742. VirtualJoystick.vjCanvas.style.height = "100%";
  91743. VirtualJoystick.vjCanvas.style.position = "absolute";
  91744. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  91745. VirtualJoystick.vjCanvas.style.top = "0px";
  91746. VirtualJoystick.vjCanvas.style.left = "0px";
  91747. VirtualJoystick.vjCanvas.style.zIndex = "5";
  91748. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  91749. // Support for jQuery PEP polyfill
  91750. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  91751. var context = VirtualJoystick.vjCanvas.getContext('2d');
  91752. if (!context) {
  91753. throw new Error("Unable to create canvas for virtual joystick");
  91754. }
  91755. VirtualJoystick.vjCanvasContext = context;
  91756. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  91757. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  91758. document.body.appendChild(VirtualJoystick.vjCanvas);
  91759. }
  91760. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  91761. this.pressed = false;
  91762. // default joystick color
  91763. this._joystickColor = "cyan";
  91764. this._joystickPointerID = -1;
  91765. // current joystick position
  91766. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  91767. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  91768. // origin joystick position
  91769. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  91770. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  91771. this._onPointerDownHandlerRef = function (evt) {
  91772. _this._onPointerDown(evt);
  91773. };
  91774. this._onPointerMoveHandlerRef = function (evt) {
  91775. _this._onPointerMove(evt);
  91776. };
  91777. this._onPointerUpHandlerRef = function (evt) {
  91778. _this._onPointerUp(evt);
  91779. };
  91780. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  91781. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  91782. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  91783. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  91784. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  91785. evt.preventDefault(); // Disables system menu
  91786. }, false);
  91787. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  91788. }
  91789. /**
  91790. * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)
  91791. * @param newJoystickSensibility defines the new sensibility
  91792. */
  91793. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  91794. this._joystickSensibility = newJoystickSensibility;
  91795. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  91796. };
  91797. VirtualJoystick.prototype._onPointerDown = function (e) {
  91798. var positionOnScreenCondition;
  91799. e.preventDefault();
  91800. if (this._leftJoystick === true) {
  91801. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  91802. }
  91803. else {
  91804. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  91805. }
  91806. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  91807. // First contact will be dedicated to the virtual joystick
  91808. this._joystickPointerID = e.pointerId;
  91809. this._joystickPointerStartPos.x = e.clientX;
  91810. this._joystickPointerStartPos.y = e.clientY;
  91811. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  91812. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  91813. this._deltaJoystickVector.x = 0;
  91814. this._deltaJoystickVector.y = 0;
  91815. this.pressed = true;
  91816. this._touches.add(e.pointerId.toString(), e);
  91817. }
  91818. else {
  91819. // You can only trigger the action buttons with a joystick declared
  91820. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  91821. this._action();
  91822. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  91823. }
  91824. }
  91825. };
  91826. VirtualJoystick.prototype._onPointerMove = function (e) {
  91827. // If the current pointer is the one associated to the joystick (first touch contact)
  91828. if (this._joystickPointerID == e.pointerId) {
  91829. this._joystickPointerPos.x = e.clientX;
  91830. this._joystickPointerPos.y = e.clientY;
  91831. this._deltaJoystickVector = this._joystickPointerPos.clone();
  91832. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  91833. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  91834. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  91835. switch (this._axisTargetedByLeftAndRight) {
  91836. case JoystickAxis.X:
  91837. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  91838. break;
  91839. case JoystickAxis.Y:
  91840. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  91841. break;
  91842. case JoystickAxis.Z:
  91843. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  91844. break;
  91845. }
  91846. var directionUpDown = this.reverseUpDown ? 1 : -1;
  91847. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  91848. switch (this._axisTargetedByUpAndDown) {
  91849. case JoystickAxis.X:
  91850. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  91851. break;
  91852. case JoystickAxis.Y:
  91853. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  91854. break;
  91855. case JoystickAxis.Z:
  91856. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  91857. break;
  91858. }
  91859. }
  91860. else {
  91861. var data = this._touches.get(e.pointerId.toString());
  91862. if (data) {
  91863. data.x = e.clientX;
  91864. data.y = e.clientY;
  91865. }
  91866. }
  91867. };
  91868. VirtualJoystick.prototype._onPointerUp = function (e) {
  91869. if (this._joystickPointerID == e.pointerId) {
  91870. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  91871. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  91872. this._joystickPointerID = -1;
  91873. this.pressed = false;
  91874. }
  91875. else {
  91876. var touch = this._touches.get(e.pointerId.toString());
  91877. if (touch) {
  91878. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  91879. }
  91880. }
  91881. this._deltaJoystickVector.x = 0;
  91882. this._deltaJoystickVector.y = 0;
  91883. this._touches.remove(e.pointerId.toString());
  91884. };
  91885. /**
  91886. * Change the color of the virtual joystick
  91887. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  91888. */
  91889. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  91890. this._joystickColor = newColor;
  91891. };
  91892. /**
  91893. * Defines a callback to call when the joystick is touched
  91894. * @param action defines the callback
  91895. */
  91896. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  91897. this._action = action;
  91898. };
  91899. /**
  91900. * Defines which axis you'd like to control for left & right
  91901. * @param axis defines the axis to use
  91902. */
  91903. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  91904. switch (axis) {
  91905. case JoystickAxis.X:
  91906. case JoystickAxis.Y:
  91907. case JoystickAxis.Z:
  91908. this._axisTargetedByLeftAndRight = axis;
  91909. break;
  91910. default:
  91911. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  91912. break;
  91913. }
  91914. };
  91915. /**
  91916. * Defines which axis you'd like to control for up & down
  91917. * @param axis defines the axis to use
  91918. */
  91919. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  91920. switch (axis) {
  91921. case JoystickAxis.X:
  91922. case JoystickAxis.Y:
  91923. case JoystickAxis.Z:
  91924. this._axisTargetedByUpAndDown = axis;
  91925. break;
  91926. default:
  91927. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  91928. break;
  91929. }
  91930. };
  91931. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  91932. var _this = this;
  91933. if (this.pressed) {
  91934. this._touches.forEach(function (key, touch) {
  91935. if (touch.pointerId === _this._joystickPointerID) {
  91936. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  91937. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  91938. VirtualJoystick.vjCanvasContext.beginPath();
  91939. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  91940. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  91941. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  91942. VirtualJoystick.vjCanvasContext.stroke();
  91943. VirtualJoystick.vjCanvasContext.closePath();
  91944. VirtualJoystick.vjCanvasContext.beginPath();
  91945. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  91946. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  91947. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  91948. VirtualJoystick.vjCanvasContext.stroke();
  91949. VirtualJoystick.vjCanvasContext.closePath();
  91950. VirtualJoystick.vjCanvasContext.beginPath();
  91951. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  91952. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  91953. VirtualJoystick.vjCanvasContext.stroke();
  91954. VirtualJoystick.vjCanvasContext.closePath();
  91955. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  91956. }
  91957. else {
  91958. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  91959. VirtualJoystick.vjCanvasContext.beginPath();
  91960. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  91961. VirtualJoystick.vjCanvasContext.beginPath();
  91962. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  91963. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  91964. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  91965. VirtualJoystick.vjCanvasContext.stroke();
  91966. VirtualJoystick.vjCanvasContext.closePath();
  91967. touch.prevX = touch.x;
  91968. touch.prevY = touch.y;
  91969. }
  91970. ;
  91971. });
  91972. }
  91973. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  91974. };
  91975. /**
  91976. * Release internal HTML canvas
  91977. */
  91978. VirtualJoystick.prototype.releaseCanvas = function () {
  91979. if (VirtualJoystick.vjCanvas) {
  91980. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  91981. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  91982. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  91983. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  91984. window.removeEventListener("resize", this._onResize);
  91985. document.body.removeChild(VirtualJoystick.vjCanvas);
  91986. VirtualJoystick.vjCanvas = null;
  91987. }
  91988. };
  91989. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  91990. VirtualJoystick._globalJoystickIndex = 0;
  91991. return VirtualJoystick;
  91992. }());
  91993. BABYLON.VirtualJoystick = VirtualJoystick;
  91994. })(BABYLON || (BABYLON = {}));
  91995. //# sourceMappingURL=babylon.virtualJoystick.js.map
  91996. var BABYLON;
  91997. (function (BABYLON) {
  91998. // We're mainly based on the logic defined into the FreeCamera code
  91999. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  92000. __extends(VirtualJoysticksCamera, _super);
  92001. function VirtualJoysticksCamera(name, position, scene) {
  92002. var _this = _super.call(this, name, position, scene) || this;
  92003. _this.inputs.addVirtualJoystick();
  92004. return _this;
  92005. }
  92006. VirtualJoysticksCamera.prototype.getClassName = function () {
  92007. return "VirtualJoysticksCamera";
  92008. };
  92009. return VirtualJoysticksCamera;
  92010. }(BABYLON.FreeCamera));
  92011. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  92012. })(BABYLON || (BABYLON = {}));
  92013. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  92014. var BABYLON;
  92015. (function (BABYLON) {
  92016. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  92017. function FreeCameraVirtualJoystickInput() {
  92018. }
  92019. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  92020. return this._leftjoystick;
  92021. };
  92022. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  92023. return this._rightjoystick;
  92024. };
  92025. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  92026. if (this._leftjoystick) {
  92027. var camera = this.camera;
  92028. var speed = camera._computeLocalCameraSpeed() * 50;
  92029. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  92030. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  92031. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  92032. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  92033. if (!this._leftjoystick.pressed) {
  92034. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  92035. }
  92036. if (!this._rightjoystick.pressed) {
  92037. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  92038. }
  92039. }
  92040. };
  92041. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  92042. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  92043. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  92044. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  92045. this._leftjoystick.setJoystickSensibility(0.15);
  92046. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  92047. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  92048. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  92049. this._rightjoystick.reverseUpDown = true;
  92050. this._rightjoystick.setJoystickSensibility(0.05);
  92051. this._rightjoystick.setJoystickColor("yellow");
  92052. };
  92053. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  92054. this._leftjoystick.releaseCanvas();
  92055. this._rightjoystick.releaseCanvas();
  92056. };
  92057. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  92058. return "FreeCameraVirtualJoystickInput";
  92059. };
  92060. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  92061. return "virtualJoystick";
  92062. };
  92063. return FreeCameraVirtualJoystickInput;
  92064. }());
  92065. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  92066. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  92067. })(BABYLON || (BABYLON = {}));
  92068. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  92069. var BABYLON;
  92070. (function (BABYLON) {
  92071. var SimplificationSettings = /** @class */ (function () {
  92072. function SimplificationSettings(quality, distance, optimizeMesh) {
  92073. this.quality = quality;
  92074. this.distance = distance;
  92075. this.optimizeMesh = optimizeMesh;
  92076. }
  92077. return SimplificationSettings;
  92078. }());
  92079. BABYLON.SimplificationSettings = SimplificationSettings;
  92080. var SimplificationQueue = /** @class */ (function () {
  92081. function SimplificationQueue() {
  92082. this.running = false;
  92083. this._simplificationArray = [];
  92084. }
  92085. SimplificationQueue.prototype.addTask = function (task) {
  92086. this._simplificationArray.push(task);
  92087. };
  92088. SimplificationQueue.prototype.executeNext = function () {
  92089. var task = this._simplificationArray.pop();
  92090. if (task) {
  92091. this.running = true;
  92092. this.runSimplification(task);
  92093. }
  92094. else {
  92095. this.running = false;
  92096. }
  92097. };
  92098. SimplificationQueue.prototype.runSimplification = function (task) {
  92099. var _this = this;
  92100. if (task.parallelProcessing) {
  92101. //parallel simplifier
  92102. task.settings.forEach(function (setting) {
  92103. var simplifier = _this.getSimplifier(task);
  92104. simplifier.simplify(setting, function (newMesh) {
  92105. task.mesh.addLODLevel(setting.distance, newMesh);
  92106. newMesh.isVisible = true;
  92107. //check if it is the last
  92108. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  92109. //all done, run the success callback.
  92110. task.successCallback();
  92111. }
  92112. _this.executeNext();
  92113. });
  92114. });
  92115. }
  92116. else {
  92117. //single simplifier.
  92118. var simplifier = this.getSimplifier(task);
  92119. var runDecimation = function (setting, callback) {
  92120. simplifier.simplify(setting, function (newMesh) {
  92121. task.mesh.addLODLevel(setting.distance, newMesh);
  92122. newMesh.isVisible = true;
  92123. //run the next quality level
  92124. callback();
  92125. });
  92126. };
  92127. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  92128. runDecimation(task.settings[loop.index], function () {
  92129. loop.executeNext();
  92130. });
  92131. }, function () {
  92132. //execution ended, run the success callback.
  92133. if (task.successCallback) {
  92134. task.successCallback();
  92135. }
  92136. _this.executeNext();
  92137. });
  92138. }
  92139. };
  92140. SimplificationQueue.prototype.getSimplifier = function (task) {
  92141. switch (task.simplificationType) {
  92142. case SimplificationType.QUADRATIC:
  92143. default:
  92144. return new QuadraticErrorSimplification(task.mesh);
  92145. }
  92146. };
  92147. return SimplificationQueue;
  92148. }());
  92149. BABYLON.SimplificationQueue = SimplificationQueue;
  92150. /**
  92151. * The implemented types of simplification
  92152. * At the moment only Quadratic Error Decimation is implemented
  92153. */
  92154. var SimplificationType;
  92155. (function (SimplificationType) {
  92156. /** Quadratic error decimation */
  92157. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  92158. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  92159. var DecimationTriangle = /** @class */ (function () {
  92160. function DecimationTriangle(vertices) {
  92161. this.vertices = vertices;
  92162. this.error = new Array(4);
  92163. this.deleted = false;
  92164. this.isDirty = false;
  92165. this.deletePending = false;
  92166. this.borderFactor = 0;
  92167. }
  92168. return DecimationTriangle;
  92169. }());
  92170. BABYLON.DecimationTriangle = DecimationTriangle;
  92171. var DecimationVertex = /** @class */ (function () {
  92172. function DecimationVertex(position, id) {
  92173. this.position = position;
  92174. this.id = id;
  92175. this.isBorder = true;
  92176. this.q = new QuadraticMatrix();
  92177. this.triangleCount = 0;
  92178. this.triangleStart = 0;
  92179. this.originalOffsets = [];
  92180. }
  92181. DecimationVertex.prototype.updatePosition = function (newPosition) {
  92182. this.position.copyFrom(newPosition);
  92183. };
  92184. return DecimationVertex;
  92185. }());
  92186. BABYLON.DecimationVertex = DecimationVertex;
  92187. var QuadraticMatrix = /** @class */ (function () {
  92188. function QuadraticMatrix(data) {
  92189. this.data = new Array(10);
  92190. for (var i = 0; i < 10; ++i) {
  92191. if (data && data[i]) {
  92192. this.data[i] = data[i];
  92193. }
  92194. else {
  92195. this.data[i] = 0;
  92196. }
  92197. }
  92198. }
  92199. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  92200. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  92201. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  92202. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  92203. return det;
  92204. };
  92205. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  92206. for (var i = 0; i < 10; ++i) {
  92207. this.data[i] += matrix.data[i];
  92208. }
  92209. };
  92210. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  92211. for (var i = 0; i < 10; ++i) {
  92212. this.data[i] += data[i];
  92213. }
  92214. };
  92215. QuadraticMatrix.prototype.add = function (matrix) {
  92216. var m = new QuadraticMatrix();
  92217. for (var i = 0; i < 10; ++i) {
  92218. m.data[i] = this.data[i] + matrix.data[i];
  92219. }
  92220. return m;
  92221. };
  92222. QuadraticMatrix.FromData = function (a, b, c, d) {
  92223. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  92224. };
  92225. //returning an array to avoid garbage collection
  92226. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  92227. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  92228. };
  92229. return QuadraticMatrix;
  92230. }());
  92231. BABYLON.QuadraticMatrix = QuadraticMatrix;
  92232. var Reference = /** @class */ (function () {
  92233. function Reference(vertexId, triangleId) {
  92234. this.vertexId = vertexId;
  92235. this.triangleId = triangleId;
  92236. }
  92237. return Reference;
  92238. }());
  92239. BABYLON.Reference = Reference;
  92240. /**
  92241. * An implementation of the Quadratic Error simplification algorithm.
  92242. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  92243. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  92244. * @author RaananW
  92245. */
  92246. var QuadraticErrorSimplification = /** @class */ (function () {
  92247. function QuadraticErrorSimplification(_mesh) {
  92248. this._mesh = _mesh;
  92249. this.syncIterations = 5000;
  92250. this.aggressiveness = 7;
  92251. this.decimationIterations = 100;
  92252. this.boundingBoxEpsilon = BABYLON.Epsilon;
  92253. }
  92254. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  92255. var _this = this;
  92256. this.initDecimatedMesh();
  92257. //iterating through the submeshes array, one after the other.
  92258. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  92259. _this.initWithMesh(loop.index, function () {
  92260. _this.runDecimation(settings, loop.index, function () {
  92261. loop.executeNext();
  92262. });
  92263. }, settings.optimizeMesh);
  92264. }, function () {
  92265. setTimeout(function () {
  92266. successCallback(_this._reconstructedMesh);
  92267. }, 0);
  92268. });
  92269. };
  92270. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  92271. var _this = this;
  92272. var targetCount = ~~(this.triangles.length * settings.quality);
  92273. var deletedTriangles = 0;
  92274. var triangleCount = this.triangles.length;
  92275. var iterationFunction = function (iteration, callback) {
  92276. setTimeout(function () {
  92277. if (iteration % 5 === 0) {
  92278. _this.updateMesh(iteration === 0);
  92279. }
  92280. for (var i = 0; i < _this.triangles.length; ++i) {
  92281. _this.triangles[i].isDirty = false;
  92282. }
  92283. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  92284. var trianglesIterator = function (i) {
  92285. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  92286. var t = _this.triangles[tIdx];
  92287. if (!t)
  92288. return;
  92289. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  92290. return;
  92291. }
  92292. for (var j = 0; j < 3; ++j) {
  92293. if (t.error[j] < threshold) {
  92294. var deleted0 = [];
  92295. var deleted1 = [];
  92296. var v0 = t.vertices[j];
  92297. var v1 = t.vertices[(j + 1) % 3];
  92298. if (v0.isBorder || v1.isBorder)
  92299. continue;
  92300. var p = BABYLON.Vector3.Zero();
  92301. var n = BABYLON.Vector3.Zero();
  92302. var uv = BABYLON.Vector2.Zero();
  92303. var color = new BABYLON.Color4(0, 0, 0, 1);
  92304. _this.calculateError(v0, v1, p, n, uv, color);
  92305. var delTr = new Array();
  92306. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  92307. continue;
  92308. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  92309. continue;
  92310. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  92311. continue;
  92312. var uniqueArray = new Array();
  92313. delTr.forEach(function (deletedT) {
  92314. if (uniqueArray.indexOf(deletedT) === -1) {
  92315. deletedT.deletePending = true;
  92316. uniqueArray.push(deletedT);
  92317. }
  92318. });
  92319. if (uniqueArray.length % 2 !== 0) {
  92320. continue;
  92321. }
  92322. v0.q = v1.q.add(v0.q);
  92323. v0.updatePosition(p);
  92324. var tStart = _this.references.length;
  92325. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  92326. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  92327. var tCount = _this.references.length - tStart;
  92328. if (tCount <= v0.triangleCount) {
  92329. if (tCount) {
  92330. for (var c = 0; c < tCount; c++) {
  92331. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  92332. }
  92333. }
  92334. }
  92335. else {
  92336. v0.triangleStart = tStart;
  92337. }
  92338. v0.triangleCount = tCount;
  92339. break;
  92340. }
  92341. }
  92342. };
  92343. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  92344. }, 0);
  92345. };
  92346. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  92347. if (triangleCount - deletedTriangles <= targetCount)
  92348. loop.breakLoop();
  92349. else {
  92350. iterationFunction(loop.index, function () {
  92351. loop.executeNext();
  92352. });
  92353. }
  92354. }, function () {
  92355. setTimeout(function () {
  92356. //reconstruct this part of the mesh
  92357. _this.reconstructMesh(submeshIndex);
  92358. successCallback();
  92359. }, 0);
  92360. });
  92361. };
  92362. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  92363. var _this = this;
  92364. this.vertices = [];
  92365. this.triangles = [];
  92366. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  92367. var indices = this._mesh.getIndices();
  92368. var submesh = this._mesh.subMeshes[submeshIndex];
  92369. var findInVertices = function (positionToSearch) {
  92370. if (optimizeMesh) {
  92371. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  92372. if (_this.vertices[ii].position.equals(positionToSearch)) {
  92373. return _this.vertices[ii];
  92374. }
  92375. }
  92376. }
  92377. return null;
  92378. };
  92379. var vertexReferences = [];
  92380. var vertexInit = function (i) {
  92381. if (!positionData) {
  92382. return;
  92383. }
  92384. var offset = i + submesh.verticesStart;
  92385. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  92386. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  92387. vertex.originalOffsets.push(offset);
  92388. if (vertex.id === _this.vertices.length) {
  92389. _this.vertices.push(vertex);
  92390. }
  92391. vertexReferences.push(vertex.id);
  92392. };
  92393. //var totalVertices = mesh.getTotalVertices();
  92394. var totalVertices = submesh.verticesCount;
  92395. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  92396. var indicesInit = function (i) {
  92397. if (!indices) {
  92398. return;
  92399. }
  92400. var offset = (submesh.indexStart / 3) + i;
  92401. var pos = (offset * 3);
  92402. var i0 = indices[pos + 0];
  92403. var i1 = indices[pos + 1];
  92404. var i2 = indices[pos + 2];
  92405. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  92406. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  92407. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  92408. var triangle = new DecimationTriangle([v0, v1, v2]);
  92409. triangle.originalOffset = pos;
  92410. _this.triangles.push(triangle);
  92411. };
  92412. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  92413. _this.init(callback);
  92414. });
  92415. });
  92416. };
  92417. QuadraticErrorSimplification.prototype.init = function (callback) {
  92418. var _this = this;
  92419. var triangleInit1 = function (i) {
  92420. var t = _this.triangles[i];
  92421. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  92422. for (var j = 0; j < 3; j++) {
  92423. 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))));
  92424. }
  92425. };
  92426. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  92427. var triangleInit2 = function (i) {
  92428. var t = _this.triangles[i];
  92429. for (var j = 0; j < 3; ++j) {
  92430. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  92431. }
  92432. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  92433. };
  92434. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  92435. callback();
  92436. });
  92437. });
  92438. };
  92439. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  92440. var newTriangles = [];
  92441. var i;
  92442. for (i = 0; i < this.vertices.length; ++i) {
  92443. this.vertices[i].triangleCount = 0;
  92444. }
  92445. var t;
  92446. var j;
  92447. for (i = 0; i < this.triangles.length; ++i) {
  92448. if (!this.triangles[i].deleted) {
  92449. t = this.triangles[i];
  92450. for (j = 0; j < 3; ++j) {
  92451. t.vertices[j].triangleCount = 1;
  92452. }
  92453. newTriangles.push(t);
  92454. }
  92455. }
  92456. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  92457. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  92458. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  92459. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  92460. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  92461. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  92462. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  92463. var vertexCount = 0;
  92464. for (i = 0; i < this.vertices.length; ++i) {
  92465. var vertex = this.vertices[i];
  92466. vertex.id = vertexCount;
  92467. if (vertex.triangleCount) {
  92468. vertex.originalOffsets.forEach(function (originalOffset) {
  92469. if (!normalData) {
  92470. return;
  92471. }
  92472. newPositionData.push(vertex.position.x);
  92473. newPositionData.push(vertex.position.y);
  92474. newPositionData.push(vertex.position.z);
  92475. newNormalData.push(normalData[originalOffset * 3]);
  92476. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  92477. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  92478. if (uvs && uvs.length) {
  92479. newUVsData.push(uvs[(originalOffset * 2)]);
  92480. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  92481. }
  92482. else if (colorsData && colorsData.length) {
  92483. newColorsData.push(colorsData[(originalOffset * 4)]);
  92484. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  92485. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  92486. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  92487. }
  92488. ++vertexCount;
  92489. });
  92490. }
  92491. }
  92492. var startingIndex = this._reconstructedMesh.getTotalIndices();
  92493. var startingVertex = this._reconstructedMesh.getTotalVertices();
  92494. var submeshesArray = this._reconstructedMesh.subMeshes;
  92495. this._reconstructedMesh.subMeshes = [];
  92496. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  92497. var originalIndices = this._mesh.getIndices();
  92498. for (i = 0; i < newTriangles.length; ++i) {
  92499. t = newTriangles[i]; //now get the new referencing point for each vertex
  92500. [0, 1, 2].forEach(function (idx) {
  92501. var id = originalIndices[t.originalOffset + idx];
  92502. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  92503. if (offset < 0)
  92504. offset = 0;
  92505. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  92506. });
  92507. }
  92508. //overwriting the old vertex buffers and indices.
  92509. this._reconstructedMesh.setIndices(newIndicesArray);
  92510. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  92511. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  92512. if (newUVsData.length > 0)
  92513. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  92514. if (newColorsData.length > 0)
  92515. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  92516. //create submesh
  92517. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  92518. if (submeshIndex > 0) {
  92519. this._reconstructedMesh.subMeshes = [];
  92520. submeshesArray.forEach(function (submesh) {
  92521. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  92522. });
  92523. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  92524. }
  92525. };
  92526. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  92527. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  92528. this._reconstructedMesh.material = this._mesh.material;
  92529. this._reconstructedMesh.parent = this._mesh.parent;
  92530. this._reconstructedMesh.isVisible = false;
  92531. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  92532. };
  92533. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  92534. for (var i = 0; i < vertex1.triangleCount; ++i) {
  92535. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  92536. if (t.deleted)
  92537. continue;
  92538. var s = this.references[vertex1.triangleStart + i].vertexId;
  92539. var v1 = t.vertices[(s + 1) % 3];
  92540. var v2 = t.vertices[(s + 2) % 3];
  92541. if ((v1 === vertex2 || v2 === vertex2)) {
  92542. deletedArray[i] = true;
  92543. delTr.push(t);
  92544. continue;
  92545. }
  92546. var d1 = v1.position.subtract(point);
  92547. d1 = d1.normalize();
  92548. var d2 = v2.position.subtract(point);
  92549. d2 = d2.normalize();
  92550. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  92551. return true;
  92552. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  92553. deletedArray[i] = false;
  92554. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  92555. return true;
  92556. }
  92557. return false;
  92558. };
  92559. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  92560. var newDeleted = deletedTriangles;
  92561. for (var i = 0; i < vertex.triangleCount; ++i) {
  92562. var ref = this.references[vertex.triangleStart + i];
  92563. var t = this.triangles[ref.triangleId];
  92564. if (t.deleted)
  92565. continue;
  92566. if (deletedArray[i] && t.deletePending) {
  92567. t.deleted = true;
  92568. newDeleted++;
  92569. continue;
  92570. }
  92571. t.vertices[ref.vertexId] = origVertex;
  92572. t.isDirty = true;
  92573. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  92574. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  92575. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  92576. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  92577. this.references.push(ref);
  92578. }
  92579. return newDeleted;
  92580. };
  92581. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  92582. for (var i = 0; i < this.vertices.length; ++i) {
  92583. var vCount = [];
  92584. var vId = [];
  92585. var v = this.vertices[i];
  92586. var j;
  92587. for (j = 0; j < v.triangleCount; ++j) {
  92588. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  92589. for (var ii = 0; ii < 3; ii++) {
  92590. var ofs = 0;
  92591. var vv = triangle.vertices[ii];
  92592. while (ofs < vCount.length) {
  92593. if (vId[ofs] === vv.id)
  92594. break;
  92595. ++ofs;
  92596. }
  92597. if (ofs === vCount.length) {
  92598. vCount.push(1);
  92599. vId.push(vv.id);
  92600. }
  92601. else {
  92602. vCount[ofs]++;
  92603. }
  92604. }
  92605. }
  92606. for (j = 0; j < vCount.length; ++j) {
  92607. if (vCount[j] === 1) {
  92608. this.vertices[vId[j]].isBorder = true;
  92609. }
  92610. else {
  92611. this.vertices[vId[j]].isBorder = false;
  92612. }
  92613. }
  92614. }
  92615. };
  92616. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  92617. if (identifyBorders === void 0) { identifyBorders = false; }
  92618. var i;
  92619. if (!identifyBorders) {
  92620. var newTrianglesVector = [];
  92621. for (i = 0; i < this.triangles.length; ++i) {
  92622. if (!this.triangles[i].deleted) {
  92623. newTrianglesVector.push(this.triangles[i]);
  92624. }
  92625. }
  92626. this.triangles = newTrianglesVector;
  92627. }
  92628. for (i = 0; i < this.vertices.length; ++i) {
  92629. this.vertices[i].triangleCount = 0;
  92630. this.vertices[i].triangleStart = 0;
  92631. }
  92632. var t;
  92633. var j;
  92634. var v;
  92635. for (i = 0; i < this.triangles.length; ++i) {
  92636. t = this.triangles[i];
  92637. for (j = 0; j < 3; ++j) {
  92638. v = t.vertices[j];
  92639. v.triangleCount++;
  92640. }
  92641. }
  92642. var tStart = 0;
  92643. for (i = 0; i < this.vertices.length; ++i) {
  92644. this.vertices[i].triangleStart = tStart;
  92645. tStart += this.vertices[i].triangleCount;
  92646. this.vertices[i].triangleCount = 0;
  92647. }
  92648. var newReferences = new Array(this.triangles.length * 3);
  92649. for (i = 0; i < this.triangles.length; ++i) {
  92650. t = this.triangles[i];
  92651. for (j = 0; j < 3; ++j) {
  92652. v = t.vertices[j];
  92653. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  92654. v.triangleCount++;
  92655. }
  92656. }
  92657. this.references = newReferences;
  92658. if (identifyBorders) {
  92659. this.identifyBorder();
  92660. }
  92661. };
  92662. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  92663. var x = point.x;
  92664. var y = point.y;
  92665. var z = point.z;
  92666. 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
  92667. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  92668. };
  92669. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  92670. var q = vertex1.q.add(vertex2.q);
  92671. var border = vertex1.isBorder && vertex2.isBorder;
  92672. var error = 0;
  92673. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  92674. if (qDet !== 0 && !border) {
  92675. if (!pointResult) {
  92676. pointResult = BABYLON.Vector3.Zero();
  92677. }
  92678. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  92679. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  92680. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  92681. error = this.vertexError(q, pointResult);
  92682. }
  92683. else {
  92684. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  92685. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  92686. var error1 = this.vertexError(q, vertex1.position);
  92687. var error2 = this.vertexError(q, vertex2.position);
  92688. var error3 = this.vertexError(q, p3);
  92689. error = Math.min(error1, error2, error3);
  92690. if (error === error1) {
  92691. if (pointResult) {
  92692. pointResult.copyFrom(vertex1.position);
  92693. }
  92694. }
  92695. else if (error === error2) {
  92696. if (pointResult) {
  92697. pointResult.copyFrom(vertex2.position);
  92698. }
  92699. }
  92700. else {
  92701. if (pointResult) {
  92702. pointResult.copyFrom(p3);
  92703. }
  92704. }
  92705. }
  92706. return error;
  92707. };
  92708. return QuadraticErrorSimplification;
  92709. }());
  92710. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  92711. })(BABYLON || (BABYLON = {}));
  92712. //# sourceMappingURL=babylon.meshSimplification.js.map
  92713. var BABYLON;
  92714. (function (BABYLON) {
  92715. var MeshLODLevel = /** @class */ (function () {
  92716. function MeshLODLevel(distance, mesh) {
  92717. this.distance = distance;
  92718. this.mesh = mesh;
  92719. }
  92720. return MeshLODLevel;
  92721. }());
  92722. BABYLON.MeshLODLevel = MeshLODLevel;
  92723. })(BABYLON || (BABYLON = {}));
  92724. //# sourceMappingURL=babylon.meshLODLevel.js.map
  92725. var BABYLON;
  92726. (function (BABYLON) {
  92727. /**
  92728. * Defines the root class used to create scene optimization to use with SceneOptimizer
  92729. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  92730. */
  92731. var SceneOptimization = /** @class */ (function () {
  92732. /**
  92733. * Creates the SceneOptimization object
  92734. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  92735. * @param desc defines the description associated with the optimization
  92736. */
  92737. function SceneOptimization(
  92738. /**
  92739. * Defines the priority of this optimization (0 by default which means first in the list)
  92740. */
  92741. priority) {
  92742. if (priority === void 0) { priority = 0; }
  92743. this.priority = priority;
  92744. }
  92745. /**
  92746. * Gets a string describing the action executed by the current optimization
  92747. * @returns description string
  92748. */
  92749. SceneOptimization.prototype.getDescription = function () {
  92750. return "";
  92751. };
  92752. /**
  92753. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  92754. * @param scene defines the current scene where to apply this optimization
  92755. * @param optimizer defines the current optimizer
  92756. * @returns true if everything that can be done was applied
  92757. */
  92758. SceneOptimization.prototype.apply = function (scene, optimizer) {
  92759. return true;
  92760. };
  92761. ;
  92762. return SceneOptimization;
  92763. }());
  92764. BABYLON.SceneOptimization = SceneOptimization;
  92765. /**
  92766. * Defines an optimization used to reduce the size of render target textures
  92767. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  92768. */
  92769. var TextureOptimization = /** @class */ (function (_super) {
  92770. __extends(TextureOptimization, _super);
  92771. /**
  92772. * Creates the TextureOptimization object
  92773. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  92774. * @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
  92775. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  92776. */
  92777. function TextureOptimization(
  92778. /**
  92779. * Defines the priority of this optimization (0 by default which means first in the list)
  92780. */
  92781. priority,
  92782. /**
  92783. * 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
  92784. */
  92785. maximumSize,
  92786. /**
  92787. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  92788. */
  92789. step) {
  92790. if (priority === void 0) { priority = 0; }
  92791. if (maximumSize === void 0) { maximumSize = 1024; }
  92792. if (step === void 0) { step = 0.5; }
  92793. var _this = _super.call(this, priority) || this;
  92794. _this.priority = priority;
  92795. _this.maximumSize = maximumSize;
  92796. _this.step = step;
  92797. return _this;
  92798. }
  92799. /**
  92800. * Gets a string describing the action executed by the current optimization
  92801. * @returns description string
  92802. */
  92803. TextureOptimization.prototype.getDescription = function () {
  92804. return "Reducing render target texture size to " + this.maximumSize;
  92805. };
  92806. /**
  92807. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  92808. * @param scene defines the current scene where to apply this optimization
  92809. * @param optimizer defines the current optimizer
  92810. * @returns true if everything that can be done was applied
  92811. */
  92812. TextureOptimization.prototype.apply = function (scene, optimizer) {
  92813. var allDone = true;
  92814. for (var index = 0; index < scene.textures.length; index++) {
  92815. var texture = scene.textures[index];
  92816. if (!texture.canRescale || texture.getContext) {
  92817. continue;
  92818. }
  92819. var currentSize = texture.getSize();
  92820. var maxDimension = Math.max(currentSize.width, currentSize.height);
  92821. if (maxDimension > this.maximumSize) {
  92822. texture.scale(this.step);
  92823. allDone = false;
  92824. }
  92825. }
  92826. return allDone;
  92827. };
  92828. return TextureOptimization;
  92829. }(SceneOptimization));
  92830. BABYLON.TextureOptimization = TextureOptimization;
  92831. /**
  92832. * Defines an optimization used to increase or decrease the rendering resolution
  92833. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  92834. */
  92835. var HardwareScalingOptimization = /** @class */ (function (_super) {
  92836. __extends(HardwareScalingOptimization, _super);
  92837. /**
  92838. * Creates the HardwareScalingOptimization object
  92839. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  92840. * @param maximumScale defines the maximum scale to use (2 by default)
  92841. * @param step defines the step to use between two passes (0.5 by default)
  92842. */
  92843. function HardwareScalingOptimization(
  92844. /**
  92845. * Defines the priority of this optimization (0 by default which means first in the list)
  92846. */
  92847. priority,
  92848. /**
  92849. * Defines the maximum scale to use (2 by default)
  92850. */
  92851. maximumScale,
  92852. /**
  92853. * Defines the step to use between two passes (0.5 by default)
  92854. */
  92855. step) {
  92856. if (priority === void 0) { priority = 0; }
  92857. if (maximumScale === void 0) { maximumScale = 2; }
  92858. if (step === void 0) { step = 0.25; }
  92859. var _this = _super.call(this, priority) || this;
  92860. _this.priority = priority;
  92861. _this.maximumScale = maximumScale;
  92862. _this.step = step;
  92863. _this._currentScale = -1;
  92864. _this._directionOffset = 1;
  92865. return _this;
  92866. }
  92867. /**
  92868. * Gets a string describing the action executed by the current optimization
  92869. * @return description string
  92870. */
  92871. HardwareScalingOptimization.prototype.getDescription = function () {
  92872. return "Setting hardware scaling level to " + this._currentScale;
  92873. };
  92874. /**
  92875. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  92876. * @param scene defines the current scene where to apply this optimization
  92877. * @param optimizer defines the current optimizer
  92878. * @returns true if everything that can be done was applied
  92879. */
  92880. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  92881. if (this._currentScale === -1) {
  92882. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  92883. if (this._currentScale > this.maximumScale) {
  92884. this._directionOffset = -1;
  92885. }
  92886. }
  92887. this._currentScale += this._directionOffset * this.step;
  92888. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  92889. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  92890. };
  92891. ;
  92892. return HardwareScalingOptimization;
  92893. }(SceneOptimization));
  92894. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  92895. /**
  92896. * Defines an optimization used to remove shadows
  92897. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  92898. */
  92899. var ShadowsOptimization = /** @class */ (function (_super) {
  92900. __extends(ShadowsOptimization, _super);
  92901. function ShadowsOptimization() {
  92902. return _super !== null && _super.apply(this, arguments) || this;
  92903. }
  92904. /**
  92905. * Gets a string describing the action executed by the current optimization
  92906. * @return description string
  92907. */
  92908. ShadowsOptimization.prototype.getDescription = function () {
  92909. return "Turning shadows on/off";
  92910. };
  92911. /**
  92912. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  92913. * @param scene defines the current scene where to apply this optimization
  92914. * @param optimizer defines the current optimizer
  92915. * @returns true if everything that can be done was applied
  92916. */
  92917. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  92918. scene.shadowsEnabled = optimizer.isInImprovementMode;
  92919. return true;
  92920. };
  92921. ;
  92922. return ShadowsOptimization;
  92923. }(SceneOptimization));
  92924. BABYLON.ShadowsOptimization = ShadowsOptimization;
  92925. /**
  92926. * Defines an optimization used to turn post-processes off
  92927. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  92928. */
  92929. var PostProcessesOptimization = /** @class */ (function (_super) {
  92930. __extends(PostProcessesOptimization, _super);
  92931. function PostProcessesOptimization() {
  92932. return _super !== null && _super.apply(this, arguments) || this;
  92933. }
  92934. /**
  92935. * Gets a string describing the action executed by the current optimization
  92936. * @return description string
  92937. */
  92938. PostProcessesOptimization.prototype.getDescription = function () {
  92939. return "Turning post-processes on/off";
  92940. };
  92941. /**
  92942. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  92943. * @param scene defines the current scene where to apply this optimization
  92944. * @param optimizer defines the current optimizer
  92945. * @returns true if everything that can be done was applied
  92946. */
  92947. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  92948. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  92949. return true;
  92950. };
  92951. ;
  92952. return PostProcessesOptimization;
  92953. }(SceneOptimization));
  92954. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  92955. /**
  92956. * Defines an optimization used to turn lens flares off
  92957. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  92958. */
  92959. var LensFlaresOptimization = /** @class */ (function (_super) {
  92960. __extends(LensFlaresOptimization, _super);
  92961. function LensFlaresOptimization() {
  92962. return _super !== null && _super.apply(this, arguments) || this;
  92963. }
  92964. /**
  92965. * Gets a string describing the action executed by the current optimization
  92966. * @return description string
  92967. */
  92968. LensFlaresOptimization.prototype.getDescription = function () {
  92969. return "Turning lens flares on/off";
  92970. };
  92971. /**
  92972. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  92973. * @param scene defines the current scene where to apply this optimization
  92974. * @param optimizer defines the current optimizer
  92975. * @returns true if everything that can be done was applied
  92976. */
  92977. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  92978. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  92979. return true;
  92980. };
  92981. ;
  92982. return LensFlaresOptimization;
  92983. }(SceneOptimization));
  92984. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  92985. /**
  92986. * Defines an optimization based on user defined callback.
  92987. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  92988. */
  92989. var CustomOptimization = /** @class */ (function (_super) {
  92990. __extends(CustomOptimization, _super);
  92991. function CustomOptimization() {
  92992. return _super !== null && _super.apply(this, arguments) || this;
  92993. }
  92994. /**
  92995. * Gets a string describing the action executed by the current optimization
  92996. * @returns description string
  92997. */
  92998. CustomOptimization.prototype.getDescription = function () {
  92999. if (this.onGetDescription) {
  93000. return this.onGetDescription();
  93001. }
  93002. return "Running user defined callback";
  93003. };
  93004. /**
  93005. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  93006. * @param scene defines the current scene where to apply this optimization
  93007. * @param optimizer defines the current optimizer
  93008. * @returns true if everything that can be done was applied
  93009. */
  93010. CustomOptimization.prototype.apply = function (scene, optimizer) {
  93011. if (this.onApply) {
  93012. return this.onApply(scene, optimizer);
  93013. }
  93014. return true;
  93015. };
  93016. ;
  93017. return CustomOptimization;
  93018. }(SceneOptimization));
  93019. BABYLON.CustomOptimization = CustomOptimization;
  93020. /**
  93021. * Defines an optimization used to turn particles off
  93022. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  93023. */
  93024. var ParticlesOptimization = /** @class */ (function (_super) {
  93025. __extends(ParticlesOptimization, _super);
  93026. function ParticlesOptimization() {
  93027. return _super !== null && _super.apply(this, arguments) || this;
  93028. }
  93029. /**
  93030. * Gets a string describing the action executed by the current optimization
  93031. * @return description string
  93032. */
  93033. ParticlesOptimization.prototype.getDescription = function () {
  93034. return "Turning particles on/off";
  93035. };
  93036. /**
  93037. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  93038. * @param scene defines the current scene where to apply this optimization
  93039. * @param optimizer defines the current optimizer
  93040. * @returns true if everything that can be done was applied
  93041. */
  93042. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  93043. scene.particlesEnabled = optimizer.isInImprovementMode;
  93044. return true;
  93045. };
  93046. ;
  93047. return ParticlesOptimization;
  93048. }(SceneOptimization));
  93049. BABYLON.ParticlesOptimization = ParticlesOptimization;
  93050. /**
  93051. * Defines an optimization used to turn render targets off
  93052. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  93053. */
  93054. var RenderTargetsOptimization = /** @class */ (function (_super) {
  93055. __extends(RenderTargetsOptimization, _super);
  93056. function RenderTargetsOptimization() {
  93057. return _super !== null && _super.apply(this, arguments) || this;
  93058. }
  93059. /**
  93060. * Gets a string describing the action executed by the current optimization
  93061. * @return description string
  93062. */
  93063. RenderTargetsOptimization.prototype.getDescription = function () {
  93064. return "Turning render targets off";
  93065. };
  93066. /**
  93067. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  93068. * @param scene defines the current scene where to apply this optimization
  93069. * @param optimizer defines the current optimizer
  93070. * @returns true if everything that can be done was applied
  93071. */
  93072. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  93073. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  93074. return true;
  93075. };
  93076. ;
  93077. return RenderTargetsOptimization;
  93078. }(SceneOptimization));
  93079. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  93080. /**
  93081. * Defines an optimization used to merge meshes with compatible materials
  93082. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  93083. */
  93084. var MergeMeshesOptimization = /** @class */ (function (_super) {
  93085. __extends(MergeMeshesOptimization, _super);
  93086. function MergeMeshesOptimization() {
  93087. var _this = _super !== null && _super.apply(this, arguments) || this;
  93088. _this._canBeMerged = function (abstractMesh) {
  93089. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  93090. return false;
  93091. }
  93092. var mesh = abstractMesh;
  93093. if (!mesh.isVisible || !mesh.isEnabled()) {
  93094. return false;
  93095. }
  93096. if (mesh.instances.length > 0) {
  93097. return false;
  93098. }
  93099. if (mesh.skeleton || mesh.hasLODLevels) {
  93100. return false;
  93101. }
  93102. if (mesh.parent) {
  93103. return false;
  93104. }
  93105. return true;
  93106. };
  93107. return _this;
  93108. }
  93109. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  93110. /**
  93111. * Gets or sets a boolean which defines if optimization octree has to be updated
  93112. */
  93113. get: function () {
  93114. return MergeMeshesOptimization._UpdateSelectionTree;
  93115. },
  93116. /**
  93117. * Gets or sets a boolean which defines if optimization octree has to be updated
  93118. */
  93119. set: function (value) {
  93120. MergeMeshesOptimization._UpdateSelectionTree = value;
  93121. },
  93122. enumerable: true,
  93123. configurable: true
  93124. });
  93125. /**
  93126. * Gets a string describing the action executed by the current optimization
  93127. * @return description string
  93128. */
  93129. MergeMeshesOptimization.prototype.getDescription = function () {
  93130. return "Merging similar meshes together";
  93131. };
  93132. /**
  93133. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  93134. * @param scene defines the current scene where to apply this optimization
  93135. * @param optimizer defines the current optimizer
  93136. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  93137. * @returns true if everything that can be done was applied
  93138. */
  93139. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  93140. var globalPool = scene.meshes.slice(0);
  93141. var globalLength = globalPool.length;
  93142. for (var index = 0; index < globalLength; index++) {
  93143. var currentPool = new Array();
  93144. var current = globalPool[index];
  93145. // Checks
  93146. if (!this._canBeMerged(current)) {
  93147. continue;
  93148. }
  93149. currentPool.push(current);
  93150. // Find compatible meshes
  93151. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  93152. var otherMesh = globalPool[subIndex];
  93153. if (!this._canBeMerged(otherMesh)) {
  93154. continue;
  93155. }
  93156. if (otherMesh.material !== current.material) {
  93157. continue;
  93158. }
  93159. if (otherMesh.checkCollisions !== current.checkCollisions) {
  93160. continue;
  93161. }
  93162. currentPool.push(otherMesh);
  93163. globalLength--;
  93164. globalPool.splice(subIndex, 1);
  93165. subIndex--;
  93166. }
  93167. if (currentPool.length < 2) {
  93168. continue;
  93169. }
  93170. // Merge meshes
  93171. BABYLON.Mesh.MergeMeshes(currentPool, undefined, true);
  93172. }
  93173. if (updateSelectionTree != undefined) {
  93174. if (updateSelectionTree) {
  93175. scene.createOrUpdateSelectionOctree();
  93176. }
  93177. }
  93178. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  93179. scene.createOrUpdateSelectionOctree();
  93180. }
  93181. return true;
  93182. };
  93183. ;
  93184. MergeMeshesOptimization._UpdateSelectionTree = false;
  93185. return MergeMeshesOptimization;
  93186. }(SceneOptimization));
  93187. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  93188. /**
  93189. * Defines a list of options used by SceneOptimizer
  93190. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  93191. */
  93192. var SceneOptimizerOptions = /** @class */ (function () {
  93193. /**
  93194. * Creates a new list of options used by SceneOptimizer
  93195. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  93196. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  93197. */
  93198. function SceneOptimizerOptions(
  93199. /**
  93200. * Defines the target frame rate to reach (60 by default)
  93201. */
  93202. targetFrameRate,
  93203. /**
  93204. * Defines the interval between two checkes (2000ms by default)
  93205. */
  93206. trackerDuration) {
  93207. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  93208. if (trackerDuration === void 0) { trackerDuration = 2000; }
  93209. this.targetFrameRate = targetFrameRate;
  93210. this.trackerDuration = trackerDuration;
  93211. /**
  93212. * Gets the list of optimizations to apply
  93213. */
  93214. this.optimizations = new Array();
  93215. }
  93216. /**
  93217. * Add a new optimization
  93218. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  93219. * @returns the current SceneOptimizerOptions
  93220. */
  93221. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  93222. this.optimizations.push(optimization);
  93223. return this;
  93224. };
  93225. /**
  93226. * Add a new custom optimization
  93227. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  93228. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  93229. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  93230. * @returns the current SceneOptimizerOptions
  93231. */
  93232. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  93233. if (priority === void 0) { priority = 0; }
  93234. var optimization = new CustomOptimization(priority);
  93235. optimization.onApply = onApply;
  93236. optimization.onGetDescription = onGetDescription;
  93237. this.optimizations.push(optimization);
  93238. return this;
  93239. };
  93240. /**
  93241. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  93242. * @param targetFrameRate defines the target frame rate (60 by default)
  93243. * @returns a SceneOptimizerOptions object
  93244. */
  93245. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  93246. var result = new SceneOptimizerOptions(targetFrameRate);
  93247. var priority = 0;
  93248. result.addOptimization(new MergeMeshesOptimization(priority));
  93249. result.addOptimization(new ShadowsOptimization(priority));
  93250. result.addOptimization(new LensFlaresOptimization(priority));
  93251. // Next priority
  93252. priority++;
  93253. result.addOptimization(new PostProcessesOptimization(priority));
  93254. result.addOptimization(new ParticlesOptimization(priority));
  93255. // Next priority
  93256. priority++;
  93257. result.addOptimization(new TextureOptimization(priority, 1024));
  93258. return result;
  93259. };
  93260. /**
  93261. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  93262. * @param targetFrameRate defines the target frame rate (60 by default)
  93263. * @returns a SceneOptimizerOptions object
  93264. */
  93265. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  93266. var result = new SceneOptimizerOptions(targetFrameRate);
  93267. var priority = 0;
  93268. result.addOptimization(new MergeMeshesOptimization(priority));
  93269. result.addOptimization(new ShadowsOptimization(priority));
  93270. result.addOptimization(new LensFlaresOptimization(priority));
  93271. // Next priority
  93272. priority++;
  93273. result.addOptimization(new PostProcessesOptimization(priority));
  93274. result.addOptimization(new ParticlesOptimization(priority));
  93275. // Next priority
  93276. priority++;
  93277. result.addOptimization(new TextureOptimization(priority, 512));
  93278. // Next priority
  93279. priority++;
  93280. result.addOptimization(new RenderTargetsOptimization(priority));
  93281. // Next priority
  93282. priority++;
  93283. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  93284. return result;
  93285. };
  93286. /**
  93287. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  93288. * @param targetFrameRate defines the target frame rate (60 by default)
  93289. * @returns a SceneOptimizerOptions object
  93290. */
  93291. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  93292. var result = new SceneOptimizerOptions(targetFrameRate);
  93293. var priority = 0;
  93294. result.addOptimization(new MergeMeshesOptimization(priority));
  93295. result.addOptimization(new ShadowsOptimization(priority));
  93296. result.addOptimization(new LensFlaresOptimization(priority));
  93297. // Next priority
  93298. priority++;
  93299. result.addOptimization(new PostProcessesOptimization(priority));
  93300. result.addOptimization(new ParticlesOptimization(priority));
  93301. // Next priority
  93302. priority++;
  93303. result.addOptimization(new TextureOptimization(priority, 256));
  93304. // Next priority
  93305. priority++;
  93306. result.addOptimization(new RenderTargetsOptimization(priority));
  93307. // Next priority
  93308. priority++;
  93309. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  93310. return result;
  93311. };
  93312. return SceneOptimizerOptions;
  93313. }());
  93314. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  93315. /**
  93316. * Class used to run optimizations in order to reach a target frame rate
  93317. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  93318. */
  93319. var SceneOptimizer = /** @class */ (function () {
  93320. /**
  93321. * Creates a new SceneOptimizer
  93322. * @param scene defines the scene to work on
  93323. * @param options defines the options to use with the SceneOptimizer
  93324. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  93325. * @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)
  93326. */
  93327. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  93328. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  93329. if (improvementMode === void 0) { improvementMode = false; }
  93330. var _this = this;
  93331. this._isRunning = false;
  93332. this._currentPriorityLevel = 0;
  93333. this._targetFrameRate = 60;
  93334. this._trackerDuration = 2000;
  93335. this._currentFrameRate = 0;
  93336. this._improvementMode = false;
  93337. /**
  93338. * Defines an observable called when the optimizer reaches the target frame rate
  93339. */
  93340. this.onSuccessObservable = new BABYLON.Observable();
  93341. /**
  93342. * Defines an observable called when the optimizer enables an optimization
  93343. */
  93344. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  93345. /**
  93346. * Defines an observable called when the optimizer is not able to reach the target frame rate
  93347. */
  93348. this.onFailureObservable = new BABYLON.Observable();
  93349. if (!options) {
  93350. this._options = new SceneOptimizerOptions();
  93351. }
  93352. else {
  93353. this._options = options;
  93354. }
  93355. if (this._options.targetFrameRate) {
  93356. this._targetFrameRate = this._options.targetFrameRate;
  93357. }
  93358. if (this._options.trackerDuration) {
  93359. this._trackerDuration = this._options.trackerDuration;
  93360. }
  93361. if (autoGeneratePriorities) {
  93362. var priority = 0;
  93363. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  93364. var optim = _a[_i];
  93365. optim.priority = priority++;
  93366. }
  93367. }
  93368. this._improvementMode = improvementMode;
  93369. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  93370. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  93371. _this._sceneDisposeObserver = null;
  93372. _this.dispose();
  93373. });
  93374. }
  93375. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  93376. /**
  93377. * Gets a boolean indicating if the optimizer is in improvement mode
  93378. */
  93379. get: function () {
  93380. return this._improvementMode;
  93381. },
  93382. enumerable: true,
  93383. configurable: true
  93384. });
  93385. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  93386. /**
  93387. * Gets the current priority level (0 at start)
  93388. */
  93389. get: function () {
  93390. return this._currentPriorityLevel;
  93391. },
  93392. enumerable: true,
  93393. configurable: true
  93394. });
  93395. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  93396. /**
  93397. * Gets the current frame rate checked by the SceneOptimizer
  93398. */
  93399. get: function () {
  93400. return this._currentFrameRate;
  93401. },
  93402. enumerable: true,
  93403. configurable: true
  93404. });
  93405. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  93406. /**
  93407. * Gets or sets the current target frame rate (60 by default)
  93408. */
  93409. get: function () {
  93410. return this._targetFrameRate;
  93411. },
  93412. /**
  93413. * Gets or sets the current target frame rate (60 by default)
  93414. */
  93415. set: function (value) {
  93416. this._targetFrameRate = value;
  93417. },
  93418. enumerable: true,
  93419. configurable: true
  93420. });
  93421. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  93422. /**
  93423. * Gets or sets the current interval between two checks (every 2000ms by default)
  93424. */
  93425. get: function () {
  93426. return this._trackerDuration;
  93427. },
  93428. /**
  93429. * Gets or sets the current interval between two checks (every 2000ms by default)
  93430. */
  93431. set: function (value) {
  93432. this._trackerDuration = value;
  93433. },
  93434. enumerable: true,
  93435. configurable: true
  93436. });
  93437. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  93438. /**
  93439. * Gets the list of active optimizations
  93440. */
  93441. get: function () {
  93442. return this._options.optimizations;
  93443. },
  93444. enumerable: true,
  93445. configurable: true
  93446. });
  93447. /**
  93448. * Stops the current optimizer
  93449. */
  93450. SceneOptimizer.prototype.stop = function () {
  93451. this._isRunning = false;
  93452. };
  93453. /**
  93454. * Reset the optimizer to initial step (current priority level = 0)
  93455. */
  93456. SceneOptimizer.prototype.reset = function () {
  93457. this._currentPriorityLevel = 0;
  93458. };
  93459. /**
  93460. * Start the optimizer. By default it will try to reach a specific framerate
  93461. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  93462. */
  93463. SceneOptimizer.prototype.start = function () {
  93464. var _this = this;
  93465. if (this._isRunning) {
  93466. return;
  93467. }
  93468. this._isRunning = true;
  93469. // Let's wait for the scene to be ready before running our check
  93470. this._scene.executeWhenReady(function () {
  93471. setTimeout(function () {
  93472. _this._checkCurrentState();
  93473. }, _this._trackerDuration);
  93474. });
  93475. };
  93476. SceneOptimizer.prototype._checkCurrentState = function () {
  93477. var _this = this;
  93478. if (!this._isRunning) {
  93479. return;
  93480. }
  93481. var scene = this._scene;
  93482. var options = this._options;
  93483. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  93484. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  93485. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  93486. this._isRunning = false;
  93487. this.onSuccessObservable.notifyObservers(this);
  93488. return;
  93489. }
  93490. // Apply current level of optimizations
  93491. var allDone = true;
  93492. var noOptimizationApplied = true;
  93493. for (var index = 0; index < options.optimizations.length; index++) {
  93494. var optimization = options.optimizations[index];
  93495. if (optimization.priority === this._currentPriorityLevel) {
  93496. noOptimizationApplied = false;
  93497. allDone = allDone && optimization.apply(scene, this);
  93498. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  93499. }
  93500. }
  93501. // If no optimization was applied, this is a failure :(
  93502. if (noOptimizationApplied) {
  93503. this._isRunning = false;
  93504. this.onFailureObservable.notifyObservers(this);
  93505. return;
  93506. }
  93507. // If all optimizations were done, move to next level
  93508. if (allDone) {
  93509. this._currentPriorityLevel++;
  93510. }
  93511. // Let's the system running for a specific amount of time before checking FPS
  93512. scene.executeWhenReady(function () {
  93513. setTimeout(function () {
  93514. _this._checkCurrentState();
  93515. }, _this._trackerDuration);
  93516. });
  93517. };
  93518. /**
  93519. * Release all resources
  93520. */
  93521. SceneOptimizer.prototype.dispose = function () {
  93522. this.stop();
  93523. this.onSuccessObservable.clear();
  93524. this.onFailureObservable.clear();
  93525. this.onNewOptimizationAppliedObservable.clear();
  93526. if (this._sceneDisposeObserver) {
  93527. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  93528. }
  93529. };
  93530. /**
  93531. * Helper function to create a SceneOptimizer with one single line of code
  93532. * @param scene defines the scene to work on
  93533. * @param options defines the options to use with the SceneOptimizer
  93534. * @param onSuccess defines a callback to call on success
  93535. * @param onFailure defines a callback to call on failure
  93536. * @returns the new SceneOptimizer object
  93537. */
  93538. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  93539. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  93540. if (onSuccess) {
  93541. optimizer.onSuccessObservable.add(function () {
  93542. onSuccess();
  93543. });
  93544. }
  93545. if (onFailure) {
  93546. optimizer.onFailureObservable.add(function () {
  93547. onFailure();
  93548. });
  93549. }
  93550. optimizer.start();
  93551. return optimizer;
  93552. };
  93553. return SceneOptimizer;
  93554. }());
  93555. BABYLON.SceneOptimizer = SceneOptimizer;
  93556. })(BABYLON || (BABYLON = {}));
  93557. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  93558. var BABYLON;
  93559. (function (BABYLON) {
  93560. var OutlineRenderer = /** @class */ (function () {
  93561. function OutlineRenderer(scene) {
  93562. this.zOffset = 1;
  93563. this._scene = scene;
  93564. }
  93565. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  93566. var _this = this;
  93567. if (useOverlay === void 0) { useOverlay = false; }
  93568. var scene = this._scene;
  93569. var engine = this._scene.getEngine();
  93570. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  93571. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  93572. return;
  93573. }
  93574. var mesh = subMesh.getRenderingMesh();
  93575. var material = subMesh.getMaterial();
  93576. if (!material || !scene.activeCamera) {
  93577. return;
  93578. }
  93579. engine.enableEffect(this._effect);
  93580. // Logarithmic depth
  93581. if (material.useLogarithmicDepth) {
  93582. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  93583. }
  93584. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  93585. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  93586. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  93587. // Bones
  93588. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  93589. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  93590. }
  93591. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  93592. // Alpha test
  93593. if (material && material.needAlphaTesting()) {
  93594. var alphaTexture = material.getAlphaTestTexture();
  93595. if (alphaTexture) {
  93596. this._effect.setTexture("diffuseSampler", alphaTexture);
  93597. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  93598. }
  93599. }
  93600. engine.setZOffset(-this.zOffset);
  93601. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  93602. engine.setZOffset(0);
  93603. };
  93604. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  93605. var defines = [];
  93606. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  93607. var mesh = subMesh.getMesh();
  93608. var material = subMesh.getMaterial();
  93609. if (material) {
  93610. // Alpha test
  93611. if (material.needAlphaTesting()) {
  93612. defines.push("#define ALPHATEST");
  93613. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  93614. attribs.push(BABYLON.VertexBuffer.UVKind);
  93615. defines.push("#define UV1");
  93616. }
  93617. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  93618. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  93619. defines.push("#define UV2");
  93620. }
  93621. }
  93622. //Logarithmic depth
  93623. if (material.useLogarithmicDepth) {
  93624. defines.push("#define LOGARITHMICDEPTH");
  93625. }
  93626. }
  93627. // Bones
  93628. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  93629. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  93630. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  93631. if (mesh.numBoneInfluencers > 4) {
  93632. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  93633. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  93634. }
  93635. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  93636. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  93637. }
  93638. else {
  93639. defines.push("#define NUM_BONE_INFLUENCERS 0");
  93640. }
  93641. // Instances
  93642. if (useInstances) {
  93643. defines.push("#define INSTANCES");
  93644. attribs.push("world0");
  93645. attribs.push("world1");
  93646. attribs.push("world2");
  93647. attribs.push("world3");
  93648. }
  93649. // Get correct effect
  93650. var join = defines.join("\n");
  93651. if (this._cachedDefines !== join) {
  93652. this._cachedDefines = join;
  93653. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  93654. }
  93655. return this._effect.isReady();
  93656. };
  93657. return OutlineRenderer;
  93658. }());
  93659. BABYLON.OutlineRenderer = OutlineRenderer;
  93660. })(BABYLON || (BABYLON = {}));
  93661. //# sourceMappingURL=babylon.outlineRenderer.js.map
  93662. var BABYLON;
  93663. (function (BABYLON) {
  93664. var FaceAdjacencies = /** @class */ (function () {
  93665. function FaceAdjacencies() {
  93666. this.edges = new Array();
  93667. this.edgesConnectedCount = 0;
  93668. }
  93669. return FaceAdjacencies;
  93670. }());
  93671. var EdgesRenderer = /** @class */ (function () {
  93672. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  93673. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  93674. if (epsilon === void 0) { epsilon = 0.95; }
  93675. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  93676. this.edgesWidthScalerForOrthographic = 1000.0;
  93677. this.edgesWidthScalerForPerspective = 50.0;
  93678. this._linesPositions = new Array();
  93679. this._linesNormals = new Array();
  93680. this._linesIndices = new Array();
  93681. this._buffers = {};
  93682. this._checkVerticesInsteadOfIndices = false;
  93683. /** Gets or sets a boolean indicating if the edgesRenderer is active */
  93684. this.isEnabled = true;
  93685. this._source = source;
  93686. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  93687. this._epsilon = epsilon;
  93688. this._prepareRessources();
  93689. this._generateEdgesLines();
  93690. }
  93691. EdgesRenderer.prototype._prepareRessources = function () {
  93692. if (this._lineShader) {
  93693. return;
  93694. }
  93695. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  93696. attributes: ["position", "normal"],
  93697. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  93698. });
  93699. this._lineShader.disableDepthWrite = true;
  93700. this._lineShader.backFaceCulling = false;
  93701. };
  93702. EdgesRenderer.prototype._rebuild = function () {
  93703. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  93704. if (buffer) {
  93705. buffer._rebuild();
  93706. }
  93707. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  93708. if (buffer) {
  93709. buffer._rebuild();
  93710. }
  93711. var scene = this._source.getScene();
  93712. var engine = scene.getEngine();
  93713. this._ib = engine.createIndexBuffer(this._linesIndices);
  93714. };
  93715. EdgesRenderer.prototype.dispose = function () {
  93716. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  93717. if (buffer) {
  93718. buffer.dispose();
  93719. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  93720. }
  93721. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  93722. if (buffer) {
  93723. buffer.dispose();
  93724. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  93725. }
  93726. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  93727. this._lineShader.dispose();
  93728. };
  93729. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  93730. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  93731. return 0;
  93732. }
  93733. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  93734. return 1;
  93735. }
  93736. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  93737. return 2;
  93738. }
  93739. return -1;
  93740. };
  93741. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  93742. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  93743. return 0;
  93744. }
  93745. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  93746. return 1;
  93747. }
  93748. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  93749. return 2;
  93750. }
  93751. return -1;
  93752. };
  93753. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  93754. var needToCreateLine;
  93755. if (edge === undefined) {
  93756. needToCreateLine = true;
  93757. }
  93758. else {
  93759. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  93760. needToCreateLine = dotProduct < this._epsilon;
  93761. }
  93762. if (needToCreateLine) {
  93763. var offset = this._linesPositions.length / 3;
  93764. var normal = p0.subtract(p1);
  93765. normal.normalize();
  93766. // Positions
  93767. this._linesPositions.push(p0.x);
  93768. this._linesPositions.push(p0.y);
  93769. this._linesPositions.push(p0.z);
  93770. this._linesPositions.push(p0.x);
  93771. this._linesPositions.push(p0.y);
  93772. this._linesPositions.push(p0.z);
  93773. this._linesPositions.push(p1.x);
  93774. this._linesPositions.push(p1.y);
  93775. this._linesPositions.push(p1.z);
  93776. this._linesPositions.push(p1.x);
  93777. this._linesPositions.push(p1.y);
  93778. this._linesPositions.push(p1.z);
  93779. // Normals
  93780. this._linesNormals.push(p1.x);
  93781. this._linesNormals.push(p1.y);
  93782. this._linesNormals.push(p1.z);
  93783. this._linesNormals.push(-1);
  93784. this._linesNormals.push(p1.x);
  93785. this._linesNormals.push(p1.y);
  93786. this._linesNormals.push(p1.z);
  93787. this._linesNormals.push(1);
  93788. this._linesNormals.push(p0.x);
  93789. this._linesNormals.push(p0.y);
  93790. this._linesNormals.push(p0.z);
  93791. this._linesNormals.push(-1);
  93792. this._linesNormals.push(p0.x);
  93793. this._linesNormals.push(p0.y);
  93794. this._linesNormals.push(p0.z);
  93795. this._linesNormals.push(1);
  93796. // Indices
  93797. this._linesIndices.push(offset);
  93798. this._linesIndices.push(offset + 1);
  93799. this._linesIndices.push(offset + 2);
  93800. this._linesIndices.push(offset);
  93801. this._linesIndices.push(offset + 2);
  93802. this._linesIndices.push(offset + 3);
  93803. }
  93804. };
  93805. EdgesRenderer.prototype._generateEdgesLines = function () {
  93806. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  93807. var indices = this._source.getIndices();
  93808. if (!indices || !positions) {
  93809. return;
  93810. }
  93811. // First let's find adjacencies
  93812. var adjacencies = new Array();
  93813. var faceNormals = new Array();
  93814. var index;
  93815. var faceAdjacencies;
  93816. // Prepare faces
  93817. for (index = 0; index < indices.length; index += 3) {
  93818. faceAdjacencies = new FaceAdjacencies();
  93819. var p0Index = indices[index];
  93820. var p1Index = indices[index + 1];
  93821. var p2Index = indices[index + 2];
  93822. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  93823. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  93824. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  93825. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  93826. faceNormal.normalize();
  93827. faceNormals.push(faceNormal);
  93828. adjacencies.push(faceAdjacencies);
  93829. }
  93830. // Scan
  93831. for (index = 0; index < adjacencies.length; index++) {
  93832. faceAdjacencies = adjacencies[index];
  93833. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  93834. var otherFaceAdjacencies = adjacencies[otherIndex];
  93835. if (faceAdjacencies.edgesConnectedCount === 3) { // Full
  93836. break;
  93837. }
  93838. if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full
  93839. continue;
  93840. }
  93841. var otherP0 = indices[otherIndex * 3];
  93842. var otherP1 = indices[otherIndex * 3 + 1];
  93843. var otherP2 = indices[otherIndex * 3 + 2];
  93844. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  93845. var otherEdgeIndex = 0;
  93846. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  93847. continue;
  93848. }
  93849. switch (edgeIndex) {
  93850. case 0:
  93851. if (this._checkVerticesInsteadOfIndices) {
  93852. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  93853. }
  93854. else {
  93855. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  93856. }
  93857. break;
  93858. case 1:
  93859. if (this._checkVerticesInsteadOfIndices) {
  93860. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  93861. }
  93862. else {
  93863. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  93864. }
  93865. break;
  93866. case 2:
  93867. if (this._checkVerticesInsteadOfIndices) {
  93868. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  93869. }
  93870. else {
  93871. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  93872. }
  93873. break;
  93874. }
  93875. if (otherEdgeIndex === -1) {
  93876. continue;
  93877. }
  93878. faceAdjacencies.edges[edgeIndex] = otherIndex;
  93879. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  93880. faceAdjacencies.edgesConnectedCount++;
  93881. otherFaceAdjacencies.edgesConnectedCount++;
  93882. if (faceAdjacencies.edgesConnectedCount === 3) {
  93883. break;
  93884. }
  93885. }
  93886. }
  93887. }
  93888. // Create lines
  93889. for (index = 0; index < adjacencies.length; index++) {
  93890. // 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
  93891. var current = adjacencies[index];
  93892. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  93893. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  93894. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  93895. }
  93896. // Merge into a single mesh
  93897. var engine = this._source.getScene().getEngine();
  93898. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  93899. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  93900. this._ib = engine.createIndexBuffer(this._linesIndices);
  93901. this._indicesCount = this._linesIndices.length;
  93902. };
  93903. EdgesRenderer.prototype.render = function () {
  93904. var scene = this._source.getScene();
  93905. if (!this._lineShader.isReady() || !scene.activeCamera) {
  93906. return;
  93907. }
  93908. var engine = scene.getEngine();
  93909. this._lineShader._preBind();
  93910. // VBOs
  93911. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  93912. scene.resetCachedMaterial();
  93913. this._lineShader.setColor4("color", this._source.edgesColor);
  93914. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  93915. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  93916. }
  93917. else {
  93918. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  93919. }
  93920. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  93921. this._lineShader.bind(this._source.getWorldMatrix());
  93922. // Draw order
  93923. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  93924. this._lineShader.unbind();
  93925. engine.setDepthWrite(true);
  93926. };
  93927. return EdgesRenderer;
  93928. }());
  93929. BABYLON.EdgesRenderer = EdgesRenderer;
  93930. })(BABYLON || (BABYLON = {}));
  93931. //# sourceMappingURL=babylon.edgesRenderer.js.map
  93932. var __assign = (this && this.__assign) || Object.assign || function(t) {
  93933. for (var s, i = 1, n = arguments.length; i < n; i++) {
  93934. s = arguments[i];
  93935. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  93936. t[p] = s[p];
  93937. }
  93938. return t;
  93939. };
  93940. var BABYLON;
  93941. (function (BABYLON) {
  93942. /**
  93943. * The effect layer Helps adding post process effect blended with the main pass.
  93944. *
  93945. * This can be for instance use to generate glow or higlight effects on the scene.
  93946. *
  93947. * The effect layer class can not be used directly and is intented to inherited from to be
  93948. * customized per effects.
  93949. */
  93950. var EffectLayer = /** @class */ (function () {
  93951. /**
  93952. * Instantiates a new effect Layer and references it in the scene.
  93953. * @param name The name of the layer
  93954. * @param scene The scene to use the layer in
  93955. */
  93956. function EffectLayer(
  93957. /** The Friendly of the effect in the scene */
  93958. name, scene) {
  93959. this._vertexBuffers = {};
  93960. this._maxSize = 0;
  93961. this._mainTextureDesiredSize = { width: 0, height: 0 };
  93962. this._shouldRender = true;
  93963. this._postProcesses = [];
  93964. this._textures = [];
  93965. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  93966. /**
  93967. * The clear color of the texture used to generate the glow map.
  93968. */
  93969. this.neutralColor = new BABYLON.Color4();
  93970. /**
  93971. * Specifies wether the highlight layer is enabled or not.
  93972. */
  93973. this.isEnabled = true;
  93974. /**
  93975. * An event triggered when the effect layer has been disposed.
  93976. */
  93977. this.onDisposeObservable = new BABYLON.Observable();
  93978. /**
  93979. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  93980. */
  93981. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  93982. /**
  93983. * An event triggered when the generated texture is being merged in the scene.
  93984. */
  93985. this.onBeforeComposeObservable = new BABYLON.Observable();
  93986. /**
  93987. * An event triggered when the generated texture has been merged in the scene.
  93988. */
  93989. this.onAfterComposeObservable = new BABYLON.Observable();
  93990. /**
  93991. * An event triggered when the efffect layer changes its size.
  93992. */
  93993. this.onSizeChangedObservable = new BABYLON.Observable();
  93994. this.name = name;
  93995. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  93996. this._engine = scene.getEngine();
  93997. this._maxSize = this._engine.getCaps().maxTextureSize;
  93998. this._scene.effectLayers.push(this);
  93999. // Generate Buffers
  94000. this._generateIndexBuffer();
  94001. this._genrateVertexBuffer();
  94002. }
  94003. Object.defineProperty(EffectLayer.prototype, "camera", {
  94004. /**
  94005. * Gets the camera attached to the layer.
  94006. */
  94007. get: function () {
  94008. return this._effectLayerOptions.camera;
  94009. },
  94010. enumerable: true,
  94011. configurable: true
  94012. });
  94013. /**
  94014. * Initializes the effect layer with the required options.
  94015. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  94016. */
  94017. EffectLayer.prototype._init = function (options) {
  94018. // Adapt options
  94019. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  94020. this._setMainTextureSize();
  94021. this._createMainTexture();
  94022. this._createTextureAndPostProcesses();
  94023. this._mergeEffect = this._createMergeEffect();
  94024. };
  94025. /**
  94026. * Generates the index buffer of the full screen quad blending to the main canvas.
  94027. */
  94028. EffectLayer.prototype._generateIndexBuffer = function () {
  94029. // Indices
  94030. var indices = [];
  94031. indices.push(0);
  94032. indices.push(1);
  94033. indices.push(2);
  94034. indices.push(0);
  94035. indices.push(2);
  94036. indices.push(3);
  94037. this._indexBuffer = this._engine.createIndexBuffer(indices);
  94038. };
  94039. /**
  94040. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  94041. */
  94042. EffectLayer.prototype._genrateVertexBuffer = function () {
  94043. // VBO
  94044. var vertices = [];
  94045. vertices.push(1, 1);
  94046. vertices.push(-1, 1);
  94047. vertices.push(-1, -1);
  94048. vertices.push(1, -1);
  94049. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  94050. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  94051. };
  94052. /**
  94053. * Sets the main texture desired size which is the closest power of two
  94054. * of the engine canvas size.
  94055. */
  94056. EffectLayer.prototype._setMainTextureSize = function () {
  94057. if (this._effectLayerOptions.mainTextureFixedSize) {
  94058. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  94059. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  94060. }
  94061. else {
  94062. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  94063. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  94064. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  94065. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  94066. }
  94067. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  94068. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  94069. };
  94070. /**
  94071. * Creates the main texture for the effect layer.
  94072. */
  94073. EffectLayer.prototype._createMainTexture = function () {
  94074. var _this = this;
  94075. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  94076. width: this._mainTextureDesiredSize.width,
  94077. height: this._mainTextureDesiredSize.height
  94078. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  94079. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  94080. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94081. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94082. this._mainTexture.anisotropicFilteringLevel = 1;
  94083. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  94084. this._mainTexture.renderParticles = false;
  94085. this._mainTexture.renderList = null;
  94086. this._mainTexture.ignoreCameraViewport = true;
  94087. // Custom render function
  94088. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  94089. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  94090. var index;
  94091. var engine = _this._scene.getEngine();
  94092. if (depthOnlySubMeshes.length) {
  94093. engine.setColorWrite(false);
  94094. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  94095. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  94096. }
  94097. engine.setColorWrite(true);
  94098. }
  94099. for (index = 0; index < opaqueSubMeshes.length; index++) {
  94100. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  94101. }
  94102. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  94103. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  94104. }
  94105. for (index = 0; index < transparentSubMeshes.length; index++) {
  94106. _this._renderSubMesh(transparentSubMeshes.data[index]);
  94107. }
  94108. };
  94109. this._mainTexture.onClearObservable.add(function (engine) {
  94110. engine.clear(_this.neutralColor, true, true, true);
  94111. });
  94112. };
  94113. /**
  94114. * Checks for the readiness of the element composing the layer.
  94115. * @param subMesh the mesh to check for
  94116. * @param useInstances specify wether or not to use instances to render the mesh
  94117. * @param emissiveTexture the associated emissive texture used to generate the glow
  94118. * @return true if ready otherwise, false
  94119. */
  94120. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  94121. var material = subMesh.getMaterial();
  94122. if (!material) {
  94123. return false;
  94124. }
  94125. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  94126. return false;
  94127. }
  94128. var defines = [];
  94129. var attribs = [BABYLON.VertexBuffer.PositionKind];
  94130. var mesh = subMesh.getMesh();
  94131. var uv1 = false;
  94132. var uv2 = false;
  94133. // Alpha test
  94134. if (material && material.needAlphaTesting()) {
  94135. var alphaTexture = material.getAlphaTestTexture();
  94136. if (alphaTexture) {
  94137. defines.push("#define ALPHATEST");
  94138. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  94139. alphaTexture.coordinatesIndex === 1) {
  94140. defines.push("#define DIFFUSEUV2");
  94141. uv2 = true;
  94142. }
  94143. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  94144. defines.push("#define DIFFUSEUV1");
  94145. uv1 = true;
  94146. }
  94147. }
  94148. }
  94149. // Emissive
  94150. if (emissiveTexture) {
  94151. defines.push("#define EMISSIVE");
  94152. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  94153. emissiveTexture.coordinatesIndex === 1) {
  94154. defines.push("#define EMISSIVEUV2");
  94155. uv2 = true;
  94156. }
  94157. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  94158. defines.push("#define EMISSIVEUV1");
  94159. uv1 = true;
  94160. }
  94161. }
  94162. if (uv1) {
  94163. attribs.push(BABYLON.VertexBuffer.UVKind);
  94164. defines.push("#define UV1");
  94165. }
  94166. if (uv2) {
  94167. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  94168. defines.push("#define UV2");
  94169. }
  94170. // Bones
  94171. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  94172. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  94173. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  94174. if (mesh.numBoneInfluencers > 4) {
  94175. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  94176. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  94177. }
  94178. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  94179. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  94180. }
  94181. else {
  94182. defines.push("#define NUM_BONE_INFLUENCERS 0");
  94183. }
  94184. // Morph targets
  94185. var manager = mesh.morphTargetManager;
  94186. var morphInfluencers = 0;
  94187. if (manager) {
  94188. if (manager.numInfluencers > 0) {
  94189. defines.push("#define MORPHTARGETS");
  94190. morphInfluencers = manager.numInfluencers;
  94191. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  94192. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  94193. }
  94194. }
  94195. // Instances
  94196. if (useInstances) {
  94197. defines.push("#define INSTANCES");
  94198. attribs.push("world0");
  94199. attribs.push("world1");
  94200. attribs.push("world2");
  94201. attribs.push("world3");
  94202. }
  94203. // Get correct effect
  94204. var join = defines.join("\n");
  94205. if (this._cachedDefines !== join) {
  94206. this._cachedDefines = join;
  94207. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  94208. }
  94209. return this._effectLayerMapGenerationEffect.isReady();
  94210. };
  94211. /**
  94212. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  94213. */
  94214. EffectLayer.prototype.render = function () {
  94215. var currentEffect = this._mergeEffect;
  94216. // Check
  94217. if (!currentEffect.isReady())
  94218. return;
  94219. for (var i = 0; i < this._postProcesses.length; i++) {
  94220. if (!this._postProcesses[i].isReady()) {
  94221. return;
  94222. }
  94223. }
  94224. var engine = this._scene.getEngine();
  94225. this.onBeforeComposeObservable.notifyObservers(this);
  94226. // Render
  94227. engine.enableEffect(currentEffect);
  94228. engine.setState(false);
  94229. // VBOs
  94230. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  94231. // Cache
  94232. var previousAlphaMode = engine.getAlphaMode();
  94233. // Go Blend.
  94234. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  94235. // Blends the map on the main canvas.
  94236. this._internalRender(currentEffect);
  94237. // Restore Alpha
  94238. engine.setAlphaMode(previousAlphaMode);
  94239. this.onAfterComposeObservable.notifyObservers(this);
  94240. // Handle size changes.
  94241. var size = this._mainTexture.getSize();
  94242. this._setMainTextureSize();
  94243. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  94244. // Recreate RTT and post processes on size change.
  94245. this.onSizeChangedObservable.notifyObservers(this);
  94246. this._disposeTextureAndPostProcesses();
  94247. this._createMainTexture();
  94248. this._createTextureAndPostProcesses();
  94249. }
  94250. };
  94251. /**
  94252. * Determine if a given mesh will be used in the current effect.
  94253. * @param mesh mesh to test
  94254. * @returns true if the mesh will be used
  94255. */
  94256. EffectLayer.prototype.hasMesh = function (mesh) {
  94257. return true;
  94258. };
  94259. /**
  94260. * Returns true if the layer contains information to display, otherwise false.
  94261. * @returns true if the glow layer should be rendered
  94262. */
  94263. EffectLayer.prototype.shouldRender = function () {
  94264. return this.isEnabled && this._shouldRender;
  94265. };
  94266. /**
  94267. * Returns true if the mesh should render, otherwise false.
  94268. * @param mesh The mesh to render
  94269. * @returns true if it should render otherwise false
  94270. */
  94271. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  94272. return true;
  94273. };
  94274. /**
  94275. * Returns true if the mesh should render, otherwise false.
  94276. * @param mesh The mesh to render
  94277. * @returns true if it should render otherwise false
  94278. */
  94279. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  94280. return true;
  94281. };
  94282. /**
  94283. * Renders the submesh passed in parameter to the generation map.
  94284. */
  94285. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  94286. var _this = this;
  94287. if (!this.shouldRender()) {
  94288. return;
  94289. }
  94290. var material = subMesh.getMaterial();
  94291. var mesh = subMesh.getRenderingMesh();
  94292. var scene = this._scene;
  94293. var engine = scene.getEngine();
  94294. if (!material) {
  94295. return;
  94296. }
  94297. // Do not block in blend mode.
  94298. if (material.needAlphaBlendingForMesh(mesh)) {
  94299. return;
  94300. }
  94301. // Culling
  94302. engine.setState(material.backFaceCulling);
  94303. // Managing instances
  94304. var batch = mesh._getInstancesRenderList(subMesh._id);
  94305. if (batch.mustReturn) {
  94306. return;
  94307. }
  94308. // Early Exit per mesh
  94309. if (!this._shouldRenderMesh(mesh)) {
  94310. return;
  94311. }
  94312. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  94313. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  94314. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  94315. engine.enableEffect(this._effectLayerMapGenerationEffect);
  94316. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  94317. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  94318. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  94319. // Alpha test
  94320. if (material && material.needAlphaTesting()) {
  94321. var alphaTexture = material.getAlphaTestTexture();
  94322. if (alphaTexture) {
  94323. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  94324. var textureMatrix = alphaTexture.getTextureMatrix();
  94325. if (textureMatrix) {
  94326. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  94327. }
  94328. }
  94329. }
  94330. // Glow emissive only
  94331. if (this._emissiveTextureAndColor.texture) {
  94332. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  94333. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  94334. }
  94335. // Bones
  94336. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  94337. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  94338. }
  94339. // Morph targets
  94340. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  94341. // Draw
  94342. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  94343. }
  94344. else {
  94345. // Need to reset refresh rate of the shadowMap
  94346. this._mainTexture.resetRefreshCounter();
  94347. }
  94348. };
  94349. /**
  94350. * Rebuild the required buffers.
  94351. * @hidden Internal use only.
  94352. */
  94353. EffectLayer.prototype._rebuild = function () {
  94354. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  94355. if (vb) {
  94356. vb._rebuild();
  94357. }
  94358. this._generateIndexBuffer();
  94359. };
  94360. /**
  94361. * Dispose only the render target textures and post process.
  94362. */
  94363. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  94364. this._mainTexture.dispose();
  94365. for (var i = 0; i < this._postProcesses.length; i++) {
  94366. if (this._postProcesses[i]) {
  94367. this._postProcesses[i].dispose();
  94368. }
  94369. }
  94370. this._postProcesses = [];
  94371. for (var i = 0; i < this._textures.length; i++) {
  94372. if (this._textures[i]) {
  94373. this._textures[i].dispose();
  94374. }
  94375. }
  94376. this._textures = [];
  94377. };
  94378. /**
  94379. * Dispose the highlight layer and free resources.
  94380. */
  94381. EffectLayer.prototype.dispose = function () {
  94382. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  94383. if (vertexBuffer) {
  94384. vertexBuffer.dispose();
  94385. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  94386. }
  94387. if (this._indexBuffer) {
  94388. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  94389. this._indexBuffer = null;
  94390. }
  94391. // Clean textures and post processes
  94392. this._disposeTextureAndPostProcesses();
  94393. // Remove from scene
  94394. var index = this._scene.effectLayers.indexOf(this, 0);
  94395. if (index > -1) {
  94396. this._scene.effectLayers.splice(index, 1);
  94397. }
  94398. // Callback
  94399. this.onDisposeObservable.notifyObservers(this);
  94400. this.onDisposeObservable.clear();
  94401. this.onBeforeRenderMainTextureObservable.clear();
  94402. this.onBeforeComposeObservable.clear();
  94403. this.onAfterComposeObservable.clear();
  94404. this.onSizeChangedObservable.clear();
  94405. };
  94406. /**
  94407. * Gets the class name of the effect layer
  94408. * @returns the string with the class name of the effect layer
  94409. */
  94410. EffectLayer.prototype.getClassName = function () {
  94411. return "EffectLayer";
  94412. };
  94413. /**
  94414. * Creates an effect layer from parsed effect layer data
  94415. * @param parsedEffectLayer defines effect layer data
  94416. * @param scene defines the current scene
  94417. * @param rootUrl defines the root URL containing the effect layer information
  94418. * @returns a parsed effect Layer
  94419. */
  94420. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  94421. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  94422. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  94423. };
  94424. __decorate([
  94425. BABYLON.serialize()
  94426. ], EffectLayer.prototype, "name", void 0);
  94427. __decorate([
  94428. BABYLON.serializeAsColor4()
  94429. ], EffectLayer.prototype, "neutralColor", void 0);
  94430. __decorate([
  94431. BABYLON.serialize()
  94432. ], EffectLayer.prototype, "isEnabled", void 0);
  94433. __decorate([
  94434. BABYLON.serializeAsCameraReference()
  94435. ], EffectLayer.prototype, "camera", null);
  94436. return EffectLayer;
  94437. }());
  94438. BABYLON.EffectLayer = EffectLayer;
  94439. })(BABYLON || (BABYLON = {}));
  94440. //# sourceMappingURL=babylon.effectLayer.js.map
  94441. var BABYLON;
  94442. (function (BABYLON) {
  94443. /**
  94444. * Special Glow Blur post process only blurring the alpha channel
  94445. * It enforces keeping the most luminous color in the color channel.
  94446. */
  94447. var GlowBlurPostProcess = /** @class */ (function (_super) {
  94448. __extends(GlowBlurPostProcess, _super);
  94449. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  94450. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  94451. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  94452. _this.direction = direction;
  94453. _this.kernel = kernel;
  94454. _this.onApplyObservable.add(function (effect) {
  94455. effect.setFloat2("screenSize", _this.width, _this.height);
  94456. effect.setVector2("direction", _this.direction);
  94457. effect.setFloat("blurWidth", _this.kernel);
  94458. });
  94459. return _this;
  94460. }
  94461. return GlowBlurPostProcess;
  94462. }(BABYLON.PostProcess));
  94463. /**
  94464. * The highlight layer Helps adding a glow effect around a mesh.
  94465. *
  94466. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  94467. * glowy meshes to your scene.
  94468. *
  94469. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  94470. */
  94471. var HighlightLayer = /** @class */ (function (_super) {
  94472. __extends(HighlightLayer, _super);
  94473. /**
  94474. * Instantiates a new highlight Layer and references it to the scene..
  94475. * @param name The name of the layer
  94476. * @param scene The scene to use the layer in
  94477. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  94478. */
  94479. function HighlightLayer(name, scene, options) {
  94480. var _this = _super.call(this, name, scene) || this;
  94481. _this.name = name;
  94482. /**
  94483. * Specifies whether or not the inner glow is ACTIVE in the layer.
  94484. */
  94485. _this.innerGlow = true;
  94486. /**
  94487. * Specifies whether or not the outer glow is ACTIVE in the layer.
  94488. */
  94489. _this.outerGlow = true;
  94490. /**
  94491. * An event triggered when the highlight layer is being blurred.
  94492. */
  94493. _this.onBeforeBlurObservable = new BABYLON.Observable();
  94494. /**
  94495. * An event triggered when the highlight layer has been blurred.
  94496. */
  94497. _this.onAfterBlurObservable = new BABYLON.Observable();
  94498. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  94499. _this._meshes = {};
  94500. _this._excludedMeshes = {};
  94501. _this.neutralColor = HighlightLayer.NeutralColor;
  94502. // Warn on stencil
  94503. if (!_this._engine.isStencilEnable) {
  94504. 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 }");
  94505. }
  94506. // Adapt options
  94507. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  94508. // Initialize the layer
  94509. _this._init({
  94510. alphaBlendingMode: _this._options.alphaBlendingMode,
  94511. camera: _this._options.camera,
  94512. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  94513. mainTextureRatio: _this._options.mainTextureRatio
  94514. });
  94515. // Do not render as long as no meshes have been added
  94516. _this._shouldRender = false;
  94517. return _this;
  94518. }
  94519. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  94520. /**
  94521. * Gets the horizontal size of the blur.
  94522. */
  94523. get: function () {
  94524. return this._horizontalBlurPostprocess.kernel;
  94525. },
  94526. /**
  94527. * Specifies the horizontal size of the blur.
  94528. */
  94529. set: function (value) {
  94530. this._horizontalBlurPostprocess.kernel = value;
  94531. },
  94532. enumerable: true,
  94533. configurable: true
  94534. });
  94535. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  94536. /**
  94537. * Gets the vertical size of the blur.
  94538. */
  94539. get: function () {
  94540. return this._verticalBlurPostprocess.kernel;
  94541. },
  94542. /**
  94543. * Specifies the vertical size of the blur.
  94544. */
  94545. set: function (value) {
  94546. this._verticalBlurPostprocess.kernel = value;
  94547. },
  94548. enumerable: true,
  94549. configurable: true
  94550. });
  94551. /**
  94552. * Get the effect name of the layer.
  94553. * @return The effect name
  94554. */
  94555. HighlightLayer.prototype.getEffectName = function () {
  94556. return HighlightLayer.EffectName;
  94557. };
  94558. /**
  94559. * Create the merge effect. This is the shader use to blit the information back
  94560. * to the main canvas at the end of the scene rendering.
  94561. */
  94562. HighlightLayer.prototype._createMergeEffect = function () {
  94563. // Effect
  94564. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  94565. };
  94566. /**
  94567. * Creates the render target textures and post processes used in the highlight layer.
  94568. */
  94569. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  94570. var _this = this;
  94571. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  94572. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  94573. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  94574. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  94575. var textureType = 0;
  94576. if (this._engine.getCaps().textureHalfFloatRender) {
  94577. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  94578. }
  94579. else {
  94580. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  94581. }
  94582. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  94583. width: blurTextureWidth,
  94584. height: blurTextureHeight
  94585. }, this._scene, false, true, textureType);
  94586. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94587. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94588. this._blurTexture.anisotropicFilteringLevel = 16;
  94589. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  94590. this._blurTexture.renderParticles = false;
  94591. this._blurTexture.ignoreCameraViewport = true;
  94592. this._textures = [this._blurTexture];
  94593. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  94594. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  94595. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  94596. effect.setTexture("textureSampler", _this._mainTexture);
  94597. });
  94598. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  94599. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  94600. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  94601. });
  94602. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  94603. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  94604. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  94605. });
  94606. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  94607. }
  94608. else {
  94609. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  94610. width: blurTextureWidth,
  94611. height: blurTextureHeight
  94612. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  94613. this._horizontalBlurPostprocess.width = blurTextureWidth;
  94614. this._horizontalBlurPostprocess.height = blurTextureHeight;
  94615. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  94616. effect.setTexture("textureSampler", _this._mainTexture);
  94617. });
  94618. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  94619. width: blurTextureWidth,
  94620. height: blurTextureHeight
  94621. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  94622. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  94623. }
  94624. this._mainTexture.onAfterUnbindObservable.add(function () {
  94625. _this.onBeforeBlurObservable.notifyObservers(_this);
  94626. var internalTexture = _this._blurTexture.getInternalTexture();
  94627. if (internalTexture) {
  94628. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  94629. }
  94630. _this.onAfterBlurObservable.notifyObservers(_this);
  94631. });
  94632. // Prevent autoClear.
  94633. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  94634. };
  94635. /**
  94636. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  94637. */
  94638. HighlightLayer.prototype.needStencil = function () {
  94639. return true;
  94640. };
  94641. /**
  94642. * Checks for the readiness of the element composing the layer.
  94643. * @param subMesh the mesh to check for
  94644. * @param useInstances specify wether or not to use instances to render the mesh
  94645. * @param emissiveTexture the associated emissive texture used to generate the glow
  94646. * @return true if ready otherwise, false
  94647. */
  94648. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  94649. var material = subMesh.getMaterial();
  94650. var mesh = subMesh.getRenderingMesh();
  94651. if (!material || !mesh || !this._meshes) {
  94652. return false;
  94653. }
  94654. var emissiveTexture = null;
  94655. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  94656. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  94657. emissiveTexture = material.emissiveTexture;
  94658. }
  94659. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  94660. };
  94661. /**
  94662. * Implementation specific of rendering the generating effect on the main canvas.
  94663. * @param effect The effect used to render through
  94664. */
  94665. HighlightLayer.prototype._internalRender = function (effect) {
  94666. // Texture
  94667. effect.setTexture("textureSampler", this._blurTexture);
  94668. // Cache
  94669. var engine = this._engine;
  94670. var previousStencilBuffer = engine.getStencilBuffer();
  94671. var previousStencilFunction = engine.getStencilFunction();
  94672. var previousStencilMask = engine.getStencilMask();
  94673. var previousStencilOperationPass = engine.getStencilOperationPass();
  94674. var previousStencilOperationFail = engine.getStencilOperationFail();
  94675. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  94676. var previousStencilReference = engine.getStencilFunctionReference();
  94677. // Stencil operations
  94678. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  94679. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  94680. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  94681. // Draw order
  94682. engine.setStencilMask(0x00);
  94683. engine.setStencilBuffer(true);
  94684. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  94685. // 2 passes inner outer
  94686. if (this.outerGlow) {
  94687. effect.setFloat("offset", 0);
  94688. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  94689. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  94690. }
  94691. if (this.innerGlow) {
  94692. effect.setFloat("offset", 1);
  94693. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  94694. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  94695. }
  94696. // Restore Cache
  94697. engine.setStencilFunction(previousStencilFunction);
  94698. engine.setStencilMask(previousStencilMask);
  94699. engine.setStencilBuffer(previousStencilBuffer);
  94700. engine.setStencilOperationPass(previousStencilOperationPass);
  94701. engine.setStencilOperationFail(previousStencilOperationFail);
  94702. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  94703. engine.setStencilFunctionReference(previousStencilReference);
  94704. };
  94705. /**
  94706. * Returns true if the layer contains information to display, otherwise false.
  94707. */
  94708. HighlightLayer.prototype.shouldRender = function () {
  94709. if (_super.prototype.shouldRender.call(this)) {
  94710. return this._meshes ? true : false;
  94711. }
  94712. return false;
  94713. };
  94714. /**
  94715. * Returns true if the mesh should render, otherwise false.
  94716. * @param mesh The mesh to render
  94717. * @returns true if it should render otherwise false
  94718. */
  94719. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  94720. // Excluded Mesh
  94721. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  94722. return false;
  94723. }
  94724. ;
  94725. return true;
  94726. };
  94727. /**
  94728. * Sets the required values for both the emissive texture and and the main color.
  94729. */
  94730. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  94731. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  94732. if (highlightLayerMesh) {
  94733. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  94734. }
  94735. else {
  94736. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  94737. }
  94738. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  94739. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  94740. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  94741. }
  94742. else {
  94743. this._emissiveTextureAndColor.texture = null;
  94744. }
  94745. };
  94746. /**
  94747. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  94748. * @param mesh The mesh to exclude from the highlight layer
  94749. */
  94750. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  94751. if (!this._excludedMeshes) {
  94752. return;
  94753. }
  94754. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  94755. if (!meshExcluded) {
  94756. this._excludedMeshes[mesh.uniqueId] = {
  94757. mesh: mesh,
  94758. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  94759. mesh.getEngine().setStencilBuffer(false);
  94760. }),
  94761. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  94762. mesh.getEngine().setStencilBuffer(true);
  94763. }),
  94764. };
  94765. }
  94766. };
  94767. /**
  94768. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  94769. * @param mesh The mesh to highlight
  94770. */
  94771. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  94772. if (!this._excludedMeshes) {
  94773. return;
  94774. }
  94775. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  94776. if (meshExcluded) {
  94777. if (meshExcluded.beforeRender) {
  94778. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  94779. }
  94780. if (meshExcluded.afterRender) {
  94781. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  94782. }
  94783. }
  94784. this._excludedMeshes[mesh.uniqueId] = null;
  94785. };
  94786. /**
  94787. * Determine if a given mesh will be highlighted by the current HighlightLayer
  94788. * @param mesh mesh to test
  94789. * @returns true if the mesh will be highlighted by the current HighlightLayer
  94790. */
  94791. HighlightLayer.prototype.hasMesh = function (mesh) {
  94792. if (!this._meshes) {
  94793. return false;
  94794. }
  94795. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  94796. };
  94797. /**
  94798. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  94799. * @param mesh The mesh to highlight
  94800. * @param color The color of the highlight
  94801. * @param glowEmissiveOnly Extract the glow from the emissive texture
  94802. */
  94803. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  94804. var _this = this;
  94805. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  94806. if (!this._meshes) {
  94807. return;
  94808. }
  94809. var meshHighlight = this._meshes[mesh.uniqueId];
  94810. if (meshHighlight) {
  94811. meshHighlight.color = color;
  94812. }
  94813. else {
  94814. this._meshes[mesh.uniqueId] = {
  94815. mesh: mesh,
  94816. color: color,
  94817. // Lambda required for capture due to Observable this context
  94818. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  94819. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  94820. _this._defaultStencilReference(mesh);
  94821. }
  94822. else {
  94823. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  94824. }
  94825. }),
  94826. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  94827. glowEmissiveOnly: glowEmissiveOnly
  94828. };
  94829. }
  94830. this._shouldRender = true;
  94831. };
  94832. /**
  94833. * Remove a mesh from the highlight layer in order to make it stop glowing.
  94834. * @param mesh The mesh to highlight
  94835. */
  94836. HighlightLayer.prototype.removeMesh = function (mesh) {
  94837. if (!this._meshes) {
  94838. return;
  94839. }
  94840. var meshHighlight = this._meshes[mesh.uniqueId];
  94841. if (meshHighlight) {
  94842. if (meshHighlight.observerHighlight) {
  94843. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  94844. }
  94845. if (meshHighlight.observerDefault) {
  94846. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  94847. }
  94848. delete this._meshes[mesh.uniqueId];
  94849. }
  94850. this._shouldRender = false;
  94851. for (var meshHighlightToCheck in this._meshes) {
  94852. if (this._meshes[meshHighlightToCheck]) {
  94853. this._shouldRender = true;
  94854. break;
  94855. }
  94856. }
  94857. };
  94858. /**
  94859. * Force the stencil to the normal expected value for none glowing parts
  94860. */
  94861. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  94862. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  94863. };
  94864. /**
  94865. * Free any resources and references associated to a mesh.
  94866. * Internal use
  94867. * @param mesh The mesh to free.
  94868. */
  94869. HighlightLayer.prototype._disposeMesh = function (mesh) {
  94870. this.removeMesh(mesh);
  94871. this.removeExcludedMesh(mesh);
  94872. };
  94873. /**
  94874. * Dispose the highlight layer and free resources.
  94875. */
  94876. HighlightLayer.prototype.dispose = function () {
  94877. if (this._meshes) {
  94878. // Clean mesh references
  94879. for (var id in this._meshes) {
  94880. var meshHighlight = this._meshes[id];
  94881. if (meshHighlight && meshHighlight.mesh) {
  94882. if (meshHighlight.observerHighlight) {
  94883. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  94884. }
  94885. if (meshHighlight.observerDefault) {
  94886. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  94887. }
  94888. }
  94889. }
  94890. this._meshes = null;
  94891. }
  94892. if (this._excludedMeshes) {
  94893. for (var id in this._excludedMeshes) {
  94894. var meshHighlight = this._excludedMeshes[id];
  94895. if (meshHighlight) {
  94896. if (meshHighlight.beforeRender) {
  94897. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  94898. }
  94899. if (meshHighlight.afterRender) {
  94900. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  94901. }
  94902. }
  94903. }
  94904. this._excludedMeshes = null;
  94905. }
  94906. _super.prototype.dispose.call(this);
  94907. };
  94908. /**
  94909. * Gets the class name of the effect layer
  94910. * @returns the string with the class name of the effect layer
  94911. */
  94912. HighlightLayer.prototype.getClassName = function () {
  94913. return "HighlightLayer";
  94914. };
  94915. /**
  94916. * Serializes this Highlight layer
  94917. * @returns a serialized Highlight layer object
  94918. */
  94919. HighlightLayer.prototype.serialize = function () {
  94920. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  94921. serializationObject.customType = "BABYLON.HighlightLayer";
  94922. // Highlighted meshes
  94923. serializationObject.meshes = [];
  94924. if (this._meshes) {
  94925. for (var m in this._meshes) {
  94926. var mesh = this._meshes[m];
  94927. if (mesh) {
  94928. serializationObject.meshes.push({
  94929. glowEmissiveOnly: mesh.glowEmissiveOnly,
  94930. color: mesh.color.asArray(),
  94931. meshId: mesh.mesh.id
  94932. });
  94933. }
  94934. }
  94935. }
  94936. // Excluded meshes
  94937. serializationObject.excludedMeshes = [];
  94938. if (this._excludedMeshes) {
  94939. for (var e in this._excludedMeshes) {
  94940. var excludedMesh = this._excludedMeshes[e];
  94941. if (excludedMesh) {
  94942. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  94943. }
  94944. }
  94945. }
  94946. return serializationObject;
  94947. };
  94948. /**
  94949. * Creates a Highlight layer from parsed Highlight layer data
  94950. * @param parsedHightlightLayer defines the Highlight layer data
  94951. * @param scene defines the current scene
  94952. * @param rootUrl defines the root URL containing the Highlight layer information
  94953. * @returns a parsed Highlight layer
  94954. */
  94955. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  94956. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  94957. var index;
  94958. // Excluded meshes
  94959. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  94960. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  94961. if (mesh) {
  94962. hl.addExcludedMesh(mesh);
  94963. }
  94964. }
  94965. // Included meshes
  94966. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  94967. var highlightedMesh = parsedHightlightLayer.meshes[index];
  94968. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  94969. if (mesh) {
  94970. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  94971. }
  94972. }
  94973. return hl;
  94974. };
  94975. /**
  94976. * Effect Name of the highlight layer.
  94977. */
  94978. HighlightLayer.EffectName = "HighlightLayer";
  94979. /**
  94980. * The neutral color used during the preparation of the glow effect.
  94981. * This is black by default as the blend operation is a blend operation.
  94982. */
  94983. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  94984. /**
  94985. * Stencil value used for glowing meshes.
  94986. */
  94987. HighlightLayer.GlowingMeshStencilReference = 0x02;
  94988. /**
  94989. * Stencil value used for the other meshes in the scene.
  94990. */
  94991. HighlightLayer.NormalMeshStencilReference = 0x01;
  94992. __decorate([
  94993. BABYLON.serialize()
  94994. ], HighlightLayer.prototype, "innerGlow", void 0);
  94995. __decorate([
  94996. BABYLON.serialize()
  94997. ], HighlightLayer.prototype, "outerGlow", void 0);
  94998. __decorate([
  94999. BABYLON.serialize()
  95000. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  95001. __decorate([
  95002. BABYLON.serialize()
  95003. ], HighlightLayer.prototype, "blurVerticalSize", null);
  95004. __decorate([
  95005. BABYLON.serialize("options")
  95006. ], HighlightLayer.prototype, "_options", void 0);
  95007. return HighlightLayer;
  95008. }(BABYLON.EffectLayer));
  95009. BABYLON.HighlightLayer = HighlightLayer;
  95010. })(BABYLON || (BABYLON = {}));
  95011. //# sourceMappingURL=babylon.highlightLayer.js.map
  95012. var BABYLON;
  95013. (function (BABYLON) {
  95014. /**
  95015. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  95016. *
  95017. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  95018. * glowy meshes to your scene.
  95019. *
  95020. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  95021. */
  95022. var GlowLayer = /** @class */ (function (_super) {
  95023. __extends(GlowLayer, _super);
  95024. /**
  95025. * Instantiates a new glow Layer and references it to the scene.
  95026. * @param name The name of the layer
  95027. * @param scene The scene to use the layer in
  95028. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  95029. */
  95030. function GlowLayer(name, scene, options) {
  95031. var _this = _super.call(this, name, scene) || this;
  95032. _this._intensity = 1.0;
  95033. _this._includedOnlyMeshes = [];
  95034. _this._excludedMeshes = [];
  95035. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  95036. // Adapt options
  95037. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1 }, options);
  95038. // Initialize the layer
  95039. _this._init({
  95040. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  95041. camera: _this._options.camera,
  95042. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  95043. mainTextureRatio: _this._options.mainTextureRatio
  95044. });
  95045. return _this;
  95046. }
  95047. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  95048. /**
  95049. * Gets the kernel size of the blur.
  95050. */
  95051. get: function () {
  95052. return this._horizontalBlurPostprocess1.kernel;
  95053. },
  95054. /**
  95055. * Sets the kernel size of the blur.
  95056. */
  95057. set: function (value) {
  95058. this._horizontalBlurPostprocess1.kernel = value;
  95059. this._verticalBlurPostprocess1.kernel = value;
  95060. this._horizontalBlurPostprocess2.kernel = value;
  95061. this._verticalBlurPostprocess2.kernel = value;
  95062. },
  95063. enumerable: true,
  95064. configurable: true
  95065. });
  95066. Object.defineProperty(GlowLayer.prototype, "intensity", {
  95067. /**
  95068. * Gets the glow intensity.
  95069. */
  95070. get: function () {
  95071. return this._intensity;
  95072. },
  95073. /**
  95074. * Sets the glow intensity.
  95075. */
  95076. set: function (value) {
  95077. this._intensity = value;
  95078. },
  95079. enumerable: true,
  95080. configurable: true
  95081. });
  95082. /**
  95083. * Get the effect name of the layer.
  95084. * @return The effect name
  95085. */
  95086. GlowLayer.prototype.getEffectName = function () {
  95087. return GlowLayer.EffectName;
  95088. };
  95089. /**
  95090. * Create the merge effect. This is the shader use to blit the information back
  95091. * to the main canvas at the end of the scene rendering.
  95092. */
  95093. GlowLayer.prototype._createMergeEffect = function () {
  95094. // Effect
  95095. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  95096. };
  95097. /**
  95098. * Creates the render target textures and post processes used in the glow layer.
  95099. */
  95100. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  95101. var _this = this;
  95102. var blurTextureWidth = this._mainTextureDesiredSize.width;
  95103. var blurTextureHeight = this._mainTextureDesiredSize.height;
  95104. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  95105. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  95106. var textureType = 0;
  95107. if (this._engine.getCaps().textureHalfFloatRender) {
  95108. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  95109. }
  95110. else {
  95111. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  95112. }
  95113. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  95114. width: blurTextureWidth,
  95115. height: blurTextureHeight
  95116. }, this._scene, false, true, textureType);
  95117. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  95118. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  95119. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  95120. this._blurTexture1.renderParticles = false;
  95121. this._blurTexture1.ignoreCameraViewport = true;
  95122. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  95123. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  95124. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  95125. width: blurTextureWidth2,
  95126. height: blurTextureHeight2
  95127. }, this._scene, false, true, textureType);
  95128. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  95129. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  95130. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  95131. this._blurTexture2.renderParticles = false;
  95132. this._blurTexture2.ignoreCameraViewport = true;
  95133. this._textures = [this._blurTexture1, this._blurTexture2];
  95134. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  95135. width: blurTextureWidth,
  95136. height: blurTextureHeight
  95137. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  95138. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  95139. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  95140. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  95141. effect.setTexture("textureSampler", _this._mainTexture);
  95142. });
  95143. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  95144. width: blurTextureWidth,
  95145. height: blurTextureHeight
  95146. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  95147. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  95148. width: blurTextureWidth2,
  95149. height: blurTextureHeight2
  95150. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  95151. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  95152. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  95153. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  95154. effect.setTexture("textureSampler", _this._blurTexture1);
  95155. });
  95156. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  95157. width: blurTextureWidth2,
  95158. height: blurTextureHeight2
  95159. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  95160. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  95161. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  95162. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  95163. this._mainTexture.samples = this._options.mainTextureSamples;
  95164. this._mainTexture.onAfterUnbindObservable.add(function () {
  95165. var internalTexture = _this._blurTexture1.getInternalTexture();
  95166. if (internalTexture) {
  95167. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  95168. internalTexture = _this._blurTexture2.getInternalTexture();
  95169. if (internalTexture) {
  95170. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  95171. }
  95172. }
  95173. });
  95174. // Prevent autoClear.
  95175. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  95176. };
  95177. /**
  95178. * Checks for the readiness of the element composing the layer.
  95179. * @param subMesh the mesh to check for
  95180. * @param useInstances specify wether or not to use instances to render the mesh
  95181. * @param emissiveTexture the associated emissive texture used to generate the glow
  95182. * @return true if ready otherwise, false
  95183. */
  95184. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  95185. var material = subMesh.getMaterial();
  95186. var mesh = subMesh.getRenderingMesh();
  95187. if (!material || !mesh) {
  95188. return false;
  95189. }
  95190. var emissiveTexture = material.emissiveTexture;
  95191. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  95192. };
  95193. /**
  95194. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  95195. */
  95196. GlowLayer.prototype.needStencil = function () {
  95197. return false;
  95198. };
  95199. /**
  95200. * Implementation specific of rendering the generating effect on the main canvas.
  95201. * @param effect The effect used to render through
  95202. */
  95203. GlowLayer.prototype._internalRender = function (effect) {
  95204. // Texture
  95205. effect.setTexture("textureSampler", this._blurTexture1);
  95206. effect.setTexture("textureSampler2", this._blurTexture2);
  95207. effect.setFloat("offset", this._intensity);
  95208. // Cache
  95209. var engine = this._engine;
  95210. var previousStencilBuffer = engine.getStencilBuffer();
  95211. // Draw order
  95212. engine.setStencilBuffer(false);
  95213. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  95214. // Draw order
  95215. engine.setStencilBuffer(previousStencilBuffer);
  95216. };
  95217. /**
  95218. * Sets the required values for both the emissive texture and and the main color.
  95219. */
  95220. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  95221. var textureLevel = 1.0;
  95222. if (this.customEmissiveTextureSelector) {
  95223. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  95224. }
  95225. else {
  95226. if (material) {
  95227. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  95228. if (this._emissiveTextureAndColor.texture) {
  95229. textureLevel = this._emissiveTextureAndColor.texture.level;
  95230. }
  95231. }
  95232. else {
  95233. this._emissiveTextureAndColor.texture = null;
  95234. }
  95235. }
  95236. if (this.customEmissiveColorSelector) {
  95237. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  95238. }
  95239. else {
  95240. if (material.emissiveColor) {
  95241. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  95242. }
  95243. else {
  95244. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  95245. }
  95246. }
  95247. };
  95248. /**
  95249. * Returns true if the mesh should render, otherwise false.
  95250. * @param mesh The mesh to render
  95251. * @returns true if it should render otherwise false
  95252. */
  95253. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  95254. return this.hasMesh(mesh);
  95255. };
  95256. /**
  95257. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  95258. * @param mesh The mesh to exclude from the glow layer
  95259. */
  95260. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  95261. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  95262. this._excludedMeshes.push(mesh.uniqueId);
  95263. }
  95264. };
  95265. /**
  95266. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  95267. * @param mesh The mesh to remove
  95268. */
  95269. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  95270. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  95271. if (index !== -1) {
  95272. this._excludedMeshes.splice(index, 1);
  95273. }
  95274. };
  95275. /**
  95276. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  95277. * @param mesh The mesh to include in the glow layer
  95278. */
  95279. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  95280. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  95281. this._includedOnlyMeshes.push(mesh.uniqueId);
  95282. }
  95283. };
  95284. /**
  95285. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  95286. * @param mesh The mesh to remove
  95287. */
  95288. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  95289. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  95290. if (index !== -1) {
  95291. this._includedOnlyMeshes.splice(index, 1);
  95292. }
  95293. };
  95294. /**
  95295. * Determine if a given mesh will be used in the glow layer
  95296. * @param mesh The mesh to test
  95297. * @returns true if the mesh will be highlighted by the current glow layer
  95298. */
  95299. GlowLayer.prototype.hasMesh = function (mesh) {
  95300. // Included Mesh
  95301. if (this._includedOnlyMeshes.length) {
  95302. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  95303. }
  95304. ;
  95305. // Excluded Mesh
  95306. if (this._excludedMeshes.length) {
  95307. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  95308. }
  95309. ;
  95310. return true;
  95311. };
  95312. /**
  95313. * Free any resources and references associated to a mesh.
  95314. * Internal use
  95315. * @param mesh The mesh to free.
  95316. */
  95317. GlowLayer.prototype._disposeMesh = function (mesh) {
  95318. this.removeIncludedOnlyMesh(mesh);
  95319. this.removeExcludedMesh(mesh);
  95320. };
  95321. /**
  95322. * Gets the class name of the effect layer
  95323. * @returns the string with the class name of the effect layer
  95324. */
  95325. GlowLayer.prototype.getClassName = function () {
  95326. return "GlowLayer";
  95327. };
  95328. /**
  95329. * Serializes this glow layer
  95330. * @returns a serialized glow layer object
  95331. */
  95332. GlowLayer.prototype.serialize = function () {
  95333. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  95334. serializationObject.customType = "BABYLON.GlowLayer";
  95335. var index;
  95336. // Included meshes
  95337. serializationObject.includedMeshes = [];
  95338. if (this._includedOnlyMeshes.length) {
  95339. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  95340. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  95341. if (mesh) {
  95342. serializationObject.includedMeshes.push(mesh.id);
  95343. }
  95344. }
  95345. }
  95346. // Excluded meshes
  95347. serializationObject.excludedMeshes = [];
  95348. if (this._excludedMeshes.length) {
  95349. for (index = 0; index < this._excludedMeshes.length; index++) {
  95350. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  95351. if (mesh) {
  95352. serializationObject.excludedMeshes.push(mesh.id);
  95353. }
  95354. }
  95355. }
  95356. return serializationObject;
  95357. };
  95358. /**
  95359. * Creates a Glow Layer from parsed glow layer data
  95360. * @param parsedGlowLayer defines glow layer data
  95361. * @param scene defines the current scene
  95362. * @param rootUrl defines the root URL containing the glow layer information
  95363. * @returns a parsed Glow Layer
  95364. */
  95365. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  95366. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  95367. var index;
  95368. // Excluded meshes
  95369. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  95370. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  95371. if (mesh) {
  95372. gl.addExcludedMesh(mesh);
  95373. }
  95374. }
  95375. // Included meshes
  95376. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  95377. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  95378. if (mesh) {
  95379. gl.addIncludedOnlyMesh(mesh);
  95380. }
  95381. }
  95382. return gl;
  95383. };
  95384. /**
  95385. * Effect Name of the layer.
  95386. */
  95387. GlowLayer.EffectName = "GlowLayer";
  95388. /**
  95389. * The default blur kernel size used for the glow.
  95390. */
  95391. GlowLayer.DefaultBlurKernelSize = 32;
  95392. /**
  95393. * The default texture size ratio used for the glow.
  95394. */
  95395. GlowLayer.DefaultTextureRatio = 0.5;
  95396. __decorate([
  95397. BABYLON.serialize()
  95398. ], GlowLayer.prototype, "blurKernelSize", null);
  95399. __decorate([
  95400. BABYLON.serialize()
  95401. ], GlowLayer.prototype, "intensity", null);
  95402. __decorate([
  95403. BABYLON.serialize("options")
  95404. ], GlowLayer.prototype, "_options", void 0);
  95405. return GlowLayer;
  95406. }(BABYLON.EffectLayer));
  95407. BABYLON.GlowLayer = GlowLayer;
  95408. })(BABYLON || (BABYLON = {}));
  95409. //# sourceMappingURL=babylon.glowLayer.js.map
  95410. var BABYLON;
  95411. (function (BABYLON) {
  95412. /**
  95413. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  95414. */
  95415. var AssetTaskState;
  95416. (function (AssetTaskState) {
  95417. /**
  95418. * Initialization
  95419. */
  95420. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  95421. /**
  95422. * Running
  95423. */
  95424. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  95425. /**
  95426. * Done
  95427. */
  95428. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  95429. /**
  95430. * Error
  95431. */
  95432. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  95433. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  95434. /**
  95435. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  95436. */
  95437. var AbstractAssetTask = /** @class */ (function () {
  95438. /**
  95439. * Creates a new {BABYLON.AssetsManager}
  95440. * @param name defines the name of the task
  95441. */
  95442. function AbstractAssetTask(
  95443. /**
  95444. * Task name
  95445. */ name) {
  95446. this.name = name;
  95447. this._isCompleted = false;
  95448. this._taskState = AssetTaskState.INIT;
  95449. }
  95450. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  95451. /**
  95452. * Get if the task is completed
  95453. */
  95454. get: function () {
  95455. return this._isCompleted;
  95456. },
  95457. enumerable: true,
  95458. configurable: true
  95459. });
  95460. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  95461. /**
  95462. * Gets the current state of the task
  95463. */
  95464. get: function () {
  95465. return this._taskState;
  95466. },
  95467. enumerable: true,
  95468. configurable: true
  95469. });
  95470. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  95471. /**
  95472. * Gets the current error object (if task is in error)
  95473. */
  95474. get: function () {
  95475. return this._errorObject;
  95476. },
  95477. enumerable: true,
  95478. configurable: true
  95479. });
  95480. /**
  95481. * Internal only
  95482. * @hidden
  95483. */
  95484. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  95485. if (this._errorObject) {
  95486. return;
  95487. }
  95488. this._errorObject = {
  95489. message: message,
  95490. exception: exception
  95491. };
  95492. };
  95493. /**
  95494. * Execute the current task
  95495. * @param scene defines the scene where you want your assets to be loaded
  95496. * @param onSuccess is a callback called when the task is successfully executed
  95497. * @param onError is a callback called if an error occurs
  95498. */
  95499. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  95500. var _this = this;
  95501. this._taskState = AssetTaskState.RUNNING;
  95502. this.runTask(scene, function () {
  95503. _this.onDoneCallback(onSuccess, onError);
  95504. }, function (msg, exception) {
  95505. _this.onErrorCallback(onError, msg, exception);
  95506. });
  95507. };
  95508. /**
  95509. * Execute the current task
  95510. * @param scene defines the scene where you want your assets to be loaded
  95511. * @param onSuccess is a callback called when the task is successfully executed
  95512. * @param onError is a callback called if an error occurs
  95513. */
  95514. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  95515. throw new Error("runTask is not implemented");
  95516. };
  95517. /**
  95518. * Reset will set the task state back to INIT, so the next load call of the assets manager will execute this task again.
  95519. * This can be used with failed tasks that have the reason for failure fixed.
  95520. */
  95521. AbstractAssetTask.prototype.reset = function () {
  95522. this._taskState = AssetTaskState.INIT;
  95523. };
  95524. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  95525. this._taskState = AssetTaskState.ERROR;
  95526. this._errorObject = {
  95527. message: message,
  95528. exception: exception
  95529. };
  95530. if (this.onError) {
  95531. this.onError(this, message, exception);
  95532. }
  95533. onError();
  95534. };
  95535. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  95536. try {
  95537. this._taskState = AssetTaskState.DONE;
  95538. this._isCompleted = true;
  95539. if (this.onSuccess) {
  95540. this.onSuccess(this);
  95541. }
  95542. onSuccess();
  95543. }
  95544. catch (e) {
  95545. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  95546. }
  95547. };
  95548. return AbstractAssetTask;
  95549. }());
  95550. BABYLON.AbstractAssetTask = AbstractAssetTask;
  95551. /**
  95552. * Class used to share progress information about assets loading
  95553. */
  95554. var AssetsProgressEvent = /** @class */ (function () {
  95555. /**
  95556. * Creates a {BABYLON.AssetsProgressEvent}
  95557. * @param remainingCount defines the number of remaining tasks to process
  95558. * @param totalCount defines the total number of tasks
  95559. * @param task defines the task that was just processed
  95560. */
  95561. function AssetsProgressEvent(remainingCount, totalCount, task) {
  95562. this.remainingCount = remainingCount;
  95563. this.totalCount = totalCount;
  95564. this.task = task;
  95565. }
  95566. return AssetsProgressEvent;
  95567. }());
  95568. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  95569. /**
  95570. * Define a task used by {BABYLON.AssetsManager} to load meshes
  95571. */
  95572. var MeshAssetTask = /** @class */ (function (_super) {
  95573. __extends(MeshAssetTask, _super);
  95574. /**
  95575. * Creates a new {BABYLON.MeshAssetTask}
  95576. * @param name defines the name of the task
  95577. * @param meshesNames defines the list of mesh's names you want to load
  95578. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  95579. * @param sceneFilename defines the filename of the scene to load from
  95580. */
  95581. function MeshAssetTask(
  95582. /**
  95583. * Defines the name of the task
  95584. */
  95585. name,
  95586. /**
  95587. * Defines the list of mesh's names you want to load
  95588. */
  95589. meshesNames,
  95590. /**
  95591. * Defines the root url to use as a base to load your meshes and associated resources
  95592. */
  95593. rootUrl,
  95594. /**
  95595. * Defines the filename of the scene to load from
  95596. */
  95597. sceneFilename) {
  95598. var _this = _super.call(this, name) || this;
  95599. _this.name = name;
  95600. _this.meshesNames = meshesNames;
  95601. _this.rootUrl = rootUrl;
  95602. _this.sceneFilename = sceneFilename;
  95603. return _this;
  95604. }
  95605. /**
  95606. * Execute the current task
  95607. * @param scene defines the scene where you want your assets to be loaded
  95608. * @param onSuccess is a callback called when the task is successfully executed
  95609. * @param onError is a callback called if an error occurs
  95610. */
  95611. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  95612. var _this = this;
  95613. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  95614. _this.loadedMeshes = meshes;
  95615. _this.loadedParticleSystems = particleSystems;
  95616. _this.loadedSkeletons = skeletons;
  95617. onSuccess();
  95618. }, null, function (scene, message, exception) {
  95619. onError(message, exception);
  95620. });
  95621. };
  95622. return MeshAssetTask;
  95623. }(AbstractAssetTask));
  95624. BABYLON.MeshAssetTask = MeshAssetTask;
  95625. /**
  95626. * Define a task used by {BABYLON.AssetsManager} to load text content
  95627. */
  95628. var TextFileAssetTask = /** @class */ (function (_super) {
  95629. __extends(TextFileAssetTask, _super);
  95630. /**
  95631. * Creates a new TextFileAssetTask object
  95632. * @param name defines the name of the task
  95633. * @param url defines the location of the file to load
  95634. */
  95635. function TextFileAssetTask(
  95636. /**
  95637. * Defines the name of the task
  95638. */
  95639. name,
  95640. /**
  95641. * Defines the location of the file to load
  95642. */
  95643. url) {
  95644. var _this = _super.call(this, name) || this;
  95645. _this.name = name;
  95646. _this.url = url;
  95647. return _this;
  95648. }
  95649. /**
  95650. * Execute the current task
  95651. * @param scene defines the scene where you want your assets to be loaded
  95652. * @param onSuccess is a callback called when the task is successfully executed
  95653. * @param onError is a callback called if an error occurs
  95654. */
  95655. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  95656. var _this = this;
  95657. scene._loadFile(this.url, function (data) {
  95658. _this.text = data;
  95659. onSuccess();
  95660. }, undefined, false, false, function (request, exception) {
  95661. if (request) {
  95662. onError(request.status + " " + request.statusText, exception);
  95663. }
  95664. });
  95665. };
  95666. return TextFileAssetTask;
  95667. }(AbstractAssetTask));
  95668. BABYLON.TextFileAssetTask = TextFileAssetTask;
  95669. /**
  95670. * Define a task used by {BABYLON.AssetsManager} to load binary data
  95671. */
  95672. var BinaryFileAssetTask = /** @class */ (function (_super) {
  95673. __extends(BinaryFileAssetTask, _super);
  95674. /**
  95675. * Creates a new BinaryFileAssetTask object
  95676. * @param name defines the name of the new task
  95677. * @param url defines the location of the file to load
  95678. */
  95679. function BinaryFileAssetTask(
  95680. /**
  95681. * Defines the name of the task
  95682. */
  95683. name,
  95684. /**
  95685. * Defines the location of the file to load
  95686. */
  95687. url) {
  95688. var _this = _super.call(this, name) || this;
  95689. _this.name = name;
  95690. _this.url = url;
  95691. return _this;
  95692. }
  95693. /**
  95694. * Execute the current task
  95695. * @param scene defines the scene where you want your assets to be loaded
  95696. * @param onSuccess is a callback called when the task is successfully executed
  95697. * @param onError is a callback called if an error occurs
  95698. */
  95699. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  95700. var _this = this;
  95701. scene._loadFile(this.url, function (data) {
  95702. _this.data = data;
  95703. onSuccess();
  95704. }, undefined, true, true, function (request, exception) {
  95705. if (request) {
  95706. onError(request.status + " " + request.statusText, exception);
  95707. }
  95708. });
  95709. };
  95710. return BinaryFileAssetTask;
  95711. }(AbstractAssetTask));
  95712. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  95713. /**
  95714. * Define a task used by {BABYLON.AssetsManager} to load images
  95715. */
  95716. var ImageAssetTask = /** @class */ (function (_super) {
  95717. __extends(ImageAssetTask, _super);
  95718. /**
  95719. * Creates a new ImageAssetTask
  95720. * @param name defines the name of the task
  95721. * @param url defines the location of the image to load
  95722. */
  95723. function ImageAssetTask(
  95724. /**
  95725. * Defines the name of the task
  95726. */
  95727. name,
  95728. /**
  95729. * Defines the location of the image to load
  95730. */
  95731. url) {
  95732. var _this = _super.call(this, name) || this;
  95733. _this.name = name;
  95734. _this.url = url;
  95735. return _this;
  95736. }
  95737. /**
  95738. * Execute the current task
  95739. * @param scene defines the scene where you want your assets to be loaded
  95740. * @param onSuccess is a callback called when the task is successfully executed
  95741. * @param onError is a callback called if an error occurs
  95742. */
  95743. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  95744. var _this = this;
  95745. var img = new Image();
  95746. BABYLON.Tools.SetCorsBehavior(this.url, img);
  95747. img.onload = function () {
  95748. _this.image = img;
  95749. onSuccess();
  95750. };
  95751. img.onerror = function (err) {
  95752. onError("Error loading image", err);
  95753. };
  95754. img.src = this.url;
  95755. };
  95756. return ImageAssetTask;
  95757. }(AbstractAssetTask));
  95758. BABYLON.ImageAssetTask = ImageAssetTask;
  95759. /**
  95760. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  95761. */
  95762. var TextureAssetTask = /** @class */ (function (_super) {
  95763. __extends(TextureAssetTask, _super);
  95764. /**
  95765. * Creates a new TextureAssetTask object
  95766. * @param name defines the name of the task
  95767. * @param url defines the location of the file to load
  95768. * @param noMipmap defines if mipmap should not be generated (default is false)
  95769. * @param invertY defines if texture must be inverted on Y axis (default is false)
  95770. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  95771. */
  95772. function TextureAssetTask(
  95773. /**
  95774. * Defines the name of the task
  95775. */
  95776. name,
  95777. /**
  95778. * Defines the location of the file to load
  95779. */
  95780. url,
  95781. /**
  95782. * Defines if mipmap should not be generated (default is false)
  95783. */
  95784. noMipmap,
  95785. /**
  95786. * Defines if texture must be inverted on Y axis (default is false)
  95787. */
  95788. invertY,
  95789. /**
  95790. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  95791. */
  95792. samplingMode) {
  95793. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  95794. var _this = _super.call(this, name) || this;
  95795. _this.name = name;
  95796. _this.url = url;
  95797. _this.noMipmap = noMipmap;
  95798. _this.invertY = invertY;
  95799. _this.samplingMode = samplingMode;
  95800. return _this;
  95801. }
  95802. /**
  95803. * Execute the current task
  95804. * @param scene defines the scene where you want your assets to be loaded
  95805. * @param onSuccess is a callback called when the task is successfully executed
  95806. * @param onError is a callback called if an error occurs
  95807. */
  95808. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  95809. var onload = function () {
  95810. onSuccess();
  95811. };
  95812. var onerror = function (message, exception) {
  95813. onError(message, exception);
  95814. };
  95815. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  95816. };
  95817. return TextureAssetTask;
  95818. }(AbstractAssetTask));
  95819. BABYLON.TextureAssetTask = TextureAssetTask;
  95820. /**
  95821. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  95822. */
  95823. var CubeTextureAssetTask = /** @class */ (function (_super) {
  95824. __extends(CubeTextureAssetTask, _super);
  95825. /**
  95826. * Creates a new CubeTextureAssetTask
  95827. * @param name defines the name of the task
  95828. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  95829. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  95830. * @param noMipmap defines if mipmaps should not be generated (default is false)
  95831. * @param files defines the explicit list of files (undefined by default)
  95832. */
  95833. function CubeTextureAssetTask(
  95834. /**
  95835. * Defines the name of the task
  95836. */
  95837. name,
  95838. /**
  95839. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  95840. */
  95841. url,
  95842. /**
  95843. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  95844. */
  95845. extensions,
  95846. /**
  95847. * Defines if mipmaps should not be generated (default is false)
  95848. */
  95849. noMipmap,
  95850. /**
  95851. * Defines the explicit list of files (undefined by default)
  95852. */
  95853. files) {
  95854. var _this = _super.call(this, name) || this;
  95855. _this.name = name;
  95856. _this.url = url;
  95857. _this.extensions = extensions;
  95858. _this.noMipmap = noMipmap;
  95859. _this.files = files;
  95860. return _this;
  95861. }
  95862. /**
  95863. * Execute the current task
  95864. * @param scene defines the scene where you want your assets to be loaded
  95865. * @param onSuccess is a callback called when the task is successfully executed
  95866. * @param onError is a callback called if an error occurs
  95867. */
  95868. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  95869. var onload = function () {
  95870. onSuccess();
  95871. };
  95872. var onerror = function (message, exception) {
  95873. onError(message, exception);
  95874. };
  95875. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  95876. };
  95877. return CubeTextureAssetTask;
  95878. }(AbstractAssetTask));
  95879. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  95880. /**
  95881. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  95882. */
  95883. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  95884. __extends(HDRCubeTextureAssetTask, _super);
  95885. /**
  95886. * Creates a new HDRCubeTextureAssetTask object
  95887. * @param name defines the name of the task
  95888. * @param url defines the location of the file to load
  95889. * @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.
  95890. * @param noMipmap defines if mipmaps should not be generated (default is false)
  95891. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  95892. * @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)
  95893. * @param reserved Internal use only
  95894. */
  95895. function HDRCubeTextureAssetTask(
  95896. /**
  95897. * Defines the name of the task
  95898. */
  95899. name,
  95900. /**
  95901. * Defines the location of the file to load
  95902. */
  95903. url,
  95904. /**
  95905. * Defines the desired size (the more it increases the longer the generation will be)
  95906. */
  95907. size,
  95908. /**
  95909. * Defines if mipmaps should not be generated (default is false)
  95910. */
  95911. noMipmap,
  95912. /**
  95913. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  95914. */
  95915. generateHarmonics,
  95916. /**
  95917. * 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)
  95918. */
  95919. gammaSpace,
  95920. /**
  95921. * Internal Use Only
  95922. */
  95923. reserved) {
  95924. if (noMipmap === void 0) { noMipmap = false; }
  95925. if (generateHarmonics === void 0) { generateHarmonics = true; }
  95926. if (gammaSpace === void 0) { gammaSpace = false; }
  95927. if (reserved === void 0) { reserved = false; }
  95928. var _this = _super.call(this, name) || this;
  95929. _this.name = name;
  95930. _this.url = url;
  95931. _this.size = size;
  95932. _this.noMipmap = noMipmap;
  95933. _this.generateHarmonics = generateHarmonics;
  95934. _this.gammaSpace = gammaSpace;
  95935. _this.reserved = reserved;
  95936. return _this;
  95937. }
  95938. /**
  95939. * Execute the current task
  95940. * @param scene defines the scene where you want your assets to be loaded
  95941. * @param onSuccess is a callback called when the task is successfully executed
  95942. * @param onError is a callback called if an error occurs
  95943. */
  95944. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  95945. var onload = function () {
  95946. onSuccess();
  95947. };
  95948. var onerror = function (message, exception) {
  95949. onError(message, exception);
  95950. };
  95951. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.gammaSpace, this.reserved, onload, onerror);
  95952. };
  95953. return HDRCubeTextureAssetTask;
  95954. }(AbstractAssetTask));
  95955. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  95956. /**
  95957. * This class can be used to easily import assets into a scene
  95958. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  95959. */
  95960. var AssetsManager = /** @class */ (function () {
  95961. /**
  95962. * Creates a new AssetsManager
  95963. * @param scene defines the scene to work on
  95964. */
  95965. function AssetsManager(scene) {
  95966. this._isLoading = false;
  95967. this._tasks = new Array();
  95968. this._waitingTasksCount = 0;
  95969. this._totalTasksCount = 0;
  95970. /**
  95971. * Observable called when all tasks are processed
  95972. */
  95973. this.onTaskSuccessObservable = new BABYLON.Observable();
  95974. /**
  95975. * Observable called when a task had an error
  95976. */
  95977. this.onTaskErrorObservable = new BABYLON.Observable();
  95978. /**
  95979. * Observable called when a task is successful
  95980. */
  95981. this.onTasksDoneObservable = new BABYLON.Observable();
  95982. /**
  95983. * Observable called when a task is done (whatever the result is)
  95984. */
  95985. this.onProgressObservable = new BABYLON.Observable();
  95986. /**
  95987. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  95988. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  95989. */
  95990. this.useDefaultLoadingScreen = true;
  95991. this._scene = scene;
  95992. }
  95993. /**
  95994. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  95995. * @param taskName defines the name of the new task
  95996. * @param meshesNames defines the name of meshes to load
  95997. * @param rootUrl defines the root url to use to locate files
  95998. * @param sceneFilename defines the filename of the scene file
  95999. * @returns a new {BABYLON.MeshAssetTask} object
  96000. */
  96001. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  96002. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  96003. this._tasks.push(task);
  96004. return task;
  96005. };
  96006. /**
  96007. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  96008. * @param taskName defines the name of the new task
  96009. * @param url defines the url of the file to load
  96010. * @returns a new {BABYLON.TextFileAssetTask} object
  96011. */
  96012. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  96013. var task = new TextFileAssetTask(taskName, url);
  96014. this._tasks.push(task);
  96015. return task;
  96016. };
  96017. /**
  96018. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  96019. * @param taskName defines the name of the new task
  96020. * @param url defines the url of the file to load
  96021. * @returns a new {BABYLON.BinaryFileAssetTask} object
  96022. */
  96023. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  96024. var task = new BinaryFileAssetTask(taskName, url);
  96025. this._tasks.push(task);
  96026. return task;
  96027. };
  96028. /**
  96029. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  96030. * @param taskName defines the name of the new task
  96031. * @param url defines the url of the file to load
  96032. * @returns a new {BABYLON.ImageAssetTask} object
  96033. */
  96034. AssetsManager.prototype.addImageTask = function (taskName, url) {
  96035. var task = new ImageAssetTask(taskName, url);
  96036. this._tasks.push(task);
  96037. return task;
  96038. };
  96039. /**
  96040. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  96041. * @param taskName defines the name of the new task
  96042. * @param url defines the url of the file to load
  96043. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  96044. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  96045. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  96046. * @returns a new {BABYLON.TextureAssetTask} object
  96047. */
  96048. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  96049. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  96050. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  96051. this._tasks.push(task);
  96052. return task;
  96053. };
  96054. /**
  96055. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  96056. * @param taskName defines the name of the new task
  96057. * @param url defines the url of the file to load
  96058. * @param extensions defines the extension to use to load the cube map (can be null)
  96059. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  96060. * @param files defines the list of files to load (can be null)
  96061. * @returns a new {BABYLON.CubeTextureAssetTask} object
  96062. */
  96063. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  96064. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  96065. this._tasks.push(task);
  96066. return task;
  96067. };
  96068. /**
  96069. *
  96070. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  96071. * @param taskName defines the name of the new task
  96072. * @param url defines the url of the file to load
  96073. * @param size defines the size you want for the cubemap (can be null)
  96074. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  96075. * @param generateHarmonics defines if you want to automatically generate (true by default)
  96076. * @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)
  96077. * @param reserved Internal use only
  96078. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  96079. */
  96080. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved) {
  96081. if (noMipmap === void 0) { noMipmap = false; }
  96082. if (generateHarmonics === void 0) { generateHarmonics = true; }
  96083. if (gammaSpace === void 0) { gammaSpace = false; }
  96084. if (reserved === void 0) { reserved = false; }
  96085. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved);
  96086. this._tasks.push(task);
  96087. return task;
  96088. };
  96089. /**
  96090. * Remove a task from the assets manager.
  96091. * @param task the task to remove
  96092. */
  96093. AssetsManager.prototype.removeTask = function (task) {
  96094. var index = this._tasks.indexOf(task);
  96095. if (index > -1) {
  96096. this._tasks.splice(index, 1);
  96097. }
  96098. };
  96099. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  96100. this._waitingTasksCount--;
  96101. try {
  96102. if (this.onProgress) {
  96103. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  96104. }
  96105. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  96106. }
  96107. catch (e) {
  96108. BABYLON.Tools.Error("Error running progress callbacks.");
  96109. console.log(e);
  96110. }
  96111. if (this._waitingTasksCount === 0) {
  96112. try {
  96113. if (this.onFinish) {
  96114. this.onFinish(this._tasks);
  96115. }
  96116. // Let's remove successfull tasks
  96117. var currentTasks = this._tasks.slice();
  96118. for (var _i = 0, currentTasks_1 = currentTasks; _i < currentTasks_1.length; _i++) {
  96119. var task = currentTasks_1[_i];
  96120. if (task.taskState === AssetTaskState.DONE) {
  96121. var index = this._tasks.indexOf(task);
  96122. if (index > -1) {
  96123. this._tasks.splice(index, 1);
  96124. }
  96125. }
  96126. }
  96127. this.onTasksDoneObservable.notifyObservers(this._tasks);
  96128. }
  96129. catch (e) {
  96130. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  96131. console.log(e);
  96132. }
  96133. this._isLoading = false;
  96134. this._scene.getEngine().hideLoadingUI();
  96135. }
  96136. };
  96137. AssetsManager.prototype._runTask = function (task) {
  96138. var _this = this;
  96139. var done = function () {
  96140. try {
  96141. if (_this.onTaskSuccess) {
  96142. _this.onTaskSuccess(task);
  96143. }
  96144. _this.onTaskSuccessObservable.notifyObservers(task);
  96145. _this._decreaseWaitingTasksCount(task);
  96146. }
  96147. catch (e) {
  96148. error("Error executing task success callbacks", e);
  96149. }
  96150. };
  96151. var error = function (message, exception) {
  96152. task._setErrorObject(message, exception);
  96153. if (_this.onTaskError) {
  96154. _this.onTaskError(task);
  96155. }
  96156. _this.onTaskErrorObservable.notifyObservers(task);
  96157. _this._decreaseWaitingTasksCount(task);
  96158. };
  96159. task.run(this._scene, done, error);
  96160. };
  96161. /**
  96162. * Reset the {BABYLON.AssetsManager} and remove all tasks
  96163. * @return the current instance of the {BABYLON.AssetsManager}
  96164. */
  96165. AssetsManager.prototype.reset = function () {
  96166. this._isLoading = false;
  96167. this._tasks = new Array();
  96168. return this;
  96169. };
  96170. /**
  96171. * Start the loading process
  96172. * @return the current instance of the {BABYLON.AssetsManager}
  96173. */
  96174. AssetsManager.prototype.load = function () {
  96175. if (this._isLoading) {
  96176. return this;
  96177. }
  96178. this._isLoading = true;
  96179. this._waitingTasksCount = this._tasks.length;
  96180. this._totalTasksCount = this._tasks.length;
  96181. if (this._waitingTasksCount === 0) {
  96182. this._isLoading = false;
  96183. if (this.onFinish) {
  96184. this.onFinish(this._tasks);
  96185. }
  96186. this.onTasksDoneObservable.notifyObservers(this._tasks);
  96187. return this;
  96188. }
  96189. if (this.useDefaultLoadingScreen) {
  96190. this._scene.getEngine().displayLoadingUI();
  96191. }
  96192. for (var index = 0; index < this._tasks.length; index++) {
  96193. var task = this._tasks[index];
  96194. if (task.taskState === AssetTaskState.INIT) {
  96195. this._runTask(task);
  96196. }
  96197. }
  96198. return this;
  96199. };
  96200. return AssetsManager;
  96201. }());
  96202. BABYLON.AssetsManager = AssetsManager;
  96203. })(BABYLON || (BABYLON = {}));
  96204. //# sourceMappingURL=babylon.assetsManager.js.map
  96205. var BABYLON;
  96206. (function (BABYLON) {
  96207. var serializedGeometries = [];
  96208. var serializeGeometry = function (geometry, serializationGeometries) {
  96209. if (serializedGeometries[geometry.id]) {
  96210. return;
  96211. }
  96212. if (geometry.doNotSerialize) {
  96213. return;
  96214. }
  96215. if (geometry instanceof BABYLON.BoxGeometry) {
  96216. serializationGeometries.boxes.push(geometry.serialize());
  96217. }
  96218. else if (geometry instanceof BABYLON.SphereGeometry) {
  96219. serializationGeometries.spheres.push(geometry.serialize());
  96220. }
  96221. else if (geometry instanceof BABYLON.CylinderGeometry) {
  96222. serializationGeometries.cylinders.push(geometry.serialize());
  96223. }
  96224. else if (geometry instanceof BABYLON.TorusGeometry) {
  96225. serializationGeometries.toruses.push(geometry.serialize());
  96226. }
  96227. else if (geometry instanceof BABYLON.GroundGeometry) {
  96228. serializationGeometries.grounds.push(geometry.serialize());
  96229. }
  96230. else if (geometry instanceof BABYLON.Plane) {
  96231. serializationGeometries.planes.push(geometry.serialize());
  96232. }
  96233. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  96234. serializationGeometries.torusKnots.push(geometry.serialize());
  96235. }
  96236. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  96237. throw new Error("Unknown primitive type");
  96238. }
  96239. else {
  96240. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  96241. }
  96242. serializedGeometries[geometry.id] = true;
  96243. };
  96244. var serializeMesh = function (mesh, serializationScene) {
  96245. var serializationObject = {};
  96246. // Geometry
  96247. var geometry = mesh._geometry;
  96248. if (geometry) {
  96249. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  96250. // 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
  96251. serializeGeometry(geometry, serializationScene.geometries);
  96252. }
  96253. }
  96254. // Custom
  96255. if (mesh.serialize) {
  96256. mesh.serialize(serializationObject);
  96257. }
  96258. return serializationObject;
  96259. };
  96260. var finalizeSingleMesh = function (mesh, serializationObject) {
  96261. //only works if the mesh is already loaded
  96262. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  96263. //serialize material
  96264. if (mesh.material) {
  96265. if (mesh.material instanceof BABYLON.MultiMaterial) {
  96266. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  96267. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  96268. serializationObject.multiMaterials.push(mesh.material.serialize());
  96269. }
  96270. }
  96271. else {
  96272. serializationObject.materials = serializationObject.materials || [];
  96273. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  96274. serializationObject.materials.push(mesh.material.serialize());
  96275. }
  96276. }
  96277. }
  96278. //serialize geometry
  96279. var geometry = mesh._geometry;
  96280. if (geometry) {
  96281. if (!serializationObject.geometries) {
  96282. serializationObject.geometries = {};
  96283. serializationObject.geometries.boxes = [];
  96284. serializationObject.geometries.spheres = [];
  96285. serializationObject.geometries.cylinders = [];
  96286. serializationObject.geometries.toruses = [];
  96287. serializationObject.geometries.grounds = [];
  96288. serializationObject.geometries.planes = [];
  96289. serializationObject.geometries.torusKnots = [];
  96290. serializationObject.geometries.vertexData = [];
  96291. }
  96292. serializeGeometry(geometry, serializationObject.geometries);
  96293. }
  96294. // Skeletons
  96295. if (mesh.skeleton) {
  96296. serializationObject.skeletons = serializationObject.skeletons || [];
  96297. serializationObject.skeletons.push(mesh.skeleton.serialize());
  96298. }
  96299. //serialize the actual mesh
  96300. serializationObject.meshes = serializationObject.meshes || [];
  96301. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  96302. }
  96303. };
  96304. var SceneSerializer = /** @class */ (function () {
  96305. function SceneSerializer() {
  96306. }
  96307. SceneSerializer.ClearCache = function () {
  96308. serializedGeometries = [];
  96309. };
  96310. SceneSerializer.Serialize = function (scene) {
  96311. var serializationObject = {};
  96312. SceneSerializer.ClearCache();
  96313. // Scene
  96314. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  96315. serializationObject.autoClear = scene.autoClear;
  96316. serializationObject.clearColor = scene.clearColor.asArray();
  96317. serializationObject.ambientColor = scene.ambientColor.asArray();
  96318. serializationObject.gravity = scene.gravity.asArray();
  96319. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  96320. serializationObject.workerCollisions = scene.workerCollisions;
  96321. // Fog
  96322. if (scene.fogMode && scene.fogMode !== 0) {
  96323. serializationObject.fogMode = scene.fogMode;
  96324. serializationObject.fogColor = scene.fogColor.asArray();
  96325. serializationObject.fogStart = scene.fogStart;
  96326. serializationObject.fogEnd = scene.fogEnd;
  96327. serializationObject.fogDensity = scene.fogDensity;
  96328. }
  96329. //Physics
  96330. if (scene.isPhysicsEnabled()) {
  96331. var physicEngine = scene.getPhysicsEngine();
  96332. if (physicEngine) {
  96333. serializationObject.physicsEnabled = true;
  96334. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  96335. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  96336. }
  96337. }
  96338. // Metadata
  96339. if (scene.metadata) {
  96340. serializationObject.metadata = scene.metadata;
  96341. }
  96342. // Morph targets
  96343. serializationObject.morphTargetManagers = [];
  96344. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  96345. var abstractMesh = _a[_i];
  96346. var manager = abstractMesh.morphTargetManager;
  96347. if (manager) {
  96348. serializationObject.morphTargetManagers.push(manager.serialize());
  96349. }
  96350. }
  96351. // Lights
  96352. serializationObject.lights = [];
  96353. var index;
  96354. var light;
  96355. for (index = 0; index < scene.lights.length; index++) {
  96356. light = scene.lights[index];
  96357. if (!light.doNotSerialize) {
  96358. serializationObject.lights.push(light.serialize());
  96359. }
  96360. }
  96361. // Cameras
  96362. serializationObject.cameras = [];
  96363. for (index = 0; index < scene.cameras.length; index++) {
  96364. var camera = scene.cameras[index];
  96365. if (!camera.doNotSerialize) {
  96366. serializationObject.cameras.push(camera.serialize());
  96367. }
  96368. }
  96369. if (scene.activeCamera) {
  96370. serializationObject.activeCameraID = scene.activeCamera.id;
  96371. }
  96372. // Animations
  96373. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  96374. // Materials
  96375. serializationObject.materials = [];
  96376. serializationObject.multiMaterials = [];
  96377. var material;
  96378. for (index = 0; index < scene.materials.length; index++) {
  96379. material = scene.materials[index];
  96380. if (!material.doNotSerialize) {
  96381. serializationObject.materials.push(material.serialize());
  96382. }
  96383. }
  96384. // MultiMaterials
  96385. serializationObject.multiMaterials = [];
  96386. for (index = 0; index < scene.multiMaterials.length; index++) {
  96387. var multiMaterial = scene.multiMaterials[index];
  96388. serializationObject.multiMaterials.push(multiMaterial.serialize());
  96389. }
  96390. // Environment texture
  96391. if (scene.environmentTexture) {
  96392. serializationObject.environmentTexture = scene.environmentTexture.name;
  96393. }
  96394. // Skeletons
  96395. serializationObject.skeletons = [];
  96396. for (index = 0; index < scene.skeletons.length; index++) {
  96397. var skeleton = scene.skeletons[index];
  96398. if (!skeleton.doNotSerialize) {
  96399. serializationObject.skeletons.push(skeleton.serialize());
  96400. }
  96401. }
  96402. // Transform nodes
  96403. serializationObject.transformNodes = [];
  96404. for (index = 0; index < scene.transformNodes.length; index++) {
  96405. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  96406. }
  96407. // Geometries
  96408. serializationObject.geometries = {};
  96409. serializationObject.geometries.boxes = [];
  96410. serializationObject.geometries.spheres = [];
  96411. serializationObject.geometries.cylinders = [];
  96412. serializationObject.geometries.toruses = [];
  96413. serializationObject.geometries.grounds = [];
  96414. serializationObject.geometries.planes = [];
  96415. serializationObject.geometries.torusKnots = [];
  96416. serializationObject.geometries.vertexData = [];
  96417. serializedGeometries = [];
  96418. var geometries = scene.getGeometries();
  96419. for (index = 0; index < geometries.length; index++) {
  96420. var geometry = geometries[index];
  96421. if (geometry.isReady()) {
  96422. serializeGeometry(geometry, serializationObject.geometries);
  96423. }
  96424. }
  96425. // Meshes
  96426. serializationObject.meshes = [];
  96427. for (index = 0; index < scene.meshes.length; index++) {
  96428. var abstractMesh = scene.meshes[index];
  96429. if (abstractMesh instanceof BABYLON.Mesh) {
  96430. var mesh = abstractMesh;
  96431. if (!mesh.doNotSerialize) {
  96432. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  96433. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  96434. }
  96435. }
  96436. }
  96437. }
  96438. // Particles Systems
  96439. serializationObject.particleSystems = [];
  96440. for (index = 0; index < scene.particleSystems.length; index++) {
  96441. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  96442. }
  96443. // Lens flares
  96444. serializationObject.lensFlareSystems = [];
  96445. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  96446. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  96447. }
  96448. // Shadows
  96449. serializationObject.shadowGenerators = [];
  96450. for (index = 0; index < scene.lights.length; index++) {
  96451. light = scene.lights[index];
  96452. var shadowGenerator = light.getShadowGenerator();
  96453. if (shadowGenerator) {
  96454. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  96455. }
  96456. }
  96457. // Action Manager
  96458. if (scene.actionManager) {
  96459. serializationObject.actions = scene.actionManager.serialize("scene");
  96460. }
  96461. // Audio
  96462. serializationObject.sounds = [];
  96463. for (index = 0; index < scene.soundTracks.length; index++) {
  96464. var soundtrack = scene.soundTracks[index];
  96465. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  96466. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  96467. }
  96468. }
  96469. // Effect layers
  96470. serializationObject.effectLayers = [];
  96471. for (index = 0; index < scene.effectLayers.length; index++) {
  96472. var layer = scene.effectLayers[index];
  96473. if (layer.serialize) {
  96474. serializationObject.effectLayers.push(layer.serialize());
  96475. }
  96476. }
  96477. return serializationObject;
  96478. };
  96479. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  96480. if (withParents === void 0) { withParents = false; }
  96481. if (withChildren === void 0) { withChildren = false; }
  96482. var serializationObject = {};
  96483. SceneSerializer.ClearCache();
  96484. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  96485. if (withParents || withChildren) {
  96486. //deliberate for loop! not for each, appended should be processed as well.
  96487. for (var i = 0; i < toSerialize.length; ++i) {
  96488. if (withChildren) {
  96489. toSerialize[i].getDescendants().forEach(function (node) {
  96490. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  96491. toSerialize.push(node);
  96492. }
  96493. });
  96494. }
  96495. //make sure the array doesn't contain the object already
  96496. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  96497. toSerialize.push(toSerialize[i].parent);
  96498. }
  96499. }
  96500. }
  96501. toSerialize.forEach(function (mesh) {
  96502. finalizeSingleMesh(mesh, serializationObject);
  96503. });
  96504. return serializationObject;
  96505. };
  96506. return SceneSerializer;
  96507. }());
  96508. BABYLON.SceneSerializer = SceneSerializer;
  96509. })(BABYLON || (BABYLON = {}));
  96510. //# sourceMappingURL=babylon.sceneSerializer.js.map
  96511. var BABYLON;
  96512. (function (BABYLON) {
  96513. var ReflectionProbe = /** @class */ (function () {
  96514. function ReflectionProbe(name, size, scene, generateMipMaps) {
  96515. if (generateMipMaps === void 0) { generateMipMaps = true; }
  96516. var _this = this;
  96517. this.name = name;
  96518. this._viewMatrix = BABYLON.Matrix.Identity();
  96519. this._target = BABYLON.Vector3.Zero();
  96520. this._add = BABYLON.Vector3.Zero();
  96521. this._invertYAxis = false;
  96522. this.position = BABYLON.Vector3.Zero();
  96523. this._scene = scene;
  96524. this._scene.reflectionProbes.push(this);
  96525. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  96526. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  96527. switch (faceIndex) {
  96528. case 0:
  96529. _this._add.copyFromFloats(1, 0, 0);
  96530. break;
  96531. case 1:
  96532. _this._add.copyFromFloats(-1, 0, 0);
  96533. break;
  96534. case 2:
  96535. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  96536. break;
  96537. case 3:
  96538. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  96539. break;
  96540. case 4:
  96541. _this._add.copyFromFloats(0, 0, 1);
  96542. break;
  96543. case 5:
  96544. _this._add.copyFromFloats(0, 0, -1);
  96545. break;
  96546. }
  96547. if (_this._attachedMesh) {
  96548. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  96549. }
  96550. _this.position.addToRef(_this._add, _this._target);
  96551. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  96552. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  96553. scene._forcedViewPosition = _this.position;
  96554. });
  96555. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  96556. scene._forcedViewPosition = null;
  96557. scene.updateTransformMatrix(true);
  96558. });
  96559. if (scene.activeCamera) {
  96560. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  96561. }
  96562. }
  96563. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  96564. get: function () {
  96565. return this._renderTargetTexture.samples;
  96566. },
  96567. set: function (value) {
  96568. this._renderTargetTexture.samples = value;
  96569. },
  96570. enumerable: true,
  96571. configurable: true
  96572. });
  96573. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  96574. get: function () {
  96575. return this._renderTargetTexture.refreshRate;
  96576. },
  96577. set: function (value) {
  96578. this._renderTargetTexture.refreshRate = value;
  96579. },
  96580. enumerable: true,
  96581. configurable: true
  96582. });
  96583. ReflectionProbe.prototype.getScene = function () {
  96584. return this._scene;
  96585. };
  96586. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  96587. get: function () {
  96588. return this._renderTargetTexture;
  96589. },
  96590. enumerable: true,
  96591. configurable: true
  96592. });
  96593. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  96594. get: function () {
  96595. return this._renderTargetTexture.renderList;
  96596. },
  96597. enumerable: true,
  96598. configurable: true
  96599. });
  96600. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  96601. this._attachedMesh = mesh;
  96602. };
  96603. /**
  96604. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  96605. *
  96606. * @param renderingGroupId The rendering group id corresponding to its index
  96607. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  96608. */
  96609. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  96610. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  96611. };
  96612. ReflectionProbe.prototype.dispose = function () {
  96613. var index = this._scene.reflectionProbes.indexOf(this);
  96614. if (index !== -1) {
  96615. // Remove from the scene if found
  96616. this._scene.reflectionProbes.splice(index, 1);
  96617. }
  96618. if (this._renderTargetTexture) {
  96619. this._renderTargetTexture.dispose();
  96620. this._renderTargetTexture = null;
  96621. }
  96622. };
  96623. return ReflectionProbe;
  96624. }());
  96625. BABYLON.ReflectionProbe = ReflectionProbe;
  96626. })(BABYLON || (BABYLON = {}));
  96627. //# sourceMappingURL=babylon.reflectionProbe.js.map
  96628. var BABYLON;
  96629. (function (BABYLON) {
  96630. var Layer = /** @class */ (function () {
  96631. function Layer(name, imgUrl, scene, isBackground, color) {
  96632. this.name = name;
  96633. this.scale = new BABYLON.Vector2(1, 1);
  96634. this.offset = new BABYLON.Vector2(0, 0);
  96635. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  96636. this.layerMask = 0x0FFFFFFF;
  96637. this._vertexBuffers = {};
  96638. // Events
  96639. /**
  96640. * An event triggered when the layer is disposed.
  96641. */
  96642. this.onDisposeObservable = new BABYLON.Observable();
  96643. /**
  96644. * An event triggered before rendering the scene
  96645. */
  96646. this.onBeforeRenderObservable = new BABYLON.Observable();
  96647. /**
  96648. * An event triggered after rendering the scene
  96649. */
  96650. this.onAfterRenderObservable = new BABYLON.Observable();
  96651. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  96652. this.isBackground = isBackground === undefined ? true : isBackground;
  96653. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  96654. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  96655. this._scene.layers.push(this);
  96656. var engine = this._scene.getEngine();
  96657. // VBO
  96658. var vertices = [];
  96659. vertices.push(1, 1);
  96660. vertices.push(-1, 1);
  96661. vertices.push(-1, -1);
  96662. vertices.push(1, -1);
  96663. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  96664. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  96665. this._createIndexBuffer();
  96666. // Effects
  96667. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  96668. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  96669. }
  96670. Object.defineProperty(Layer.prototype, "onDispose", {
  96671. set: function (callback) {
  96672. if (this._onDisposeObserver) {
  96673. this.onDisposeObservable.remove(this._onDisposeObserver);
  96674. }
  96675. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  96676. },
  96677. enumerable: true,
  96678. configurable: true
  96679. });
  96680. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  96681. set: function (callback) {
  96682. if (this._onBeforeRenderObserver) {
  96683. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  96684. }
  96685. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  96686. },
  96687. enumerable: true,
  96688. configurable: true
  96689. });
  96690. Object.defineProperty(Layer.prototype, "onAfterRender", {
  96691. set: function (callback) {
  96692. if (this._onAfterRenderObserver) {
  96693. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  96694. }
  96695. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  96696. },
  96697. enumerable: true,
  96698. configurable: true
  96699. });
  96700. Layer.prototype._createIndexBuffer = function () {
  96701. var engine = this._scene.getEngine();
  96702. // Indices
  96703. var indices = [];
  96704. indices.push(0);
  96705. indices.push(1);
  96706. indices.push(2);
  96707. indices.push(0);
  96708. indices.push(2);
  96709. indices.push(3);
  96710. this._indexBuffer = engine.createIndexBuffer(indices);
  96711. };
  96712. Layer.prototype._rebuild = function () {
  96713. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  96714. if (vb) {
  96715. vb._rebuild();
  96716. }
  96717. this._createIndexBuffer();
  96718. };
  96719. Layer.prototype.render = function () {
  96720. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  96721. // Check
  96722. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  96723. return;
  96724. var engine = this._scene.getEngine();
  96725. this.onBeforeRenderObservable.notifyObservers(this);
  96726. // Render
  96727. engine.enableEffect(currentEffect);
  96728. engine.setState(false);
  96729. // Texture
  96730. currentEffect.setTexture("textureSampler", this.texture);
  96731. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  96732. // Color
  96733. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  96734. // Scale / offset
  96735. currentEffect.setVector2("offset", this.offset);
  96736. currentEffect.setVector2("scale", this.scale);
  96737. // VBOs
  96738. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  96739. // Draw order
  96740. if (!this.alphaTest) {
  96741. engine.setAlphaMode(this.alphaBlendingMode);
  96742. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  96743. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  96744. }
  96745. else {
  96746. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  96747. }
  96748. this.onAfterRenderObservable.notifyObservers(this);
  96749. };
  96750. Layer.prototype.dispose = function () {
  96751. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  96752. if (vertexBuffer) {
  96753. vertexBuffer.dispose();
  96754. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  96755. }
  96756. if (this._indexBuffer) {
  96757. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  96758. this._indexBuffer = null;
  96759. }
  96760. if (this.texture) {
  96761. this.texture.dispose();
  96762. this.texture = null;
  96763. }
  96764. // Remove from scene
  96765. var index = this._scene.layers.indexOf(this);
  96766. this._scene.layers.splice(index, 1);
  96767. // Callback
  96768. this.onDisposeObservable.notifyObservers(this);
  96769. this.onDisposeObservable.clear();
  96770. this.onAfterRenderObservable.clear();
  96771. this.onBeforeRenderObservable.clear();
  96772. };
  96773. return Layer;
  96774. }());
  96775. BABYLON.Layer = Layer;
  96776. })(BABYLON || (BABYLON = {}));
  96777. //# sourceMappingURL=babylon.layer.js.map
  96778. var BABYLON;
  96779. (function (BABYLON) {
  96780. var TextureTools = /** @class */ (function () {
  96781. function TextureTools() {
  96782. }
  96783. /**
  96784. * Uses the GPU to create a copy texture rescaled at a given size
  96785. * @param texture Texture to copy from
  96786. * @param width Desired width
  96787. * @param height Desired height
  96788. * @return Generated texture
  96789. */
  96790. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  96791. if (useBilinearMode === void 0) { useBilinearMode = true; }
  96792. var scene = texture.getScene();
  96793. var engine = scene.getEngine();
  96794. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  96795. rtt.wrapU = texture.wrapU;
  96796. rtt.wrapV = texture.wrapV;
  96797. rtt.uOffset = texture.uOffset;
  96798. rtt.vOffset = texture.vOffset;
  96799. rtt.uScale = texture.uScale;
  96800. rtt.vScale = texture.vScale;
  96801. rtt.uAng = texture.uAng;
  96802. rtt.vAng = texture.vAng;
  96803. rtt.wAng = texture.wAng;
  96804. rtt.coordinatesIndex = texture.coordinatesIndex;
  96805. rtt.level = texture.level;
  96806. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  96807. rtt._texture.isReady = false;
  96808. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  96809. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  96810. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  96811. passPostProcess.getEffect().executeWhenCompiled(function () {
  96812. passPostProcess.onApply = function (effect) {
  96813. effect.setTexture("textureSampler", texture);
  96814. };
  96815. var internalTexture = rtt.getInternalTexture();
  96816. if (internalTexture) {
  96817. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  96818. engine.unBindFramebuffer(internalTexture);
  96819. rtt.disposeFramebufferObjects();
  96820. passPostProcess.dispose();
  96821. internalTexture.isReady = true;
  96822. }
  96823. });
  96824. return rtt;
  96825. };
  96826. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  96827. if (!scene._environmentBRDFTexture) {
  96828. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  96829. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  96830. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  96831. scene._environmentBRDFTexture = texture;
  96832. }
  96833. return scene._environmentBRDFTexture;
  96834. };
  96835. TextureTools._environmentBRDFBase64Texture = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQAAAAEACAYAAABccqhmAAAgAElEQVR4Xu19Z7PtTHbW1g3jMMbGmGDAZAMm5xxMLDAU0WSKWOQcCoqccw6eGdtgk4yNbZxnvvAL+Af8Af6AsQl+06ako9X36dXPSi3pnPu+cz/cOntL3S1pq5+w1mrpLs/eud9fvn27rf9evPPwFz+v22S7fGZ/n7/70G79J5/Xv/qzbLP+Pnvvoc/6Tz7jX/15/c62LfeH7fofbpfP3l/ct36Wf+u4+D37+XYb++G26LPsr/zFttnPuh37bm1bt0f7MvtlnOx4uv0H4fty8UUsz77rfn/57u32cgXvDv72eQf0tl0+G38b0Nf9K4Dl704MEfA16KsE8Gw9JgD+DQE8EA0DT2b7GwK4GHnF4a8iguXZt9/vL5/dbisJbEq/uwD5vIK/fbbAv4N9U/8nJIDNCazK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fBb9Xm7ccwXB8cQVE7QayIW8groI0s5KwOmYEHm9Cm/suUP+MEp/V5oiaV8B6VdsZEphR9Jk+FXLYCMAE0oTtb2OpCZoBq+kAjLFMsgDP4x33TOsfugohMnJuEUEM56lmRaSIV+/PnP8RwGfHrxzjyrZnksPlBPBlRhlwxrpnwW8CnWXJC0RymBCS5b4zwV5Wf+hwBNhH+lqW9rHdwVF1P9r/dQZ6ljiWlQC0SjIbPLRRilYFv0cC7Yc9WOrLAFWf94y9n+ljnZurdie8YnzquMS9PAUJHAVshqCs63oMsFeuzzvPaB8eZ/lS7QCU4jJVNckgUGurH1XuiVJfilSYFTdUtUIgR0nA67/tU7OjouBll2GEKVnQZ4EWXUPFps8es3KM15EEskoPt3T7KP02AojUO0UCk+CnoCWAzII7Au2w3yG8o6COzoUBioKCnKPrFBjJqRlQcQLVY2WJIjNuBaCvIwlUVX0G0NVjdATwMXEAAYBdEnhC8Ecgc/efGPNH5xFNdhOQRdt/ptpHCh3tj675CFE8JTFUjv2UriFz7GUlgOp/DNKRwUHwdxPfUeMjDoCCq5BfOOoEZvpr2x+BLavolXEyAM6obnTMzHEqoMuc09HxKv2rbTPAVYZO/ydUbXfkKP4/BnecprBuissAAAAASUVORK5CYII=";
  96836. return TextureTools;
  96837. }());
  96838. BABYLON.TextureTools = TextureTools;
  96839. })(BABYLON || (BABYLON = {}));
  96840. //# sourceMappingURL=babylon.textureTools.js.map
  96841. var BABYLON;
  96842. (function (BABYLON) {
  96843. var FramingBehavior = /** @class */ (function () {
  96844. function FramingBehavior() {
  96845. this._mode = FramingBehavior.FitFrustumSidesMode;
  96846. this._radiusScale = 1.0;
  96847. this._positionScale = 0.5;
  96848. this._defaultElevation = 0.3;
  96849. this._elevationReturnTime = 1500;
  96850. this._elevationReturnWaitTime = 1000;
  96851. this._zoomStopsAnimation = false;
  96852. this._framingTime = 1500;
  96853. this._isPointerDown = false;
  96854. this._lastInteractionTime = -Infinity;
  96855. // Framing control
  96856. this._animatables = new Array();
  96857. this._betaIsAnimating = false;
  96858. }
  96859. Object.defineProperty(FramingBehavior.prototype, "name", {
  96860. get: function () {
  96861. return "Framing";
  96862. },
  96863. enumerable: true,
  96864. configurable: true
  96865. });
  96866. Object.defineProperty(FramingBehavior.prototype, "mode", {
  96867. /**
  96868. * Gets current mode used by the behavior.
  96869. */
  96870. get: function () {
  96871. return this._mode;
  96872. },
  96873. /**
  96874. * Sets the current mode used by the behavior
  96875. */
  96876. set: function (mode) {
  96877. this._mode = mode;
  96878. },
  96879. enumerable: true,
  96880. configurable: true
  96881. });
  96882. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  96883. /**
  96884. * Gets the scale applied to the radius
  96885. */
  96886. get: function () {
  96887. return this._radiusScale;
  96888. },
  96889. /**
  96890. * Sets the scale applied to the radius (1 by default)
  96891. */
  96892. set: function (radius) {
  96893. this._radiusScale = radius;
  96894. },
  96895. enumerable: true,
  96896. configurable: true
  96897. });
  96898. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  96899. /**
  96900. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  96901. */
  96902. get: function () {
  96903. return this._positionScale;
  96904. },
  96905. /**
  96906. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  96907. */
  96908. set: function (scale) {
  96909. this._positionScale = scale;
  96910. },
  96911. enumerable: true,
  96912. configurable: true
  96913. });
  96914. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  96915. /**
  96916. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  96917. * behaviour is triggered, in radians.
  96918. */
  96919. get: function () {
  96920. return this._defaultElevation;
  96921. },
  96922. /**
  96923. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  96924. * behaviour is triggered, in radians.
  96925. */
  96926. set: function (elevation) {
  96927. this._defaultElevation = elevation;
  96928. },
  96929. enumerable: true,
  96930. configurable: true
  96931. });
  96932. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  96933. /**
  96934. * Gets the time (in milliseconds) taken to return to the default beta position.
  96935. * Negative value indicates camera should not return to default.
  96936. */
  96937. get: function () {
  96938. return this._elevationReturnTime;
  96939. },
  96940. /**
  96941. * Sets the time (in milliseconds) taken to return to the default beta position.
  96942. * Negative value indicates camera should not return to default.
  96943. */
  96944. set: function (speed) {
  96945. this._elevationReturnTime = speed;
  96946. },
  96947. enumerable: true,
  96948. configurable: true
  96949. });
  96950. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  96951. /**
  96952. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  96953. */
  96954. get: function () {
  96955. return this._elevationReturnWaitTime;
  96956. },
  96957. /**
  96958. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  96959. */
  96960. set: function (time) {
  96961. this._elevationReturnWaitTime = time;
  96962. },
  96963. enumerable: true,
  96964. configurable: true
  96965. });
  96966. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  96967. /**
  96968. * Gets the flag that indicates if user zooming should stop animation.
  96969. */
  96970. get: function () {
  96971. return this._zoomStopsAnimation;
  96972. },
  96973. /**
  96974. * Sets the flag that indicates if user zooming should stop animation.
  96975. */
  96976. set: function (flag) {
  96977. this._zoomStopsAnimation = flag;
  96978. },
  96979. enumerable: true,
  96980. configurable: true
  96981. });
  96982. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  96983. /**
  96984. * Gets the transition time when framing the mesh, in milliseconds
  96985. */
  96986. get: function () {
  96987. return this._framingTime;
  96988. },
  96989. /**
  96990. * Sets the transition time when framing the mesh, in milliseconds
  96991. */
  96992. set: function (time) {
  96993. this._framingTime = time;
  96994. },
  96995. enumerable: true,
  96996. configurable: true
  96997. });
  96998. FramingBehavior.prototype.init = function () {
  96999. // Do notihng
  97000. };
  97001. FramingBehavior.prototype.attach = function (camera) {
  97002. var _this = this;
  97003. this._attachedCamera = camera;
  97004. var scene = this._attachedCamera.getScene();
  97005. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  97006. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  97007. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  97008. _this._isPointerDown = true;
  97009. return;
  97010. }
  97011. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  97012. _this._isPointerDown = false;
  97013. }
  97014. });
  97015. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  97016. if (mesh) {
  97017. _this.zoomOnMesh(mesh);
  97018. }
  97019. });
  97020. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  97021. // Stop the animation if there is user interaction and the animation should stop for this interaction
  97022. _this._applyUserInteraction();
  97023. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  97024. // back to the default position after a given timeout
  97025. _this._maintainCameraAboveGround();
  97026. });
  97027. };
  97028. FramingBehavior.prototype.detach = function () {
  97029. if (!this._attachedCamera) {
  97030. return;
  97031. }
  97032. var scene = this._attachedCamera.getScene();
  97033. if (this._onPrePointerObservableObserver) {
  97034. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  97035. }
  97036. if (this._onAfterCheckInputsObserver) {
  97037. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  97038. }
  97039. if (this._onMeshTargetChangedObserver) {
  97040. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  97041. }
  97042. this._attachedCamera = null;
  97043. };
  97044. /**
  97045. * Targets the given mesh and updates zoom level accordingly.
  97046. * @param mesh The mesh to target.
  97047. * @param radius Optional. If a cached radius position already exists, overrides default.
  97048. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  97049. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  97050. * @param onAnimationEnd Callback triggered at the end of the framing animation
  97051. */
  97052. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  97053. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  97054. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  97055. mesh.computeWorldMatrix(true);
  97056. var boundingBox = mesh.getBoundingInfo().boundingBox;
  97057. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  97058. };
  97059. /**
  97060. * Targets the given mesh with its children and updates zoom level accordingly.
  97061. * @param mesh The mesh to target.
  97062. * @param radius Optional. If a cached radius position already exists, overrides default.
  97063. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  97064. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  97065. * @param onAnimationEnd Callback triggered at the end of the framing animation
  97066. */
  97067. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  97068. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  97069. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  97070. mesh.computeWorldMatrix(true);
  97071. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  97072. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  97073. };
  97074. /**
  97075. * Targets the given meshes with their children and updates zoom level accordingly.
  97076. * @param meshes The mesh to target.
  97077. * @param radius Optional. If a cached radius position already exists, overrides default.
  97078. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  97079. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  97080. * @param onAnimationEnd Callback triggered at the end of the framing animation
  97081. */
  97082. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  97083. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  97084. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  97085. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  97086. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  97087. for (var i = 0; i < meshes.length; i++) {
  97088. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  97089. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  97090. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  97091. }
  97092. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  97093. };
  97094. /**
  97095. * Targets the given mesh and updates zoom level accordingly.
  97096. * @param mesh The mesh to target.
  97097. * @param radius Optional. If a cached radius position already exists, overrides default.
  97098. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  97099. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  97100. * @param onAnimationEnd Callback triggered at the end of the framing animation
  97101. */
  97102. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  97103. var _this = this;
  97104. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  97105. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  97106. var zoomTarget;
  97107. if (!this._attachedCamera) {
  97108. return;
  97109. }
  97110. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  97111. var bottom = minimumWorld.y;
  97112. var top = maximumWorld.y;
  97113. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  97114. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  97115. if (focusOnOriginXZ) {
  97116. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  97117. }
  97118. else {
  97119. var centerWorld = minimumWorld.add(radiusWorld);
  97120. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  97121. }
  97122. if (!this._vectorTransition) {
  97123. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  97124. }
  97125. this._betaIsAnimating = true;
  97126. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  97127. if (animatable) {
  97128. this._animatables.push(animatable);
  97129. }
  97130. // sets the radius and lower radius bounds
  97131. // Small delta ensures camera is not always at lower zoom limit.
  97132. var radius = 0;
  97133. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  97134. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  97135. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  97136. radius = position;
  97137. }
  97138. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  97139. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  97140. if (this._attachedCamera.lowerRadiusLimit === null) {
  97141. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  97142. }
  97143. }
  97144. // Set sensibilities
  97145. var extend = maximumWorld.subtract(minimumWorld).length();
  97146. this._attachedCamera.panningSensibility = 5000 / extend;
  97147. this._attachedCamera.wheelPrecision = 100 / radius;
  97148. // transition to new radius
  97149. if (!this._radiusTransition) {
  97150. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  97151. }
  97152. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  97153. _this.stopAllAnimations();
  97154. if (onAnimationEnd) {
  97155. onAnimationEnd();
  97156. }
  97157. if (_this._attachedCamera) {
  97158. _this._attachedCamera.storeState();
  97159. }
  97160. });
  97161. if (animatable) {
  97162. this._animatables.push(animatable);
  97163. }
  97164. };
  97165. /**
  97166. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  97167. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  97168. * frustum width.
  97169. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  97170. * to fully enclose the mesh in the viewing frustum.
  97171. */
  97172. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  97173. var size = maximumWorld.subtract(minimumWorld);
  97174. var boxVectorGlobalDiagonal = size.length();
  97175. var frustumSlope = this._getFrustumSlope();
  97176. // Formula for setting distance
  97177. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  97178. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  97179. // Horizon distance
  97180. var radius = radiusWithoutFraming * this._radiusScale;
  97181. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  97182. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  97183. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  97184. var camera = this._attachedCamera;
  97185. if (!camera) {
  97186. return 0;
  97187. }
  97188. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  97189. // Don't exceed the requested limit
  97190. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  97191. }
  97192. // Don't exceed the upper radius limit
  97193. if (camera.upperRadiusLimit) {
  97194. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  97195. }
  97196. return distance;
  97197. };
  97198. /**
  97199. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  97200. * is automatically returned to its default position (expected to be above ground plane).
  97201. */
  97202. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  97203. var _this = this;
  97204. if (this._elevationReturnTime < 0) {
  97205. return;
  97206. }
  97207. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  97208. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  97209. var limitBeta = Math.PI * 0.5;
  97210. // Bring the camera back up if below the ground plane
  97211. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  97212. this._betaIsAnimating = true;
  97213. //Transition to new position
  97214. this.stopAllAnimations();
  97215. if (!this._betaTransition) {
  97216. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  97217. }
  97218. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  97219. _this._clearAnimationLocks();
  97220. _this.stopAllAnimations();
  97221. });
  97222. if (animatabe) {
  97223. this._animatables.push(animatabe);
  97224. }
  97225. }
  97226. };
  97227. /**
  97228. * Returns the frustum slope based on the canvas ratio and camera FOV
  97229. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  97230. */
  97231. FramingBehavior.prototype._getFrustumSlope = function () {
  97232. // Calculate the viewport ratio
  97233. // Aspect Ratio is Height/Width.
  97234. var camera = this._attachedCamera;
  97235. if (!camera) {
  97236. return BABYLON.Vector2.Zero();
  97237. }
  97238. var engine = camera.getScene().getEngine();
  97239. var aspectRatio = engine.getAspectRatio(camera);
  97240. // Camera FOV is the vertical field of view (top-bottom) in radians.
  97241. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  97242. var frustumSlopeY = Math.tan(camera.fov / 2);
  97243. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  97244. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  97245. // along the forward vector.
  97246. var frustumSlopeX = frustumSlopeY * aspectRatio;
  97247. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  97248. };
  97249. /**
  97250. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  97251. */
  97252. FramingBehavior.prototype._clearAnimationLocks = function () {
  97253. this._betaIsAnimating = false;
  97254. };
  97255. /**
  97256. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  97257. */
  97258. FramingBehavior.prototype._applyUserInteraction = function () {
  97259. if (this.isUserIsMoving) {
  97260. this._lastInteractionTime = BABYLON.Tools.Now;
  97261. this.stopAllAnimations();
  97262. this._clearAnimationLocks();
  97263. }
  97264. };
  97265. /**
  97266. * Stops and removes all animations that have been applied to the camera
  97267. */
  97268. FramingBehavior.prototype.stopAllAnimations = function () {
  97269. if (this._attachedCamera) {
  97270. this._attachedCamera.animations = [];
  97271. }
  97272. while (this._animatables.length) {
  97273. if (this._animatables[0]) {
  97274. this._animatables[0].onAnimationEnd = null;
  97275. this._animatables[0].stop();
  97276. }
  97277. this._animatables.shift();
  97278. }
  97279. };
  97280. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  97281. /**
  97282. * Gets a value indicating if the user is moving the camera
  97283. */
  97284. get: function () {
  97285. if (!this._attachedCamera) {
  97286. return false;
  97287. }
  97288. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  97289. this._attachedCamera.inertialBetaOffset !== 0 ||
  97290. this._attachedCamera.inertialRadiusOffset !== 0 ||
  97291. this._attachedCamera.inertialPanningX !== 0 ||
  97292. this._attachedCamera.inertialPanningY !== 0 ||
  97293. this._isPointerDown;
  97294. },
  97295. enumerable: true,
  97296. configurable: true
  97297. });
  97298. /**
  97299. * The easing function used by animations
  97300. */
  97301. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  97302. /**
  97303. * The easing mode used by animations
  97304. */
  97305. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  97306. // Statics
  97307. /**
  97308. * The camera can move all the way towards the mesh.
  97309. */
  97310. FramingBehavior.IgnoreBoundsSizeMode = 0;
  97311. /**
  97312. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  97313. */
  97314. FramingBehavior.FitFrustumSidesMode = 1;
  97315. return FramingBehavior;
  97316. }());
  97317. BABYLON.FramingBehavior = FramingBehavior;
  97318. })(BABYLON || (BABYLON = {}));
  97319. //# sourceMappingURL=babylon.framingBehavior.js.map
  97320. var BABYLON;
  97321. (function (BABYLON) {
  97322. /**
  97323. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  97324. */
  97325. var BouncingBehavior = /** @class */ (function () {
  97326. function BouncingBehavior() {
  97327. /**
  97328. * The duration of the animation, in milliseconds
  97329. */
  97330. this.transitionDuration = 450;
  97331. /**
  97332. * Length of the distance animated by the transition when lower radius is reached
  97333. */
  97334. this.lowerRadiusTransitionRange = 2;
  97335. /**
  97336. * Length of the distance animated by the transition when upper radius is reached
  97337. */
  97338. this.upperRadiusTransitionRange = -2;
  97339. this._autoTransitionRange = false;
  97340. // Animations
  97341. this._radiusIsAnimating = false;
  97342. this._radiusBounceTransition = null;
  97343. this._animatables = new Array();
  97344. }
  97345. Object.defineProperty(BouncingBehavior.prototype, "name", {
  97346. get: function () {
  97347. return "Bouncing";
  97348. },
  97349. enumerable: true,
  97350. configurable: true
  97351. });
  97352. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  97353. /**
  97354. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  97355. */
  97356. get: function () {
  97357. return this._autoTransitionRange;
  97358. },
  97359. /**
  97360. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  97361. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  97362. */
  97363. set: function (value) {
  97364. var _this = this;
  97365. if (this._autoTransitionRange === value) {
  97366. return;
  97367. }
  97368. this._autoTransitionRange = value;
  97369. var camera = this._attachedCamera;
  97370. if (!camera) {
  97371. return;
  97372. }
  97373. if (value) {
  97374. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  97375. if (!mesh) {
  97376. return;
  97377. }
  97378. mesh.computeWorldMatrix(true);
  97379. var diagonal = mesh.getBoundingInfo().diagonalLength;
  97380. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  97381. _this.upperRadiusTransitionRange = diagonal * 0.05;
  97382. });
  97383. }
  97384. else if (this._onMeshTargetChangedObserver) {
  97385. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  97386. }
  97387. },
  97388. enumerable: true,
  97389. configurable: true
  97390. });
  97391. BouncingBehavior.prototype.init = function () {
  97392. // Do notihng
  97393. };
  97394. BouncingBehavior.prototype.attach = function (camera) {
  97395. var _this = this;
  97396. this._attachedCamera = camera;
  97397. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  97398. if (!_this._attachedCamera) {
  97399. return;
  97400. }
  97401. // Add the bounce animation to the lower radius limit
  97402. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  97403. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  97404. }
  97405. // Add the bounce animation to the upper radius limit
  97406. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  97407. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  97408. }
  97409. });
  97410. };
  97411. BouncingBehavior.prototype.detach = function () {
  97412. if (!this._attachedCamera) {
  97413. return;
  97414. }
  97415. if (this._onAfterCheckInputsObserver) {
  97416. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  97417. }
  97418. if (this._onMeshTargetChangedObserver) {
  97419. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  97420. }
  97421. this._attachedCamera = null;
  97422. };
  97423. /**
  97424. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  97425. * @param radiusLimit The limit to check against.
  97426. * @return Bool to indicate if at limit.
  97427. */
  97428. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  97429. if (!this._attachedCamera) {
  97430. return false;
  97431. }
  97432. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  97433. return true;
  97434. }
  97435. return false;
  97436. };
  97437. /**
  97438. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  97439. * @param radiusDelta The delta by which to animate to. Can be negative.
  97440. */
  97441. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  97442. var _this = this;
  97443. if (!this._attachedCamera) {
  97444. return;
  97445. }
  97446. if (!this._radiusBounceTransition) {
  97447. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  97448. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  97449. }
  97450. // Prevent zoom until bounce has completed
  97451. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  97452. this._attachedCamera.wheelPrecision = Infinity;
  97453. this._attachedCamera.inertialRadiusOffset = 0;
  97454. // Animate to the radius limit
  97455. this.stopAllAnimations();
  97456. this._radiusIsAnimating = true;
  97457. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  97458. if (animatable) {
  97459. this._animatables.push(animatable);
  97460. }
  97461. };
  97462. /**
  97463. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  97464. */
  97465. BouncingBehavior.prototype._clearAnimationLocks = function () {
  97466. this._radiusIsAnimating = false;
  97467. if (this._attachedCamera) {
  97468. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  97469. }
  97470. };
  97471. /**
  97472. * Stops and removes all animations that have been applied to the camera
  97473. */
  97474. BouncingBehavior.prototype.stopAllAnimations = function () {
  97475. if (this._attachedCamera) {
  97476. this._attachedCamera.animations = [];
  97477. }
  97478. while (this._animatables.length) {
  97479. this._animatables[0].onAnimationEnd = null;
  97480. this._animatables[0].stop();
  97481. this._animatables.shift();
  97482. }
  97483. };
  97484. /**
  97485. * The easing function used by animations
  97486. */
  97487. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  97488. /**
  97489. * The easing mode used by animations
  97490. */
  97491. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  97492. return BouncingBehavior;
  97493. }());
  97494. BABYLON.BouncingBehavior = BouncingBehavior;
  97495. })(BABYLON || (BABYLON = {}));
  97496. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  97497. var BABYLON;
  97498. (function (BABYLON) {
  97499. var AutoRotationBehavior = /** @class */ (function () {
  97500. function AutoRotationBehavior() {
  97501. this._zoomStopsAnimation = false;
  97502. this._idleRotationSpeed = 0.05;
  97503. this._idleRotationWaitTime = 2000;
  97504. this._idleRotationSpinupTime = 2000;
  97505. this._isPointerDown = false;
  97506. this._lastFrameTime = null;
  97507. this._lastInteractionTime = -Infinity;
  97508. this._cameraRotationSpeed = 0;
  97509. this._lastFrameRadius = 0;
  97510. }
  97511. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  97512. get: function () {
  97513. return "AutoRotation";
  97514. },
  97515. enumerable: true,
  97516. configurable: true
  97517. });
  97518. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  97519. /**
  97520. * Gets the flag that indicates if user zooming should stop animation.
  97521. */
  97522. get: function () {
  97523. return this._zoomStopsAnimation;
  97524. },
  97525. /**
  97526. * Sets the flag that indicates if user zooming should stop animation.
  97527. */
  97528. set: function (flag) {
  97529. this._zoomStopsAnimation = flag;
  97530. },
  97531. enumerable: true,
  97532. configurable: true
  97533. });
  97534. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  97535. /**
  97536. * Gets the default speed at which the camera rotates around the model.
  97537. */
  97538. get: function () {
  97539. return this._idleRotationSpeed;
  97540. },
  97541. /**
  97542. * Sets the default speed at which the camera rotates around the model.
  97543. */
  97544. set: function (speed) {
  97545. this._idleRotationSpeed = speed;
  97546. },
  97547. enumerable: true,
  97548. configurable: true
  97549. });
  97550. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  97551. /**
  97552. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  97553. */
  97554. get: function () {
  97555. return this._idleRotationWaitTime;
  97556. },
  97557. /**
  97558. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  97559. */
  97560. set: function (time) {
  97561. this._idleRotationWaitTime = time;
  97562. },
  97563. enumerable: true,
  97564. configurable: true
  97565. });
  97566. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  97567. /**
  97568. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  97569. */
  97570. get: function () {
  97571. return this._idleRotationSpinupTime;
  97572. },
  97573. /**
  97574. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  97575. */
  97576. set: function (time) {
  97577. this._idleRotationSpinupTime = time;
  97578. },
  97579. enumerable: true,
  97580. configurable: true
  97581. });
  97582. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  97583. /**
  97584. * Gets a value indicating if the camera is currently rotating because of this behavior
  97585. */
  97586. get: function () {
  97587. return Math.abs(this._cameraRotationSpeed) > 0;
  97588. },
  97589. enumerable: true,
  97590. configurable: true
  97591. });
  97592. AutoRotationBehavior.prototype.init = function () {
  97593. // Do notihng
  97594. };
  97595. AutoRotationBehavior.prototype.attach = function (camera) {
  97596. var _this = this;
  97597. this._attachedCamera = camera;
  97598. var scene = this._attachedCamera.getScene();
  97599. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  97600. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  97601. _this._isPointerDown = true;
  97602. return;
  97603. }
  97604. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  97605. _this._isPointerDown = false;
  97606. }
  97607. });
  97608. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  97609. var now = BABYLON.Tools.Now;
  97610. var dt = 0;
  97611. if (_this._lastFrameTime != null) {
  97612. dt = now - _this._lastFrameTime;
  97613. }
  97614. _this._lastFrameTime = now;
  97615. // Stop the animation if there is user interaction and the animation should stop for this interaction
  97616. _this._applyUserInteraction();
  97617. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  97618. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  97619. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  97620. // Step camera rotation by rotation speed
  97621. if (_this._attachedCamera) {
  97622. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  97623. }
  97624. });
  97625. };
  97626. AutoRotationBehavior.prototype.detach = function () {
  97627. if (!this._attachedCamera) {
  97628. return;
  97629. }
  97630. var scene = this._attachedCamera.getScene();
  97631. if (this._onPrePointerObservableObserver) {
  97632. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  97633. }
  97634. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  97635. this._attachedCamera = null;
  97636. };
  97637. /**
  97638. * Returns true if user is scrolling.
  97639. * @return true if user is scrolling.
  97640. */
  97641. AutoRotationBehavior.prototype._userIsZooming = function () {
  97642. if (!this._attachedCamera) {
  97643. return false;
  97644. }
  97645. return this._attachedCamera.inertialRadiusOffset !== 0;
  97646. };
  97647. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  97648. if (!this._attachedCamera) {
  97649. return false;
  97650. }
  97651. var zoomHasHitLimit = false;
  97652. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  97653. zoomHasHitLimit = true;
  97654. }
  97655. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  97656. this._lastFrameRadius = this._attachedCamera.radius;
  97657. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  97658. };
  97659. /**
  97660. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  97661. */
  97662. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  97663. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  97664. this._lastInteractionTime = BABYLON.Tools.Now;
  97665. }
  97666. };
  97667. // Tools
  97668. AutoRotationBehavior.prototype._userIsMoving = function () {
  97669. if (!this._attachedCamera) {
  97670. return false;
  97671. }
  97672. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  97673. this._attachedCamera.inertialBetaOffset !== 0 ||
  97674. this._attachedCamera.inertialRadiusOffset !== 0 ||
  97675. this._attachedCamera.inertialPanningX !== 0 ||
  97676. this._attachedCamera.inertialPanningY !== 0 ||
  97677. this._isPointerDown;
  97678. };
  97679. return AutoRotationBehavior;
  97680. }());
  97681. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  97682. })(BABYLON || (BABYLON = {}));
  97683. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  97684. var BABYLON;
  97685. (function (BABYLON) {
  97686. var NullEngineOptions = /** @class */ (function () {
  97687. function NullEngineOptions() {
  97688. this.renderWidth = 512;
  97689. this.renderHeight = 256;
  97690. this.textureSize = 512;
  97691. this.deterministicLockstep = false;
  97692. this.lockstepMaxSteps = 4;
  97693. }
  97694. return NullEngineOptions;
  97695. }());
  97696. BABYLON.NullEngineOptions = NullEngineOptions;
  97697. /**
  97698. * The null engine class provides support for headless version of babylon.js.
  97699. * This can be used in server side scenario or for testing purposes
  97700. */
  97701. var NullEngine = /** @class */ (function (_super) {
  97702. __extends(NullEngine, _super);
  97703. function NullEngine(options) {
  97704. if (options === void 0) { options = new NullEngineOptions(); }
  97705. var _this = _super.call(this, null) || this;
  97706. if (options.deterministicLockstep === undefined) {
  97707. options.deterministicLockstep = false;
  97708. }
  97709. if (options.lockstepMaxSteps === undefined) {
  97710. options.lockstepMaxSteps = 4;
  97711. }
  97712. _this._options = options;
  97713. // Init caps
  97714. // We consider we are on a webgl1 capable device
  97715. _this._caps = new BABYLON.EngineCapabilities();
  97716. _this._caps.maxTexturesImageUnits = 16;
  97717. _this._caps.maxVertexTextureImageUnits = 16;
  97718. _this._caps.maxTextureSize = 512;
  97719. _this._caps.maxCubemapTextureSize = 512;
  97720. _this._caps.maxRenderTextureSize = 512;
  97721. _this._caps.maxVertexAttribs = 16;
  97722. _this._caps.maxVaryingVectors = 16;
  97723. _this._caps.maxFragmentUniformVectors = 16;
  97724. _this._caps.maxVertexUniformVectors = 16;
  97725. // Extensions
  97726. _this._caps.standardDerivatives = false;
  97727. _this._caps.astc = null;
  97728. _this._caps.s3tc = null;
  97729. _this._caps.pvrtc = null;
  97730. _this._caps.etc1 = null;
  97731. _this._caps.etc2 = null;
  97732. _this._caps.textureAnisotropicFilterExtension = null;
  97733. _this._caps.maxAnisotropy = 0;
  97734. _this._caps.uintIndices = false;
  97735. _this._caps.fragmentDepthSupported = false;
  97736. _this._caps.highPrecisionShaderSupported = true;
  97737. _this._caps.colorBufferFloat = false;
  97738. _this._caps.textureFloat = false;
  97739. _this._caps.textureFloatLinearFiltering = false;
  97740. _this._caps.textureFloatRender = false;
  97741. _this._caps.textureHalfFloat = false;
  97742. _this._caps.textureHalfFloatLinearFiltering = false;
  97743. _this._caps.textureHalfFloatRender = false;
  97744. _this._caps.textureLOD = false;
  97745. _this._caps.drawBuffersExtension = false;
  97746. _this._caps.depthTextureExtension = false;
  97747. _this._caps.vertexArrayObject = false;
  97748. _this._caps.instancedArrays = false;
  97749. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  97750. // Wrappers
  97751. if (typeof URL === "undefined") {
  97752. URL = {
  97753. createObjectURL: function () { },
  97754. revokeObjectURL: function () { }
  97755. };
  97756. }
  97757. if (typeof Blob === "undefined") {
  97758. Blob = function () { };
  97759. }
  97760. return _this;
  97761. }
  97762. NullEngine.prototype.isDeterministicLockStep = function () {
  97763. return this._options.deterministicLockstep;
  97764. };
  97765. NullEngine.prototype.getLockstepMaxSteps = function () {
  97766. return this._options.lockstepMaxSteps;
  97767. };
  97768. NullEngine.prototype.getHardwareScalingLevel = function () {
  97769. return 1.0;
  97770. };
  97771. NullEngine.prototype.createVertexBuffer = function (vertices) {
  97772. return {
  97773. capacity: 0,
  97774. references: 1,
  97775. is32Bits: false
  97776. };
  97777. };
  97778. NullEngine.prototype.createIndexBuffer = function (indices) {
  97779. return {
  97780. capacity: 0,
  97781. references: 1,
  97782. is32Bits: false
  97783. };
  97784. };
  97785. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  97786. if (stencil === void 0) { stencil = false; }
  97787. };
  97788. NullEngine.prototype.getRenderWidth = function (useScreen) {
  97789. if (useScreen === void 0) { useScreen = false; }
  97790. if (!useScreen && this._currentRenderTarget) {
  97791. return this._currentRenderTarget.width;
  97792. }
  97793. return this._options.renderWidth;
  97794. };
  97795. NullEngine.prototype.getRenderHeight = function (useScreen) {
  97796. if (useScreen === void 0) { useScreen = false; }
  97797. if (!useScreen && this._currentRenderTarget) {
  97798. return this._currentRenderTarget.height;
  97799. }
  97800. return this._options.renderHeight;
  97801. };
  97802. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  97803. this._cachedViewport = viewport;
  97804. };
  97805. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  97806. return {
  97807. transformFeedback: null,
  97808. __SPECTOR_rebuildProgram: null
  97809. };
  97810. };
  97811. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  97812. return [];
  97813. };
  97814. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  97815. return [];
  97816. };
  97817. NullEngine.prototype.bindSamplers = function (effect) {
  97818. this._currentEffect = null;
  97819. };
  97820. NullEngine.prototype.enableEffect = function (effect) {
  97821. this._currentEffect = effect;
  97822. if (effect.onBind) {
  97823. effect.onBind(effect);
  97824. }
  97825. effect.onBindObservable.notifyObservers(effect);
  97826. };
  97827. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  97828. if (zOffset === void 0) { zOffset = 0; }
  97829. if (reverseSide === void 0) { reverseSide = false; }
  97830. };
  97831. NullEngine.prototype.setIntArray = function (uniform, array) {
  97832. };
  97833. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  97834. };
  97835. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  97836. };
  97837. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  97838. };
  97839. NullEngine.prototype.setFloatArray = function (uniform, array) {
  97840. };
  97841. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  97842. };
  97843. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  97844. };
  97845. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  97846. };
  97847. NullEngine.prototype.setArray = function (uniform, array) {
  97848. };
  97849. NullEngine.prototype.setArray2 = function (uniform, array) {
  97850. };
  97851. NullEngine.prototype.setArray3 = function (uniform, array) {
  97852. };
  97853. NullEngine.prototype.setArray4 = function (uniform, array) {
  97854. };
  97855. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  97856. };
  97857. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  97858. };
  97859. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  97860. };
  97861. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  97862. };
  97863. NullEngine.prototype.setFloat = function (uniform, value) {
  97864. };
  97865. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  97866. };
  97867. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  97868. };
  97869. NullEngine.prototype.setBool = function (uniform, bool) {
  97870. };
  97871. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  97872. };
  97873. NullEngine.prototype.setColor3 = function (uniform, color3) {
  97874. };
  97875. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  97876. };
  97877. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  97878. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  97879. if (this._alphaMode === mode) {
  97880. return;
  97881. }
  97882. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  97883. if (!noDepthWriteChange) {
  97884. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  97885. }
  97886. this._alphaMode = mode;
  97887. };
  97888. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  97889. };
  97890. NullEngine.prototype.wipeCaches = function (bruteForce) {
  97891. if (this.preventCacheWipeBetweenFrames) {
  97892. return;
  97893. }
  97894. this.resetTextureCache();
  97895. this._currentEffect = null;
  97896. if (bruteForce) {
  97897. this._currentProgram = null;
  97898. this._stencilState.reset();
  97899. this._depthCullingState.reset();
  97900. this._alphaState.reset();
  97901. }
  97902. this._cachedVertexBuffers = null;
  97903. this._cachedIndexBuffer = null;
  97904. this._cachedEffectForVertexBuffers = null;
  97905. };
  97906. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  97907. };
  97908. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  97909. };
  97910. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  97911. };
  97912. NullEngine.prototype._createTexture = function () {
  97913. return {};
  97914. };
  97915. NullEngine.prototype._releaseTexture = function (texture) {
  97916. };
  97917. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  97918. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  97919. if (onLoad === void 0) { onLoad = null; }
  97920. if (onError === void 0) { onError = null; }
  97921. if (buffer === void 0) { buffer = null; }
  97922. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  97923. var url = String(urlArg);
  97924. texture.url = url;
  97925. texture.generateMipMaps = !noMipmap;
  97926. texture.samplingMode = samplingMode;
  97927. texture.invertY = invertY;
  97928. texture.baseWidth = this._options.textureSize;
  97929. texture.baseHeight = this._options.textureSize;
  97930. texture.width = this._options.textureSize;
  97931. texture.height = this._options.textureSize;
  97932. if (format) {
  97933. texture.format = format;
  97934. }
  97935. texture.isReady = true;
  97936. if (onLoad) {
  97937. onLoad();
  97938. }
  97939. this._internalTexturesCache.push(texture);
  97940. return texture;
  97941. };
  97942. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  97943. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  97944. if (options !== undefined && typeof options === "object") {
  97945. fullOptions.generateMipMaps = options.generateMipMaps;
  97946. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  97947. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  97948. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  97949. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  97950. }
  97951. else {
  97952. fullOptions.generateMipMaps = options;
  97953. fullOptions.generateDepthBuffer = true;
  97954. fullOptions.generateStencilBuffer = false;
  97955. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  97956. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  97957. }
  97958. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  97959. var width = size.width || size;
  97960. var height = size.height || size;
  97961. texture._depthStencilBuffer = {};
  97962. texture._framebuffer = {};
  97963. texture.baseWidth = width;
  97964. texture.baseHeight = height;
  97965. texture.width = width;
  97966. texture.height = height;
  97967. texture.isReady = true;
  97968. texture.samples = 1;
  97969. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  97970. texture.samplingMode = fullOptions.samplingMode;
  97971. texture.type = fullOptions.type;
  97972. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  97973. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  97974. this._internalTexturesCache.push(texture);
  97975. return texture;
  97976. };
  97977. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  97978. texture.samplingMode = samplingMode;
  97979. };
  97980. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  97981. if (this._currentRenderTarget) {
  97982. this.unBindFramebuffer(this._currentRenderTarget);
  97983. }
  97984. this._currentRenderTarget = texture;
  97985. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  97986. if (this._cachedViewport && !forceFullscreenViewport) {
  97987. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  97988. }
  97989. };
  97990. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  97991. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  97992. this._currentRenderTarget = null;
  97993. if (onBeforeUnbind) {
  97994. if (texture._MSAAFramebuffer) {
  97995. this._currentFramebuffer = texture._framebuffer;
  97996. }
  97997. onBeforeUnbind();
  97998. }
  97999. this._currentFramebuffer = null;
  98000. };
  98001. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  98002. var vbo = {
  98003. capacity: 1,
  98004. references: 1,
  98005. is32Bits: false
  98006. };
  98007. return vbo;
  98008. };
  98009. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  98010. if (offset === void 0) { offset = 0; }
  98011. };
  98012. /**
  98013. * Updates a dynamic vertex buffer.
  98014. * @param vertexBuffer the vertex buffer to update
  98015. * @param data the data used to update the vertex buffer
  98016. * @param byteOffset the byte offset of the data (optional)
  98017. * @param byteLength the byte length of the data (optional)
  98018. */
  98019. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  98020. };
  98021. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  98022. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  98023. this._boundTexturesCache[this._activeChannel] = texture;
  98024. }
  98025. };
  98026. NullEngine.prototype._bindTexture = function (channel, texture) {
  98027. if (channel < 0) {
  98028. return;
  98029. }
  98030. this._bindTextureDirectly(0, texture);
  98031. };
  98032. NullEngine.prototype._releaseBuffer = function (buffer) {
  98033. buffer.references--;
  98034. if (buffer.references === 0) {
  98035. return true;
  98036. }
  98037. return false;
  98038. };
  98039. NullEngine.prototype.releaseEffects = function () {
  98040. };
  98041. return NullEngine;
  98042. }(BABYLON.Engine));
  98043. BABYLON.NullEngine = NullEngine;
  98044. })(BABYLON || (BABYLON = {}));
  98045. //# sourceMappingURL=babylon.nullEngine.js.map
  98046. var BABYLON;
  98047. (function (BABYLON) {
  98048. /**
  98049. * This class can be used to get instrumentation data from a Babylon engine
  98050. */
  98051. var EngineInstrumentation = /** @class */ (function () {
  98052. function EngineInstrumentation(engine) {
  98053. this.engine = engine;
  98054. this._captureGPUFrameTime = false;
  98055. this._gpuFrameTime = new BABYLON.PerfCounter();
  98056. this._captureShaderCompilationTime = false;
  98057. this._shaderCompilationTime = new BABYLON.PerfCounter();
  98058. // Observers
  98059. this._onBeginFrameObserver = null;
  98060. this._onEndFrameObserver = null;
  98061. this._onBeforeShaderCompilationObserver = null;
  98062. this._onAfterShaderCompilationObserver = null;
  98063. }
  98064. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  98065. // Properties
  98066. /**
  98067. * Gets the perf counter used for GPU frame time
  98068. */
  98069. get: function () {
  98070. return this._gpuFrameTime;
  98071. },
  98072. enumerable: true,
  98073. configurable: true
  98074. });
  98075. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  98076. /**
  98077. * Gets the GPU frame time capture status
  98078. */
  98079. get: function () {
  98080. return this._captureGPUFrameTime;
  98081. },
  98082. /**
  98083. * Enable or disable the GPU frame time capture
  98084. */
  98085. set: function (value) {
  98086. var _this = this;
  98087. if (value === this._captureGPUFrameTime) {
  98088. return;
  98089. }
  98090. this._captureGPUFrameTime = value;
  98091. if (value) {
  98092. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  98093. if (!_this._gpuFrameTimeToken) {
  98094. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  98095. }
  98096. });
  98097. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  98098. if (!_this._gpuFrameTimeToken) {
  98099. return;
  98100. }
  98101. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  98102. if (time > -1) {
  98103. _this._gpuFrameTimeToken = null;
  98104. _this._gpuFrameTime.fetchNewFrame();
  98105. _this._gpuFrameTime.addCount(time, true);
  98106. }
  98107. });
  98108. }
  98109. else {
  98110. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  98111. this._onBeginFrameObserver = null;
  98112. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  98113. this._onEndFrameObserver = null;
  98114. }
  98115. },
  98116. enumerable: true,
  98117. configurable: true
  98118. });
  98119. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  98120. /**
  98121. * Gets the perf counter used for shader compilation time
  98122. */
  98123. get: function () {
  98124. return this._shaderCompilationTime;
  98125. },
  98126. enumerable: true,
  98127. configurable: true
  98128. });
  98129. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  98130. /**
  98131. * Gets the shader compilation time capture status
  98132. */
  98133. get: function () {
  98134. return this._captureShaderCompilationTime;
  98135. },
  98136. /**
  98137. * Enable or disable the shader compilation time capture
  98138. */
  98139. set: function (value) {
  98140. var _this = this;
  98141. if (value === this._captureShaderCompilationTime) {
  98142. return;
  98143. }
  98144. this._captureShaderCompilationTime = value;
  98145. if (value) {
  98146. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  98147. _this._shaderCompilationTime.fetchNewFrame();
  98148. _this._shaderCompilationTime.beginMonitoring();
  98149. });
  98150. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  98151. _this._shaderCompilationTime.endMonitoring();
  98152. });
  98153. }
  98154. else {
  98155. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  98156. this._onBeforeShaderCompilationObserver = null;
  98157. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  98158. this._onAfterShaderCompilationObserver = null;
  98159. }
  98160. },
  98161. enumerable: true,
  98162. configurable: true
  98163. });
  98164. EngineInstrumentation.prototype.dispose = function () {
  98165. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  98166. this._onBeginFrameObserver = null;
  98167. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  98168. this._onEndFrameObserver = null;
  98169. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  98170. this._onBeforeShaderCompilationObserver = null;
  98171. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  98172. this._onAfterShaderCompilationObserver = null;
  98173. this.engine = null;
  98174. };
  98175. return EngineInstrumentation;
  98176. }());
  98177. BABYLON.EngineInstrumentation = EngineInstrumentation;
  98178. })(BABYLON || (BABYLON = {}));
  98179. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  98180. var BABYLON;
  98181. (function (BABYLON) {
  98182. /**
  98183. * This class can be used to get instrumentation data from a Babylon engine
  98184. */
  98185. var SceneInstrumentation = /** @class */ (function () {
  98186. function SceneInstrumentation(scene) {
  98187. var _this = this;
  98188. this.scene = scene;
  98189. this._captureActiveMeshesEvaluationTime = false;
  98190. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  98191. this._captureRenderTargetsRenderTime = false;
  98192. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  98193. this._captureFrameTime = false;
  98194. this._frameTime = new BABYLON.PerfCounter();
  98195. this._captureRenderTime = false;
  98196. this._renderTime = new BABYLON.PerfCounter();
  98197. this._captureInterFrameTime = false;
  98198. this._interFrameTime = new BABYLON.PerfCounter();
  98199. this._captureParticlesRenderTime = false;
  98200. this._particlesRenderTime = new BABYLON.PerfCounter();
  98201. this._captureSpritesRenderTime = false;
  98202. this._spritesRenderTime = new BABYLON.PerfCounter();
  98203. this._capturePhysicsTime = false;
  98204. this._physicsTime = new BABYLON.PerfCounter();
  98205. this._captureAnimationsTime = false;
  98206. this._animationsTime = new BABYLON.PerfCounter();
  98207. this._captureCameraRenderTime = false;
  98208. this._cameraRenderTime = new BABYLON.PerfCounter();
  98209. // Observers
  98210. this._onBeforeActiveMeshesEvaluationObserver = null;
  98211. this._onAfterActiveMeshesEvaluationObserver = null;
  98212. this._onBeforeRenderTargetsRenderObserver = null;
  98213. this._onAfterRenderTargetsRenderObserver = null;
  98214. this._onAfterRenderObserver = null;
  98215. this._onBeforeDrawPhaseObserver = null;
  98216. this._onAfterDrawPhaseObserver = null;
  98217. this._onBeforeAnimationsObserver = null;
  98218. this._onBeforeParticlesRenderingObserver = null;
  98219. this._onAfterParticlesRenderingObserver = null;
  98220. this._onBeforeSpritesRenderingObserver = null;
  98221. this._onAfterSpritesRenderingObserver = null;
  98222. this._onBeforePhysicsObserver = null;
  98223. this._onAfterPhysicsObserver = null;
  98224. this._onAfterAnimationsObserver = null;
  98225. this._onBeforeCameraRenderObserver = null;
  98226. this._onAfterCameraRenderObserver = null;
  98227. // Before render
  98228. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  98229. if (_this._captureActiveMeshesEvaluationTime) {
  98230. _this._activeMeshesEvaluationTime.fetchNewFrame();
  98231. }
  98232. if (_this._captureRenderTargetsRenderTime) {
  98233. _this._renderTargetsRenderTime.fetchNewFrame();
  98234. }
  98235. if (_this._captureFrameTime) {
  98236. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  98237. _this._frameTime.beginMonitoring();
  98238. }
  98239. if (_this._captureInterFrameTime) {
  98240. _this._interFrameTime.endMonitoring();
  98241. }
  98242. if (_this._captureParticlesRenderTime) {
  98243. _this._particlesRenderTime.fetchNewFrame();
  98244. }
  98245. if (_this._captureSpritesRenderTime) {
  98246. _this._spritesRenderTime.fetchNewFrame();
  98247. }
  98248. if (_this._captureAnimationsTime) {
  98249. _this._animationsTime.beginMonitoring();
  98250. }
  98251. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  98252. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  98253. });
  98254. // After render
  98255. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  98256. if (_this._captureFrameTime) {
  98257. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  98258. _this._frameTime.endMonitoring();
  98259. }
  98260. if (_this._captureRenderTime) {
  98261. _this._renderTime.endMonitoring(false);
  98262. }
  98263. if (_this._captureInterFrameTime) {
  98264. _this._interFrameTime.beginMonitoring();
  98265. }
  98266. });
  98267. }
  98268. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  98269. // Properties
  98270. /**
  98271. * Gets the perf counter used for active meshes evaluation time
  98272. */
  98273. get: function () {
  98274. return this._activeMeshesEvaluationTime;
  98275. },
  98276. enumerable: true,
  98277. configurable: true
  98278. });
  98279. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  98280. /**
  98281. * Gets the active meshes evaluation time capture status
  98282. */
  98283. get: function () {
  98284. return this._captureActiveMeshesEvaluationTime;
  98285. },
  98286. /**
  98287. * Enable or disable the active meshes evaluation time capture
  98288. */
  98289. set: function (value) {
  98290. var _this = this;
  98291. if (value === this._captureActiveMeshesEvaluationTime) {
  98292. return;
  98293. }
  98294. this._captureActiveMeshesEvaluationTime = value;
  98295. if (value) {
  98296. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  98297. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  98298. _this._activeMeshesEvaluationTime.beginMonitoring();
  98299. });
  98300. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  98301. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  98302. _this._activeMeshesEvaluationTime.endMonitoring();
  98303. });
  98304. }
  98305. else {
  98306. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  98307. this._onBeforeActiveMeshesEvaluationObserver = null;
  98308. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  98309. this._onAfterActiveMeshesEvaluationObserver = null;
  98310. }
  98311. },
  98312. enumerable: true,
  98313. configurable: true
  98314. });
  98315. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  98316. /**
  98317. * Gets the perf counter used for render targets render time
  98318. */
  98319. get: function () {
  98320. return this._renderTargetsRenderTime;
  98321. },
  98322. enumerable: true,
  98323. configurable: true
  98324. });
  98325. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  98326. /**
  98327. * Gets the render targets render time capture status
  98328. */
  98329. get: function () {
  98330. return this._captureRenderTargetsRenderTime;
  98331. },
  98332. /**
  98333. * Enable or disable the render targets render time capture
  98334. */
  98335. set: function (value) {
  98336. var _this = this;
  98337. if (value === this._captureRenderTargetsRenderTime) {
  98338. return;
  98339. }
  98340. this._captureRenderTargetsRenderTime = value;
  98341. if (value) {
  98342. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  98343. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  98344. _this._renderTargetsRenderTime.beginMonitoring();
  98345. });
  98346. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  98347. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  98348. _this._renderTargetsRenderTime.endMonitoring(false);
  98349. });
  98350. }
  98351. else {
  98352. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  98353. this._onBeforeRenderTargetsRenderObserver = null;
  98354. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  98355. this._onAfterRenderTargetsRenderObserver = null;
  98356. }
  98357. },
  98358. enumerable: true,
  98359. configurable: true
  98360. });
  98361. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  98362. /**
  98363. * Gets the perf counter used for particles render time
  98364. */
  98365. get: function () {
  98366. return this._particlesRenderTime;
  98367. },
  98368. enumerable: true,
  98369. configurable: true
  98370. });
  98371. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  98372. /**
  98373. * Gets the particles render time capture status
  98374. */
  98375. get: function () {
  98376. return this._captureParticlesRenderTime;
  98377. },
  98378. /**
  98379. * Enable or disable the particles render time capture
  98380. */
  98381. set: function (value) {
  98382. var _this = this;
  98383. if (value === this._captureParticlesRenderTime) {
  98384. return;
  98385. }
  98386. this._captureParticlesRenderTime = value;
  98387. if (value) {
  98388. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  98389. BABYLON.Tools.StartPerformanceCounter("Particles");
  98390. _this._particlesRenderTime.beginMonitoring();
  98391. });
  98392. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  98393. BABYLON.Tools.EndPerformanceCounter("Particles");
  98394. _this._particlesRenderTime.endMonitoring(false);
  98395. });
  98396. }
  98397. else {
  98398. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  98399. this._onBeforeParticlesRenderingObserver = null;
  98400. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  98401. this._onAfterParticlesRenderingObserver = null;
  98402. }
  98403. },
  98404. enumerable: true,
  98405. configurable: true
  98406. });
  98407. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  98408. /**
  98409. * Gets the perf counter used for sprites render time
  98410. */
  98411. get: function () {
  98412. return this._spritesRenderTime;
  98413. },
  98414. enumerable: true,
  98415. configurable: true
  98416. });
  98417. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  98418. /**
  98419. * Gets the sprites render time capture status
  98420. */
  98421. get: function () {
  98422. return this._captureSpritesRenderTime;
  98423. },
  98424. /**
  98425. * Enable or disable the sprites render time capture
  98426. */
  98427. set: function (value) {
  98428. var _this = this;
  98429. if (value === this._captureSpritesRenderTime) {
  98430. return;
  98431. }
  98432. this._captureSpritesRenderTime = value;
  98433. if (value) {
  98434. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  98435. BABYLON.Tools.StartPerformanceCounter("Sprites");
  98436. _this._spritesRenderTime.beginMonitoring();
  98437. });
  98438. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  98439. BABYLON.Tools.EndPerformanceCounter("Sprites");
  98440. _this._spritesRenderTime.endMonitoring(false);
  98441. });
  98442. }
  98443. else {
  98444. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  98445. this._onBeforeSpritesRenderingObserver = null;
  98446. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  98447. this._onAfterSpritesRenderingObserver = null;
  98448. }
  98449. },
  98450. enumerable: true,
  98451. configurable: true
  98452. });
  98453. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  98454. /**
  98455. * Gets the perf counter used for physics time
  98456. */
  98457. get: function () {
  98458. return this._physicsTime;
  98459. },
  98460. enumerable: true,
  98461. configurable: true
  98462. });
  98463. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  98464. /**
  98465. * Gets the physics time capture status
  98466. */
  98467. get: function () {
  98468. return this._capturePhysicsTime;
  98469. },
  98470. /**
  98471. * Enable or disable the physics time capture
  98472. */
  98473. set: function (value) {
  98474. var _this = this;
  98475. if (value === this._capturePhysicsTime) {
  98476. return;
  98477. }
  98478. this._capturePhysicsTime = value;
  98479. if (value) {
  98480. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  98481. BABYLON.Tools.StartPerformanceCounter("Physics");
  98482. _this._physicsTime.beginMonitoring();
  98483. });
  98484. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  98485. BABYLON.Tools.EndPerformanceCounter("Physics");
  98486. _this._physicsTime.endMonitoring();
  98487. });
  98488. }
  98489. else {
  98490. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  98491. this._onBeforePhysicsObserver = null;
  98492. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  98493. this._onAfterPhysicsObserver = null;
  98494. }
  98495. },
  98496. enumerable: true,
  98497. configurable: true
  98498. });
  98499. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  98500. /**
  98501. * Gets the perf counter used for animations time
  98502. */
  98503. get: function () {
  98504. return this._animationsTime;
  98505. },
  98506. enumerable: true,
  98507. configurable: true
  98508. });
  98509. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  98510. /**
  98511. * Gets the animations time capture status
  98512. */
  98513. get: function () {
  98514. return this._captureAnimationsTime;
  98515. },
  98516. /**
  98517. * Enable or disable the animations time capture
  98518. */
  98519. set: function (value) {
  98520. var _this = this;
  98521. if (value === this._captureAnimationsTime) {
  98522. return;
  98523. }
  98524. this._captureAnimationsTime = value;
  98525. if (value) {
  98526. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  98527. _this._animationsTime.endMonitoring();
  98528. });
  98529. }
  98530. else {
  98531. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  98532. this._onAfterAnimationsObserver = null;
  98533. }
  98534. },
  98535. enumerable: true,
  98536. configurable: true
  98537. });
  98538. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  98539. /**
  98540. * Gets the perf counter used for frame time capture
  98541. */
  98542. get: function () {
  98543. return this._frameTime;
  98544. },
  98545. enumerable: true,
  98546. configurable: true
  98547. });
  98548. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  98549. /**
  98550. * Gets the frame time capture status
  98551. */
  98552. get: function () {
  98553. return this._captureFrameTime;
  98554. },
  98555. /**
  98556. * Enable or disable the frame time capture
  98557. */
  98558. set: function (value) {
  98559. this._captureFrameTime = value;
  98560. },
  98561. enumerable: true,
  98562. configurable: true
  98563. });
  98564. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  98565. /**
  98566. * Gets the perf counter used for inter-frames time capture
  98567. */
  98568. get: function () {
  98569. return this._interFrameTime;
  98570. },
  98571. enumerable: true,
  98572. configurable: true
  98573. });
  98574. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  98575. /**
  98576. * Gets the inter-frames time capture status
  98577. */
  98578. get: function () {
  98579. return this._captureInterFrameTime;
  98580. },
  98581. /**
  98582. * Enable or disable the inter-frames time capture
  98583. */
  98584. set: function (value) {
  98585. this._captureInterFrameTime = value;
  98586. },
  98587. enumerable: true,
  98588. configurable: true
  98589. });
  98590. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  98591. /**
  98592. * Gets the perf counter used for render time capture
  98593. */
  98594. get: function () {
  98595. return this._renderTime;
  98596. },
  98597. enumerable: true,
  98598. configurable: true
  98599. });
  98600. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  98601. /**
  98602. * Gets the render time capture status
  98603. */
  98604. get: function () {
  98605. return this._captureRenderTime;
  98606. },
  98607. /**
  98608. * Enable or disable the render time capture
  98609. */
  98610. set: function (value) {
  98611. var _this = this;
  98612. if (value === this._captureRenderTime) {
  98613. return;
  98614. }
  98615. this._captureRenderTime = value;
  98616. if (value) {
  98617. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  98618. _this._renderTime.beginMonitoring();
  98619. BABYLON.Tools.StartPerformanceCounter("Main render");
  98620. });
  98621. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  98622. _this._renderTime.endMonitoring(false);
  98623. BABYLON.Tools.EndPerformanceCounter("Main render");
  98624. });
  98625. }
  98626. else {
  98627. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  98628. this._onBeforeDrawPhaseObserver = null;
  98629. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  98630. this._onAfterDrawPhaseObserver = null;
  98631. }
  98632. },
  98633. enumerable: true,
  98634. configurable: true
  98635. });
  98636. Object.defineProperty(SceneInstrumentation.prototype, "cameraRenderTimeCounter", {
  98637. /**
  98638. * Gets the perf counter used for camera render time capture
  98639. */
  98640. get: function () {
  98641. return this._cameraRenderTime;
  98642. },
  98643. enumerable: true,
  98644. configurable: true
  98645. });
  98646. Object.defineProperty(SceneInstrumentation.prototype, "captureCameraRenderTime", {
  98647. /**
  98648. * Gets the camera render time capture status
  98649. */
  98650. get: function () {
  98651. return this._captureCameraRenderTime;
  98652. },
  98653. /**
  98654. * Enable or disable the camera render time capture
  98655. */
  98656. set: function (value) {
  98657. var _this = this;
  98658. if (value === this._captureCameraRenderTime) {
  98659. return;
  98660. }
  98661. this._captureCameraRenderTime = value;
  98662. if (value) {
  98663. this._onBeforeCameraRenderObserver = this.scene.onBeforeCameraRenderObservable.add(function (camera) {
  98664. _this._cameraRenderTime.beginMonitoring();
  98665. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + camera.name);
  98666. });
  98667. this._onAfterCameraRenderObserver = this.scene.onAfterCameraRenderObservable.add(function (camera) {
  98668. _this._cameraRenderTime.endMonitoring(false);
  98669. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + camera.name);
  98670. });
  98671. }
  98672. else {
  98673. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  98674. this._onBeforeCameraRenderObserver = null;
  98675. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  98676. this._onAfterCameraRenderObserver = null;
  98677. }
  98678. },
  98679. enumerable: true,
  98680. configurable: true
  98681. });
  98682. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  98683. /**
  98684. * Gets the perf counter used for draw calls
  98685. */
  98686. get: function () {
  98687. return this.scene.getEngine()._drawCalls;
  98688. },
  98689. enumerable: true,
  98690. configurable: true
  98691. });
  98692. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  98693. /**
  98694. * Gets the perf counter used for texture collisions
  98695. */
  98696. get: function () {
  98697. return this.scene.getEngine()._textureCollisions;
  98698. },
  98699. enumerable: true,
  98700. configurable: true
  98701. });
  98702. SceneInstrumentation.prototype.dispose = function () {
  98703. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  98704. this._onAfterRenderObserver = null;
  98705. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  98706. this._onBeforeActiveMeshesEvaluationObserver = null;
  98707. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  98708. this._onAfterActiveMeshesEvaluationObserver = null;
  98709. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  98710. this._onBeforeRenderTargetsRenderObserver = null;
  98711. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  98712. this._onAfterRenderTargetsRenderObserver = null;
  98713. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  98714. this._onBeforeAnimationsObserver = null;
  98715. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  98716. this._onBeforeParticlesRenderingObserver = null;
  98717. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  98718. this._onAfterParticlesRenderingObserver = null;
  98719. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  98720. this._onBeforeSpritesRenderingObserver = null;
  98721. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  98722. this._onAfterSpritesRenderingObserver = null;
  98723. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  98724. this._onBeforeDrawPhaseObserver = null;
  98725. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  98726. this._onAfterDrawPhaseObserver = null;
  98727. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  98728. this._onBeforePhysicsObserver = null;
  98729. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  98730. this._onAfterPhysicsObserver = null;
  98731. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  98732. this._onAfterAnimationsObserver = null;
  98733. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  98734. this._onBeforeCameraRenderObserver = null;
  98735. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  98736. this._onAfterCameraRenderObserver = null;
  98737. this.scene = null;
  98738. };
  98739. return SceneInstrumentation;
  98740. }());
  98741. BABYLON.SceneInstrumentation = SceneInstrumentation;
  98742. })(BABYLON || (BABYLON = {}));
  98743. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  98744. var BABYLON;
  98745. (function (BABYLON) {
  98746. /**
  98747. * @hidden
  98748. **/
  98749. var _TimeToken = /** @class */ (function () {
  98750. function _TimeToken() {
  98751. this._timeElapsedQueryEnded = false;
  98752. }
  98753. return _TimeToken;
  98754. }());
  98755. BABYLON._TimeToken = _TimeToken;
  98756. })(BABYLON || (BABYLON = {}));
  98757. //# sourceMappingURL=babylon.timeToken.js.map
  98758. var BABYLON;
  98759. (function (BABYLON) {
  98760. /**
  98761. * Background material defines definition.
  98762. * @hidden Mainly internal Use
  98763. */
  98764. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  98765. __extends(BackgroundMaterialDefines, _super);
  98766. /**
  98767. * Constructor of the defines.
  98768. */
  98769. function BackgroundMaterialDefines() {
  98770. var _this = _super.call(this) || this;
  98771. /**
  98772. * True if the diffuse texture is in use.
  98773. */
  98774. _this.DIFFUSE = false;
  98775. /**
  98776. * The direct UV channel to use.
  98777. */
  98778. _this.DIFFUSEDIRECTUV = 0;
  98779. /**
  98780. * True if the diffuse texture is in gamma space.
  98781. */
  98782. _this.GAMMADIFFUSE = false;
  98783. /**
  98784. * True if the diffuse texture has opacity in the alpha channel.
  98785. */
  98786. _this.DIFFUSEHASALPHA = false;
  98787. /**
  98788. * True if you want the material to fade to transparent at grazing angle.
  98789. */
  98790. _this.OPACITYFRESNEL = false;
  98791. /**
  98792. * True if an extra blur needs to be added in the reflection.
  98793. */
  98794. _this.REFLECTIONBLUR = false;
  98795. /**
  98796. * True if you want the material to fade to reflection at grazing angle.
  98797. */
  98798. _this.REFLECTIONFRESNEL = false;
  98799. /**
  98800. * True if you want the material to falloff as far as you move away from the scene center.
  98801. */
  98802. _this.REFLECTIONFALLOFF = false;
  98803. /**
  98804. * False if the current Webgl implementation does not support the texture lod extension.
  98805. */
  98806. _this.TEXTURELODSUPPORT = false;
  98807. /**
  98808. * True to ensure the data are premultiplied.
  98809. */
  98810. _this.PREMULTIPLYALPHA = false;
  98811. /**
  98812. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  98813. */
  98814. _this.USERGBCOLOR = false;
  98815. /**
  98816. * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
  98817. * stays aligned with the desired configuration.
  98818. */
  98819. _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
  98820. /**
  98821. * True to add noise in order to reduce the banding effect.
  98822. */
  98823. _this.NOISE = false;
  98824. /**
  98825. * is the reflection texture in BGR color scheme?
  98826. * Mainly used to solve a bug in ios10 video tag
  98827. */
  98828. _this.REFLECTIONBGR = false;
  98829. _this.IMAGEPROCESSING = false;
  98830. _this.VIGNETTE = false;
  98831. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  98832. _this.VIGNETTEBLENDMODEOPAQUE = false;
  98833. _this.TONEMAPPING = false;
  98834. _this.CONTRAST = false;
  98835. _this.COLORCURVES = false;
  98836. _this.COLORGRADING = false;
  98837. _this.COLORGRADING3D = false;
  98838. _this.SAMPLER3DGREENDEPTH = false;
  98839. _this.SAMPLER3DBGRMAP = false;
  98840. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  98841. _this.EXPOSURE = false;
  98842. // Reflection.
  98843. _this.REFLECTION = false;
  98844. _this.REFLECTIONMAP_3D = false;
  98845. _this.REFLECTIONMAP_SPHERICAL = false;
  98846. _this.REFLECTIONMAP_PLANAR = false;
  98847. _this.REFLECTIONMAP_CUBIC = false;
  98848. _this.REFLECTIONMAP_PROJECTION = false;
  98849. _this.REFLECTIONMAP_SKYBOX = false;
  98850. _this.REFLECTIONMAP_EXPLICIT = false;
  98851. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  98852. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  98853. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  98854. _this.INVERTCUBICMAP = false;
  98855. _this.REFLECTIONMAP_OPPOSITEZ = false;
  98856. _this.LODINREFLECTIONALPHA = false;
  98857. _this.GAMMAREFLECTION = false;
  98858. _this.RGBDREFLECTION = false;
  98859. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  98860. // Default BJS.
  98861. _this.MAINUV1 = false;
  98862. _this.MAINUV2 = false;
  98863. _this.UV1 = false;
  98864. _this.UV2 = false;
  98865. _this.CLIPPLANE = false;
  98866. _this.POINTSIZE = false;
  98867. _this.FOG = false;
  98868. _this.NORMAL = false;
  98869. _this.NUM_BONE_INFLUENCERS = 0;
  98870. _this.BonesPerMesh = 0;
  98871. _this.INSTANCES = false;
  98872. _this.SHADOWFLOAT = false;
  98873. _this.rebuild();
  98874. return _this;
  98875. }
  98876. return BackgroundMaterialDefines;
  98877. }(BABYLON.MaterialDefines));
  98878. /**
  98879. * Background material used to create an efficient environement around your scene.
  98880. */
  98881. var BackgroundMaterial = /** @class */ (function (_super) {
  98882. __extends(BackgroundMaterial, _super);
  98883. /**
  98884. * Instantiates a Background Material in the given scene
  98885. * @param name The friendly name of the material
  98886. * @param scene The scene to add the material to
  98887. */
  98888. function BackgroundMaterial(name, scene) {
  98889. var _this = _super.call(this, name, scene) || this;
  98890. /**
  98891. * Key light Color (multiply against the environement texture)
  98892. */
  98893. _this.primaryColor = BABYLON.Color3.White();
  98894. _this._primaryColorShadowLevel = 0;
  98895. _this._primaryColorHighlightLevel = 0;
  98896. /**
  98897. * Reflection Texture used in the material.
  98898. * Should be author in a specific way for the best result (refer to the documentation).
  98899. */
  98900. _this.reflectionTexture = null;
  98901. /**
  98902. * Reflection Texture level of blur.
  98903. *
  98904. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  98905. * texture twice.
  98906. */
  98907. _this.reflectionBlur = 0;
  98908. /**
  98909. * Diffuse Texture used in the material.
  98910. * Should be author in a specific way for the best result (refer to the documentation).
  98911. */
  98912. _this.diffuseTexture = null;
  98913. _this._shadowLights = null;
  98914. /**
  98915. * Specify the list of lights casting shadow on the material.
  98916. * All scene shadow lights will be included if null.
  98917. */
  98918. _this.shadowLights = null;
  98919. /**
  98920. * Helps adjusting the shadow to a softer level if required.
  98921. * 0 means black shadows and 1 means no shadows.
  98922. */
  98923. _this.shadowLevel = 0;
  98924. /**
  98925. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  98926. * It is usually zero but might be interesting to modify according to your setup.
  98927. */
  98928. _this.sceneCenter = BABYLON.Vector3.Zero();
  98929. /**
  98930. * This helps specifying that the material is falling off to the sky box at grazing angle.
  98931. * This helps ensuring a nice transition when the camera goes under the ground.
  98932. */
  98933. _this.opacityFresnel = true;
  98934. /**
  98935. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  98936. * This helps adding a mirror texture on the ground.
  98937. */
  98938. _this.reflectionFresnel = false;
  98939. /**
  98940. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  98941. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  98942. */
  98943. _this.reflectionFalloffDistance = 0.0;
  98944. /**
  98945. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  98946. */
  98947. _this.reflectionAmount = 1.0;
  98948. /**
  98949. * This specifies the weight of the reflection at grazing angle.
  98950. */
  98951. _this.reflectionReflectance0 = 0.05;
  98952. /**
  98953. * This specifies the weight of the reflection at a perpendicular point of view.
  98954. */
  98955. _this.reflectionReflectance90 = 0.5;
  98956. /**
  98957. * Helps to directly use the maps channels instead of their level.
  98958. */
  98959. _this.useRGBColor = true;
  98960. /**
  98961. * This helps reducing the banding effect that could occur on the background.
  98962. */
  98963. _this.enableNoise = false;
  98964. _this._fovMultiplier = 1.0;
  98965. /**
  98966. * Enable the FOV adjustment feature controlled by fovMultiplier.
  98967. */
  98968. _this.useEquirectangularFOV = false;
  98969. _this._maxSimultaneousLights = 4;
  98970. /**
  98971. * Number of Simultaneous lights allowed on the material.
  98972. */
  98973. _this.maxSimultaneousLights = 4;
  98974. /**
  98975. * Keep track of the image processing observer to allow dispose and replace.
  98976. */
  98977. _this._imageProcessingObserver = null;
  98978. /**
  98979. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  98980. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  98981. */
  98982. _this.switchToBGR = false;
  98983. // Temp values kept as cache in the material.
  98984. _this._renderTargets = new BABYLON.SmartArray(16);
  98985. _this._reflectionControls = BABYLON.Vector4.Zero();
  98986. _this._white = BABYLON.Color3.White();
  98987. _this._primaryShadowColor = BABYLON.Color3.Black();
  98988. _this._primaryHighlightColor = BABYLON.Color3.Black();
  98989. // Setup the default processing configuration to the scene.
  98990. _this._attachImageProcessingConfiguration(null);
  98991. _this.getRenderTargetTextures = function () {
  98992. _this._renderTargets.reset();
  98993. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  98994. _this._renderTargets.push(_this._diffuseTexture);
  98995. }
  98996. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  98997. _this._renderTargets.push(_this._reflectionTexture);
  98998. }
  98999. return _this._renderTargets;
  99000. };
  99001. return _this;
  99002. }
  99003. Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", {
  99004. /**
  99005. * Experimental Internal Use Only.
  99006. *
  99007. * Key light Color in "perceptual value" meaning the color you would like to see on screen.
  99008. * This acts as a helper to set the primary color to a more "human friendly" value.
  99009. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
  99010. * output color as close as possible from the chosen value.
  99011. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
  99012. * part of lighting setup.)
  99013. */
  99014. get: function () {
  99015. return this.__perceptualColor;
  99016. },
  99017. set: function (value) {
  99018. this.__perceptualColor = value;
  99019. this._computePrimaryColorFromPerceptualColor();
  99020. this._markAllSubMeshesAsLightsDirty();
  99021. },
  99022. enumerable: true,
  99023. configurable: true
  99024. });
  99025. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
  99026. /**
  99027. * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
  99028. * The color opposite to the primary color is used at the level chosen to define what the black area would look.
  99029. */
  99030. get: function () {
  99031. return this._primaryColorShadowLevel;
  99032. },
  99033. set: function (value) {
  99034. this._primaryColorShadowLevel = value;
  99035. this._computePrimaryColors();
  99036. this._markAllSubMeshesAsLightsDirty();
  99037. },
  99038. enumerable: true,
  99039. configurable: true
  99040. });
  99041. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
  99042. /**
  99043. * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
  99044. * The primary color is used at the level chosen to define what the white area would look.
  99045. */
  99046. get: function () {
  99047. return this._primaryColorHighlightLevel;
  99048. },
  99049. set: function (value) {
  99050. this._primaryColorHighlightLevel = value;
  99051. this._computePrimaryColors();
  99052. this._markAllSubMeshesAsLightsDirty();
  99053. },
  99054. enumerable: true,
  99055. configurable: true
  99056. });
  99057. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  99058. /**
  99059. * Sets the reflection reflectance fresnel values according to the default standard
  99060. * empirically know to work well :-)
  99061. */
  99062. set: function (value) {
  99063. var reflectionWeight = value;
  99064. if (reflectionWeight < 0.5) {
  99065. reflectionWeight = reflectionWeight * 2.0;
  99066. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  99067. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  99068. }
  99069. else {
  99070. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  99071. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  99072. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  99073. }
  99074. },
  99075. enumerable: true,
  99076. configurable: true
  99077. });
  99078. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  99079. /**
  99080. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  99081. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  99082. * Recommended to be keep at 1.0 except for special cases.
  99083. */
  99084. get: function () {
  99085. return this._fovMultiplier;
  99086. },
  99087. set: function (value) {
  99088. if (isNaN(value)) {
  99089. value = 1.0;
  99090. }
  99091. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  99092. },
  99093. enumerable: true,
  99094. configurable: true
  99095. });
  99096. /**
  99097. * Attaches a new image processing configuration to the PBR Material.
  99098. * @param configuration (if null the scene configuration will be use)
  99099. */
  99100. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  99101. var _this = this;
  99102. if (configuration === this._imageProcessingConfiguration) {
  99103. return;
  99104. }
  99105. // Detaches observer.
  99106. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  99107. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  99108. }
  99109. // Pick the scene configuration if needed.
  99110. if (!configuration) {
  99111. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  99112. }
  99113. else {
  99114. this._imageProcessingConfiguration = configuration;
  99115. }
  99116. // Attaches observer.
  99117. if (this._imageProcessingConfiguration) {
  99118. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  99119. _this._computePrimaryColorFromPerceptualColor();
  99120. _this._markAllSubMeshesAsImageProcessingDirty();
  99121. });
  99122. }
  99123. };
  99124. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  99125. /**
  99126. * Gets the image processing configuration used either in this material.
  99127. */
  99128. get: function () {
  99129. return this._imageProcessingConfiguration;
  99130. },
  99131. /**
  99132. * Sets the Default image processing configuration used either in the this material.
  99133. *
  99134. * If sets to null, the scene one is in use.
  99135. */
  99136. set: function (value) {
  99137. this._attachImageProcessingConfiguration(value);
  99138. // Ensure the effect will be rebuilt.
  99139. this._markAllSubMeshesAsTexturesDirty();
  99140. },
  99141. enumerable: true,
  99142. configurable: true
  99143. });
  99144. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  99145. /**
  99146. * Gets wether the color curves effect is enabled.
  99147. */
  99148. get: function () {
  99149. return this.imageProcessingConfiguration.colorCurvesEnabled;
  99150. },
  99151. /**
  99152. * Sets wether the color curves effect is enabled.
  99153. */
  99154. set: function (value) {
  99155. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  99156. },
  99157. enumerable: true,
  99158. configurable: true
  99159. });
  99160. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  99161. /**
  99162. * Gets wether the color grading effect is enabled.
  99163. */
  99164. get: function () {
  99165. return this.imageProcessingConfiguration.colorGradingEnabled;
  99166. },
  99167. /**
  99168. * Gets wether the color grading effect is enabled.
  99169. */
  99170. set: function (value) {
  99171. this.imageProcessingConfiguration.colorGradingEnabled = value;
  99172. },
  99173. enumerable: true,
  99174. configurable: true
  99175. });
  99176. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  99177. /**
  99178. * Gets wether tonemapping is enabled or not.
  99179. */
  99180. get: function () {
  99181. return this._imageProcessingConfiguration.toneMappingEnabled;
  99182. },
  99183. /**
  99184. * Sets wether tonemapping is enabled or not
  99185. */
  99186. set: function (value) {
  99187. this._imageProcessingConfiguration.toneMappingEnabled = value;
  99188. },
  99189. enumerable: true,
  99190. configurable: true
  99191. });
  99192. ;
  99193. ;
  99194. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  99195. /**
  99196. * The camera exposure used on this material.
  99197. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  99198. * This corresponds to a photographic exposure.
  99199. */
  99200. get: function () {
  99201. return this._imageProcessingConfiguration.exposure;
  99202. },
  99203. /**
  99204. * The camera exposure used on this material.
  99205. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  99206. * This corresponds to a photographic exposure.
  99207. */
  99208. set: function (value) {
  99209. this._imageProcessingConfiguration.exposure = value;
  99210. },
  99211. enumerable: true,
  99212. configurable: true
  99213. });
  99214. ;
  99215. ;
  99216. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  99217. /**
  99218. * Gets The camera contrast used on this material.
  99219. */
  99220. get: function () {
  99221. return this._imageProcessingConfiguration.contrast;
  99222. },
  99223. /**
  99224. * Sets The camera contrast used on this material.
  99225. */
  99226. set: function (value) {
  99227. this._imageProcessingConfiguration.contrast = value;
  99228. },
  99229. enumerable: true,
  99230. configurable: true
  99231. });
  99232. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  99233. /**
  99234. * Gets the Color Grading 2D Lookup Texture.
  99235. */
  99236. get: function () {
  99237. return this._imageProcessingConfiguration.colorGradingTexture;
  99238. },
  99239. /**
  99240. * Sets the Color Grading 2D Lookup Texture.
  99241. */
  99242. set: function (value) {
  99243. this.imageProcessingConfiguration.colorGradingTexture = value;
  99244. },
  99245. enumerable: true,
  99246. configurable: true
  99247. });
  99248. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  99249. /**
  99250. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  99251. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  99252. * 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;
  99253. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  99254. */
  99255. get: function () {
  99256. return this.imageProcessingConfiguration.colorCurves;
  99257. },
  99258. /**
  99259. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  99260. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  99261. * 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;
  99262. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  99263. */
  99264. set: function (value) {
  99265. this.imageProcessingConfiguration.colorCurves = value;
  99266. },
  99267. enumerable: true,
  99268. configurable: true
  99269. });
  99270. /**
  99271. * The entire material has been created in order to prevent overdraw.
  99272. * @returns false
  99273. */
  99274. BackgroundMaterial.prototype.needAlphaTesting = function () {
  99275. return true;
  99276. };
  99277. /**
  99278. * The entire material has been created in order to prevent overdraw.
  99279. * @returns true if blending is enable
  99280. */
  99281. BackgroundMaterial.prototype.needAlphaBlending = function () {
  99282. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  99283. };
  99284. /**
  99285. * Checks wether the material is ready to be rendered for a given mesh.
  99286. * @param mesh The mesh to render
  99287. * @param subMesh The submesh to check against
  99288. * @param useInstances Specify wether or not the material is used with instances
  99289. * @returns true if all the dependencies are ready (Textures, Effects...)
  99290. */
  99291. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  99292. var _this = this;
  99293. if (useInstances === void 0) { useInstances = false; }
  99294. if (subMesh.effect && this.isFrozen) {
  99295. if (this._wasPreviouslyReady) {
  99296. return true;
  99297. }
  99298. }
  99299. if (!subMesh._materialDefines) {
  99300. subMesh._materialDefines = new BackgroundMaterialDefines();
  99301. }
  99302. var scene = this.getScene();
  99303. var defines = subMesh._materialDefines;
  99304. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  99305. if (defines._renderId === scene.getRenderId()) {
  99306. return true;
  99307. }
  99308. }
  99309. var engine = scene.getEngine();
  99310. // Lights
  99311. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  99312. defines._needNormals = true;
  99313. // Textures
  99314. if (defines._areTexturesDirty) {
  99315. defines._needUVs = false;
  99316. if (scene.texturesEnabled) {
  99317. if (scene.getEngine().getCaps().textureLOD) {
  99318. defines.TEXTURELODSUPPORT = true;
  99319. }
  99320. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  99321. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  99322. return false;
  99323. }
  99324. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  99325. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  99326. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  99327. defines.OPACITYFRESNEL = this._opacityFresnel;
  99328. }
  99329. else {
  99330. defines.DIFFUSE = false;
  99331. defines.DIFFUSEHASALPHA = false;
  99332. defines.GAMMADIFFUSE = false;
  99333. defines.OPACITYFRESNEL = false;
  99334. }
  99335. var reflectionTexture = this._reflectionTexture;
  99336. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  99337. if (!reflectionTexture.isReadyOrNotBlocking()) {
  99338. return false;
  99339. }
  99340. defines.REFLECTION = true;
  99341. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  99342. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  99343. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  99344. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  99345. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  99346. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  99347. defines.REFLECTIONBGR = this.switchToBGR;
  99348. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  99349. defines.INVERTCUBICMAP = true;
  99350. }
  99351. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  99352. switch (reflectionTexture.coordinatesMode) {
  99353. case BABYLON.Texture.EXPLICIT_MODE:
  99354. defines.REFLECTIONMAP_EXPLICIT = true;
  99355. break;
  99356. case BABYLON.Texture.PLANAR_MODE:
  99357. defines.REFLECTIONMAP_PLANAR = true;
  99358. break;
  99359. case BABYLON.Texture.PROJECTION_MODE:
  99360. defines.REFLECTIONMAP_PROJECTION = true;
  99361. break;
  99362. case BABYLON.Texture.SKYBOX_MODE:
  99363. defines.REFLECTIONMAP_SKYBOX = true;
  99364. break;
  99365. case BABYLON.Texture.SPHERICAL_MODE:
  99366. defines.REFLECTIONMAP_SPHERICAL = true;
  99367. break;
  99368. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  99369. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  99370. break;
  99371. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  99372. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  99373. break;
  99374. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  99375. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  99376. break;
  99377. case BABYLON.Texture.CUBIC_MODE:
  99378. case BABYLON.Texture.INVCUBIC_MODE:
  99379. default:
  99380. defines.REFLECTIONMAP_CUBIC = true;
  99381. break;
  99382. }
  99383. if (this.reflectionFresnel) {
  99384. defines.REFLECTIONFRESNEL = true;
  99385. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  99386. this._reflectionControls.x = this.reflectionAmount;
  99387. this._reflectionControls.y = this.reflectionReflectance0;
  99388. this._reflectionControls.z = this.reflectionReflectance90;
  99389. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  99390. }
  99391. else {
  99392. defines.REFLECTIONFRESNEL = false;
  99393. defines.REFLECTIONFALLOFF = false;
  99394. }
  99395. }
  99396. else {
  99397. defines.REFLECTION = false;
  99398. defines.REFLECTIONFRESNEL = false;
  99399. defines.REFLECTIONFALLOFF = false;
  99400. defines.REFLECTIONBLUR = false;
  99401. defines.REFLECTIONMAP_3D = false;
  99402. defines.REFLECTIONMAP_SPHERICAL = false;
  99403. defines.REFLECTIONMAP_PLANAR = false;
  99404. defines.REFLECTIONMAP_CUBIC = false;
  99405. defines.REFLECTIONMAP_PROJECTION = false;
  99406. defines.REFLECTIONMAP_SKYBOX = false;
  99407. defines.REFLECTIONMAP_EXPLICIT = false;
  99408. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  99409. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  99410. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  99411. defines.INVERTCUBICMAP = false;
  99412. defines.REFLECTIONMAP_OPPOSITEZ = false;
  99413. defines.LODINREFLECTIONALPHA = false;
  99414. defines.GAMMAREFLECTION = false;
  99415. defines.RGBDREFLECTION = false;
  99416. }
  99417. }
  99418. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  99419. defines.USERGBCOLOR = this._useRGBColor;
  99420. defines.NOISE = this._enableNoise;
  99421. }
  99422. if (defines._areLightsDirty) {
  99423. defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
  99424. }
  99425. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  99426. if (!this._imageProcessingConfiguration.isReady()) {
  99427. return false;
  99428. }
  99429. this._imageProcessingConfiguration.prepareDefines(defines);
  99430. }
  99431. // Misc.
  99432. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  99433. // Values that need to be evaluated on every frame
  99434. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  99435. // Attribs
  99436. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  99437. if (mesh) {
  99438. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  99439. mesh.createNormals(true);
  99440. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  99441. }
  99442. }
  99443. }
  99444. // Get correct effect
  99445. if (defines.isDirty) {
  99446. defines.markAsProcessed();
  99447. scene.resetCachedMaterial();
  99448. // Fallbacks
  99449. var fallbacks = new BABYLON.EffectFallbacks();
  99450. if (defines.FOG) {
  99451. fallbacks.addFallback(0, "FOG");
  99452. }
  99453. if (defines.POINTSIZE) {
  99454. fallbacks.addFallback(1, "POINTSIZE");
  99455. }
  99456. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  99457. if (defines.NUM_BONE_INFLUENCERS > 0) {
  99458. fallbacks.addCPUSkinningFallback(0, mesh);
  99459. }
  99460. //Attributes
  99461. var attribs = [BABYLON.VertexBuffer.PositionKind];
  99462. if (defines.NORMAL) {
  99463. attribs.push(BABYLON.VertexBuffer.NormalKind);
  99464. }
  99465. if (defines.UV1) {
  99466. attribs.push(BABYLON.VertexBuffer.UVKind);
  99467. }
  99468. if (defines.UV2) {
  99469. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  99470. }
  99471. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  99472. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  99473. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  99474. "vFogInfos", "vFogColor", "pointSize",
  99475. "vClipPlane", "mBones",
  99476. "vPrimaryColor", "vPrimaryColorShadow",
  99477. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  99478. "shadowLevel", "alpha",
  99479. "vBackgroundCenter", "vReflectionControl",
  99480. "vDiffuseInfos", "diffuseMatrix",
  99481. ];
  99482. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  99483. var uniformBuffers = ["Material", "Scene"];
  99484. if (BABYLON.ImageProcessingConfiguration) {
  99485. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  99486. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  99487. }
  99488. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  99489. uniformsNames: uniforms,
  99490. uniformBuffersNames: uniformBuffers,
  99491. samplers: samplers,
  99492. defines: defines,
  99493. maxSimultaneousLights: this._maxSimultaneousLights
  99494. });
  99495. var onCompiled = function (effect) {
  99496. if (_this.onCompiled) {
  99497. _this.onCompiled(effect);
  99498. }
  99499. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  99500. };
  99501. var join = defines.toString();
  99502. subMesh.setEffect(scene.getEngine().createEffect("background", {
  99503. attributes: attribs,
  99504. uniformsNames: uniforms,
  99505. uniformBuffersNames: uniformBuffers,
  99506. samplers: samplers,
  99507. defines: join,
  99508. fallbacks: fallbacks,
  99509. onCompiled: onCompiled,
  99510. onError: this.onError,
  99511. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  99512. }, engine), defines);
  99513. this.buildUniformLayout();
  99514. }
  99515. if (!subMesh.effect || !subMesh.effect.isReady()) {
  99516. return false;
  99517. }
  99518. defines._renderId = scene.getRenderId();
  99519. this._wasPreviouslyReady = true;
  99520. return true;
  99521. };
  99522. /**
  99523. * Compute the primary color according to the chosen perceptual color.
  99524. */
  99525. BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
  99526. if (!this.__perceptualColor) {
  99527. return;
  99528. }
  99529. this._primaryColor.copyFrom(this.__perceptualColor);
  99530. // Revert gamma space.
  99531. this._primaryColor.toLinearSpaceToRef(this._primaryColor);
  99532. // Revert image processing configuration.
  99533. if (this._imageProcessingConfiguration) {
  99534. // Revert Exposure.
  99535. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
  99536. }
  99537. this._computePrimaryColors();
  99538. };
  99539. /**
  99540. * Compute the highlights and shadow colors according to their chosen levels.
  99541. */
  99542. BackgroundMaterial.prototype._computePrimaryColors = function () {
  99543. if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
  99544. return;
  99545. }
  99546. // Find the highlight color based on the configuration.
  99547. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
  99548. this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
  99549. // Find the shadow color based on the configuration.
  99550. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
  99551. this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
  99552. this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  99553. };
  99554. /**
  99555. * Build the uniform buffer used in the material.
  99556. */
  99557. BackgroundMaterial.prototype.buildUniformLayout = function () {
  99558. // Order is important !
  99559. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  99560. this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
  99561. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  99562. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  99563. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  99564. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  99565. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  99566. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  99567. this._uniformBuffer.addUniform("pointSize", 1);
  99568. this._uniformBuffer.addUniform("shadowLevel", 1);
  99569. this._uniformBuffer.addUniform("alpha", 1);
  99570. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  99571. this._uniformBuffer.addUniform("vReflectionControl", 4);
  99572. this._uniformBuffer.create();
  99573. };
  99574. /**
  99575. * Unbind the material.
  99576. */
  99577. BackgroundMaterial.prototype.unbind = function () {
  99578. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  99579. this._uniformBuffer.setTexture("diffuseSampler", null);
  99580. }
  99581. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  99582. this._uniformBuffer.setTexture("reflectionSampler", null);
  99583. }
  99584. _super.prototype.unbind.call(this);
  99585. };
  99586. /**
  99587. * Bind only the world matrix to the material.
  99588. * @param world The world matrix to bind.
  99589. */
  99590. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  99591. this._activeEffect.setMatrix("world", world);
  99592. };
  99593. /**
  99594. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  99595. * @param world The world matrix to bind.
  99596. * @param subMesh The submesh to bind for.
  99597. */
  99598. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  99599. var scene = this.getScene();
  99600. var defines = subMesh._materialDefines;
  99601. if (!defines) {
  99602. return;
  99603. }
  99604. var effect = subMesh.effect;
  99605. if (!effect) {
  99606. return;
  99607. }
  99608. this._activeEffect = effect;
  99609. // Matrices
  99610. this.bindOnlyWorldMatrix(world);
  99611. // Bones
  99612. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  99613. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  99614. if (mustRebind) {
  99615. this._uniformBuffer.bindToEffect(effect, "Material");
  99616. this.bindViewProjection(effect);
  99617. var reflectionTexture = this._reflectionTexture;
  99618. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  99619. // Texture uniforms
  99620. if (scene.texturesEnabled) {
  99621. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  99622. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  99623. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  99624. }
  99625. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  99626. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  99627. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  99628. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  99629. }
  99630. }
  99631. if (this.shadowLevel > 0) {
  99632. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  99633. }
  99634. this._uniformBuffer.updateFloat("alpha", this.alpha);
  99635. // Point size
  99636. if (this.pointsCloud) {
  99637. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  99638. }
  99639. if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
  99640. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
  99641. this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
  99642. }
  99643. else {
  99644. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
  99645. }
  99646. }
  99647. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  99648. // Textures
  99649. if (scene.texturesEnabled) {
  99650. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  99651. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  99652. }
  99653. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  99654. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  99655. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  99656. }
  99657. else if (!defines.REFLECTIONBLUR) {
  99658. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  99659. }
  99660. else {
  99661. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  99662. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  99663. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  99664. }
  99665. if (defines.REFLECTIONFRESNEL) {
  99666. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  99667. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  99668. }
  99669. }
  99670. }
  99671. // Clip plane
  99672. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  99673. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  99674. }
  99675. if (mustRebind || !this.isFrozen) {
  99676. if (scene.lightsEnabled) {
  99677. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  99678. }
  99679. // View
  99680. this.bindView(effect);
  99681. // Fog
  99682. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  99683. // image processing
  99684. if (this._imageProcessingConfiguration) {
  99685. this._imageProcessingConfiguration.bind(this._activeEffect);
  99686. }
  99687. }
  99688. this._uniformBuffer.update();
  99689. this._afterBind(mesh);
  99690. };
  99691. /**
  99692. * Dispose the material.
  99693. * @param forceDisposeEffect Force disposal of the associated effect.
  99694. * @param forceDisposeTextures Force disposal of the associated textures.
  99695. */
  99696. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  99697. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  99698. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  99699. if (forceDisposeTextures) {
  99700. if (this.diffuseTexture) {
  99701. this.diffuseTexture.dispose();
  99702. }
  99703. if (this.reflectionTexture) {
  99704. this.reflectionTexture.dispose();
  99705. }
  99706. }
  99707. this._renderTargets.dispose();
  99708. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  99709. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  99710. }
  99711. _super.prototype.dispose.call(this, forceDisposeEffect);
  99712. };
  99713. /**
  99714. * Clones the material.
  99715. * @param name The cloned name.
  99716. * @returns The cloned material.
  99717. */
  99718. BackgroundMaterial.prototype.clone = function (name) {
  99719. var _this = this;
  99720. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  99721. };
  99722. /**
  99723. * Serializes the current material to its JSON representation.
  99724. * @returns The JSON representation.
  99725. */
  99726. BackgroundMaterial.prototype.serialize = function () {
  99727. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  99728. serializationObject.customType = "BABYLON.BackgroundMaterial";
  99729. return serializationObject;
  99730. };
  99731. /**
  99732. * Gets the class name of the material
  99733. * @returns "BackgroundMaterial"
  99734. */
  99735. BackgroundMaterial.prototype.getClassName = function () {
  99736. return "BackgroundMaterial";
  99737. };
  99738. /**
  99739. * Parse a JSON input to create back a background material.
  99740. * @param source The JSON data to parse
  99741. * @param scene The scene to create the parsed material in
  99742. * @param rootUrl The root url of the assets the material depends upon
  99743. * @returns the instantiated BackgroundMaterial.
  99744. */
  99745. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  99746. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  99747. };
  99748. /**
  99749. * Standard reflectance value at parallel view angle.
  99750. */
  99751. BackgroundMaterial.StandardReflectance0 = 0.05;
  99752. /**
  99753. * Standard reflectance value at grazing angle.
  99754. */
  99755. BackgroundMaterial.StandardReflectance90 = 0.5;
  99756. __decorate([
  99757. BABYLON.serializeAsColor3()
  99758. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  99759. __decorate([
  99760. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  99761. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  99762. __decorate([
  99763. BABYLON.serializeAsColor3()
  99764. ], BackgroundMaterial.prototype, "__perceptualColor", void 0);
  99765. __decorate([
  99766. BABYLON.serialize()
  99767. ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
  99768. __decorate([
  99769. BABYLON.serialize()
  99770. ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
  99771. __decorate([
  99772. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  99773. ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
  99774. __decorate([
  99775. BABYLON.serializeAsTexture()
  99776. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  99777. __decorate([
  99778. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99779. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  99780. __decorate([
  99781. BABYLON.serialize()
  99782. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  99783. __decorate([
  99784. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99785. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  99786. __decorate([
  99787. BABYLON.serializeAsTexture()
  99788. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  99789. __decorate([
  99790. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99791. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  99792. __decorate([
  99793. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99794. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  99795. __decorate([
  99796. BABYLON.serialize()
  99797. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  99798. __decorate([
  99799. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99800. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  99801. __decorate([
  99802. BABYLON.serializeAsVector3()
  99803. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  99804. __decorate([
  99805. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99806. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  99807. __decorate([
  99808. BABYLON.serialize()
  99809. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  99810. __decorate([
  99811. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99812. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  99813. __decorate([
  99814. BABYLON.serialize()
  99815. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  99816. __decorate([
  99817. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99818. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  99819. __decorate([
  99820. BABYLON.serialize()
  99821. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  99822. __decorate([
  99823. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99824. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  99825. __decorate([
  99826. BABYLON.serialize()
  99827. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  99828. __decorate([
  99829. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99830. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  99831. __decorate([
  99832. BABYLON.serialize()
  99833. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  99834. __decorate([
  99835. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99836. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  99837. __decorate([
  99838. BABYLON.serialize()
  99839. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  99840. __decorate([
  99841. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99842. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  99843. __decorate([
  99844. BABYLON.serialize()
  99845. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  99846. __decorate([
  99847. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99848. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  99849. __decorate([
  99850. BABYLON.serialize()
  99851. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  99852. __decorate([
  99853. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99854. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  99855. __decorate([
  99856. BABYLON.serialize()
  99857. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  99858. __decorate([
  99859. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99860. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  99861. __decorate([
  99862. BABYLON.serializeAsImageProcessingConfiguration()
  99863. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  99864. return BackgroundMaterial;
  99865. }(BABYLON.PushMaterial));
  99866. BABYLON.BackgroundMaterial = BackgroundMaterial;
  99867. })(BABYLON || (BABYLON = {}));
  99868. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  99869. var __assign = (this && this.__assign) || Object.assign || function(t) {
  99870. for (var s, i = 1, n = arguments.length; i < n; i++) {
  99871. s = arguments[i];
  99872. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  99873. t[p] = s[p];
  99874. }
  99875. return t;
  99876. };
  99877. var BABYLON;
  99878. (function (BABYLON) {
  99879. /**
  99880. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  99881. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  99882. * It also helps with the default setup of your imageProcessing configuration.
  99883. */
  99884. var EnvironmentHelper = /** @class */ (function () {
  99885. /**
  99886. * constructor
  99887. * @param options
  99888. * @param scene The scene to add the material to
  99889. */
  99890. function EnvironmentHelper(options, scene) {
  99891. var _this = this;
  99892. this._errorHandler = function (message, exception) {
  99893. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  99894. };
  99895. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  99896. this._scene = scene;
  99897. this.onErrorObservable = new BABYLON.Observable();
  99898. this._setupBackground();
  99899. this._setupImageProcessing();
  99900. }
  99901. /**
  99902. * Creates the default options for the helper.
  99903. */
  99904. EnvironmentHelper._getDefaultOptions = function () {
  99905. return {
  99906. createGround: true,
  99907. groundSize: 15,
  99908. groundTexture: this._groundTextureCDNUrl,
  99909. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  99910. groundOpacity: 0.9,
  99911. enableGroundShadow: true,
  99912. groundShadowLevel: 0.5,
  99913. enableGroundMirror: false,
  99914. groundMirrorSizeRatio: 0.3,
  99915. groundMirrorBlurKernel: 64,
  99916. groundMirrorAmount: 1,
  99917. groundMirrorFresnelWeight: 1,
  99918. groundMirrorFallOffDistance: 0,
  99919. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  99920. groundYBias: 0.00001,
  99921. createSkybox: true,
  99922. skyboxSize: 20,
  99923. skyboxTexture: this._skyboxTextureCDNUrl,
  99924. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  99925. backgroundYRotation: 0,
  99926. sizeAuto: true,
  99927. rootPosition: BABYLON.Vector3.Zero(),
  99928. setupImageProcessing: true,
  99929. environmentTexture: this._environmentTextureCDNUrl,
  99930. cameraExposure: 0.8,
  99931. cameraContrast: 1.2,
  99932. toneMappingEnabled: true,
  99933. };
  99934. };
  99935. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  99936. /**
  99937. * Gets the root mesh created by the helper.
  99938. */
  99939. get: function () {
  99940. return this._rootMesh;
  99941. },
  99942. enumerable: true,
  99943. configurable: true
  99944. });
  99945. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  99946. /**
  99947. * Gets the skybox created by the helper.
  99948. */
  99949. get: function () {
  99950. return this._skybox;
  99951. },
  99952. enumerable: true,
  99953. configurable: true
  99954. });
  99955. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  99956. /**
  99957. * Gets the skybox texture created by the helper.
  99958. */
  99959. get: function () {
  99960. return this._skyboxTexture;
  99961. },
  99962. enumerable: true,
  99963. configurable: true
  99964. });
  99965. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  99966. /**
  99967. * Gets the skybox material created by the helper.
  99968. */
  99969. get: function () {
  99970. return this._skyboxMaterial;
  99971. },
  99972. enumerable: true,
  99973. configurable: true
  99974. });
  99975. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  99976. /**
  99977. * Gets the ground mesh created by the helper.
  99978. */
  99979. get: function () {
  99980. return this._ground;
  99981. },
  99982. enumerable: true,
  99983. configurable: true
  99984. });
  99985. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  99986. /**
  99987. * Gets the ground texture created by the helper.
  99988. */
  99989. get: function () {
  99990. return this._groundTexture;
  99991. },
  99992. enumerable: true,
  99993. configurable: true
  99994. });
  99995. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  99996. /**
  99997. * Gets the ground mirror created by the helper.
  99998. */
  99999. get: function () {
  100000. return this._groundMirror;
  100001. },
  100002. enumerable: true,
  100003. configurable: true
  100004. });
  100005. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  100006. /**
  100007. * Gets the ground mirror render list to helps pushing the meshes
  100008. * you wish in the ground reflection.
  100009. */
  100010. get: function () {
  100011. if (this._groundMirror) {
  100012. return this._groundMirror.renderList;
  100013. }
  100014. return null;
  100015. },
  100016. enumerable: true,
  100017. configurable: true
  100018. });
  100019. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  100020. /**
  100021. * Gets the ground material created by the helper.
  100022. */
  100023. get: function () {
  100024. return this._groundMaterial;
  100025. },
  100026. enumerable: true,
  100027. configurable: true
  100028. });
  100029. /**
  100030. * Updates the background according to the new options
  100031. * @param options
  100032. */
  100033. EnvironmentHelper.prototype.updateOptions = function (options) {
  100034. var newOptions = __assign({}, this._options, options);
  100035. if (this._ground && !newOptions.createGround) {
  100036. this._ground.dispose();
  100037. this._ground = null;
  100038. }
  100039. if (this._groundMaterial && !newOptions.createGround) {
  100040. this._groundMaterial.dispose();
  100041. this._groundMaterial = null;
  100042. }
  100043. if (this._groundTexture) {
  100044. if (this._options.groundTexture != newOptions.groundTexture) {
  100045. this._groundTexture.dispose();
  100046. this._groundTexture = null;
  100047. }
  100048. }
  100049. if (this._skybox && !newOptions.createSkybox) {
  100050. this._skybox.dispose();
  100051. this._skybox = null;
  100052. }
  100053. if (this._skyboxMaterial && !newOptions.createSkybox) {
  100054. this._skyboxMaterial.dispose();
  100055. this._skyboxMaterial = null;
  100056. }
  100057. if (this._skyboxTexture) {
  100058. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  100059. this._skyboxTexture.dispose();
  100060. this._skyboxTexture = null;
  100061. }
  100062. }
  100063. if (this._groundMirror && !newOptions.enableGroundMirror) {
  100064. this._groundMirror.dispose();
  100065. this._groundMirror = null;
  100066. }
  100067. if (this._scene.environmentTexture) {
  100068. if (this._options.environmentTexture != newOptions.environmentTexture) {
  100069. this._scene.environmentTexture.dispose();
  100070. }
  100071. }
  100072. this._options = newOptions;
  100073. this._setupBackground();
  100074. this._setupImageProcessing();
  100075. };
  100076. /**
  100077. * Sets the primary color of all the available elements.
  100078. * @param color the main color to affect to the ground and the background
  100079. */
  100080. EnvironmentHelper.prototype.setMainColor = function (color) {
  100081. if (this.groundMaterial) {
  100082. this.groundMaterial.primaryColor = color;
  100083. }
  100084. if (this.skyboxMaterial) {
  100085. this.skyboxMaterial.primaryColor = color;
  100086. }
  100087. if (this.groundMirror) {
  100088. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  100089. }
  100090. };
  100091. /**
  100092. * Setup the image processing according to the specified options.
  100093. */
  100094. EnvironmentHelper.prototype._setupImageProcessing = function () {
  100095. if (this._options.setupImageProcessing) {
  100096. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  100097. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  100098. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  100099. this._setupEnvironmentTexture();
  100100. }
  100101. };
  100102. /**
  100103. * Setup the environment texture according to the specified options.
  100104. */
  100105. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  100106. if (this._scene.environmentTexture) {
  100107. return;
  100108. }
  100109. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  100110. this._scene.environmentTexture = this._options.environmentTexture;
  100111. return;
  100112. }
  100113. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  100114. this._scene.environmentTexture = environmentTexture;
  100115. };
  100116. /**
  100117. * Setup the background according to the specified options.
  100118. */
  100119. EnvironmentHelper.prototype._setupBackground = function () {
  100120. if (!this._rootMesh) {
  100121. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  100122. }
  100123. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  100124. var sceneSize = this._getSceneSize();
  100125. if (this._options.createGround) {
  100126. this._setupGround(sceneSize);
  100127. this._setupGroundMaterial();
  100128. this._setupGroundDiffuseTexture();
  100129. if (this._options.enableGroundMirror) {
  100130. this._setupGroundMirrorTexture(sceneSize);
  100131. }
  100132. this._setupMirrorInGroundMaterial();
  100133. }
  100134. if (this._options.createSkybox) {
  100135. this._setupSkybox(sceneSize);
  100136. this._setupSkyboxMaterial();
  100137. this._setupSkyboxReflectionTexture();
  100138. }
  100139. this._rootMesh.position.x = sceneSize.rootPosition.x;
  100140. this._rootMesh.position.z = sceneSize.rootPosition.z;
  100141. this._rootMesh.position.y = sceneSize.rootPosition.y;
  100142. };
  100143. /**
  100144. * Get the scene sizes according to the setup.
  100145. */
  100146. EnvironmentHelper.prototype._getSceneSize = function () {
  100147. var _this = this;
  100148. var groundSize = this._options.groundSize;
  100149. var skyboxSize = this._options.skyboxSize;
  100150. var rootPosition = this._options.rootPosition;
  100151. if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
  100152. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  100153. }
  100154. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  100155. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  100156. });
  100157. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  100158. if (this._options.sizeAuto) {
  100159. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  100160. this._scene.activeCamera.upperRadiusLimit) {
  100161. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  100162. skyboxSize = groundSize;
  100163. }
  100164. var sceneDiagonalLenght = sceneDiagonal.length();
  100165. if (sceneDiagonalLenght > groundSize) {
  100166. groundSize = sceneDiagonalLenght * 2;
  100167. skyboxSize = groundSize;
  100168. }
  100169. // 10 % bigger.
  100170. groundSize *= 1.1;
  100171. skyboxSize *= 1.5;
  100172. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  100173. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  100174. }
  100175. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  100176. };
  100177. /**
  100178. * Setup the ground according to the specified options.
  100179. */
  100180. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  100181. var _this = this;
  100182. if (!this._ground) {
  100183. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  100184. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  100185. this._ground.parent = this._rootMesh;
  100186. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  100187. }
  100188. this._ground.receiveShadows = this._options.enableGroundShadow;
  100189. };
  100190. /**
  100191. * Setup the ground material according to the specified options.
  100192. */
  100193. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  100194. if (!this._groundMaterial) {
  100195. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  100196. }
  100197. this._groundMaterial.alpha = this._options.groundOpacity;
  100198. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  100199. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  100200. this._groundMaterial.primaryColor = this._options.groundColor;
  100201. this._groundMaterial.useRGBColor = false;
  100202. this._groundMaterial.enableNoise = true;
  100203. if (this._ground) {
  100204. this._ground.material = this._groundMaterial;
  100205. }
  100206. };
  100207. /**
  100208. * Setup the ground diffuse texture according to the specified options.
  100209. */
  100210. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  100211. if (!this._groundMaterial) {
  100212. return;
  100213. }
  100214. if (this._groundTexture) {
  100215. return;
  100216. }
  100217. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  100218. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  100219. return;
  100220. }
  100221. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  100222. diffuseTexture.gammaSpace = false;
  100223. diffuseTexture.hasAlpha = true;
  100224. this._groundMaterial.diffuseTexture = diffuseTexture;
  100225. };
  100226. /**
  100227. * Setup the ground mirror texture according to the specified options.
  100228. */
  100229. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  100230. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  100231. if (!this._groundMirror) {
  100232. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  100233. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  100234. this._groundMirror.anisotropicFilteringLevel = 1;
  100235. this._groundMirror.wrapU = wrapping;
  100236. this._groundMirror.wrapV = wrapping;
  100237. this._groundMirror.gammaSpace = false;
  100238. if (this._groundMirror.renderList) {
  100239. for (var i = 0; i < this._scene.meshes.length; i++) {
  100240. var mesh = this._scene.meshes[i];
  100241. if (mesh !== this._ground &&
  100242. mesh !== this._skybox &&
  100243. mesh !== this._rootMesh) {
  100244. this._groundMirror.renderList.push(mesh);
  100245. }
  100246. }
  100247. }
  100248. }
  100249. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  100250. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  100251. };
  100252. /**
  100253. * Setup the ground to receive the mirror texture.
  100254. */
  100255. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  100256. if (this._groundMaterial) {
  100257. this._groundMaterial.reflectionTexture = this._groundMirror;
  100258. this._groundMaterial.reflectionFresnel = true;
  100259. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  100260. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  100261. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  100262. }
  100263. };
  100264. /**
  100265. * Setup the skybox according to the specified options.
  100266. */
  100267. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  100268. var _this = this;
  100269. if (!this._skybox) {
  100270. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  100271. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  100272. }
  100273. this._skybox.parent = this._rootMesh;
  100274. };
  100275. /**
  100276. * Setup the skybox material according to the specified options.
  100277. */
  100278. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  100279. if (!this._skybox) {
  100280. return;
  100281. }
  100282. if (!this._skyboxMaterial) {
  100283. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  100284. }
  100285. this._skyboxMaterial.useRGBColor = false;
  100286. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  100287. this._skyboxMaterial.enableNoise = true;
  100288. this._skybox.material = this._skyboxMaterial;
  100289. };
  100290. /**
  100291. * Setup the skybox reflection texture according to the specified options.
  100292. */
  100293. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  100294. if (!this._skyboxMaterial) {
  100295. return;
  100296. }
  100297. if (this._skyboxTexture) {
  100298. return;
  100299. }
  100300. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  100301. this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
  100302. return;
  100303. }
  100304. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  100305. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  100306. this._skyboxTexture.gammaSpace = false;
  100307. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  100308. };
  100309. /**
  100310. * Dispose all the elements created by the Helper.
  100311. */
  100312. EnvironmentHelper.prototype.dispose = function () {
  100313. if (this._groundMaterial) {
  100314. this._groundMaterial.dispose(true, true);
  100315. }
  100316. if (this._skyboxMaterial) {
  100317. this._skyboxMaterial.dispose(true, true);
  100318. }
  100319. this._rootMesh.dispose(false);
  100320. };
  100321. /**
  100322. * Default ground texture URL.
  100323. */
  100324. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  100325. /**
  100326. * Default skybox texture URL.
  100327. */
  100328. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  100329. /**
  100330. * Default environment texture URL.
  100331. */
  100332. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.env";
  100333. return EnvironmentHelper;
  100334. }());
  100335. BABYLON.EnvironmentHelper = EnvironmentHelper;
  100336. })(BABYLON || (BABYLON = {}));
  100337. //# sourceMappingURL=babylon.environmentHelper.js.map
  100338. var BABYLON;
  100339. (function (BABYLON) {
  100340. /**
  100341. * This class is made for on one-liner static method to help creating particle systems.
  100342. */
  100343. var ParticleHelper = /** @class */ (function () {
  100344. function ParticleHelper() {
  100345. }
  100346. /**
  100347. * This is the main static method (one-liner) of this helper to create different particle systems.
  100348. * @param type This string represents the type to the particle system to create
  100349. * @param emitter The object where the particle system will start to emit from.
  100350. * @param scene The scene where the particle system should live.
  100351. * @param gpu If the system will use gpu.
  100352. * @returns the ParticleSystem created.
  100353. */
  100354. ParticleHelper.CreateAsync = function (type, emitter, scene, gpu) {
  100355. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  100356. if (gpu === void 0) { gpu = false; }
  100357. return new Promise(function (resolve, reject) {
  100358. if (!scene) {
  100359. scene = BABYLON.Engine.LastCreatedScene;
  100360. ;
  100361. }
  100362. if (gpu && !BABYLON.GPUParticleSystem.IsSupported) {
  100363. return reject("Particle system with GPU is not supported.");
  100364. }
  100365. BABYLON.Tools.LoadFile(ParticleHelper._baseAssetsUrl + "/systems/" + type + ".json", function (data, response) {
  100366. var newData = JSON.parse(data.toString());
  100367. return resolve(ParticleHelper.CreateSystem(newData, scene, emitter));
  100368. }, undefined, undefined, undefined, function (req, exception) {
  100369. return reject("An error occured while the creation of your particle system. Check if your type '" + type + "' exists.");
  100370. });
  100371. });
  100372. };
  100373. /**
  100374. * Static function used to create a new particle system from a IParticleSystemData
  100375. * @param data defines the source data
  100376. * @param scene defines the hosting scene
  100377. * @param emitter defines the particle emitter
  100378. * @returns a new ParticleSystem based on referenced data
  100379. */
  100380. ParticleHelper.CreateSystem = function (data, scene, emitter) {
  100381. // Create a particle system
  100382. var system = new BABYLON.ParticleSystem(data.type, data.capacity, scene);
  100383. // Where the particles come from
  100384. system.emitter = emitter; // the starting object, the emitter
  100385. ParticleHelper.UpdateSystem(system, data, scene);
  100386. return system;
  100387. };
  100388. /**
  100389. * Static function used to update a particle system from a IParticleSystemData
  100390. * @param system defines the particle system to update
  100391. * @param data defines the source data
  100392. * @param scene defines the hosting scene
  100393. */
  100394. ParticleHelper.UpdateSystem = function (system, data, scene) {
  100395. // Texture of each particle
  100396. if (data.textureFile) {
  100397. system.particleTexture = new BABYLON.Texture(ParticleHelper._baseAssetsUrl + "/textures/" + data.textureFile, scene);
  100398. }
  100399. // Colors of all particles
  100400. system.color1 = new BABYLON.Color4(data.color1.r, data.color1.g, data.color1.b, data.color1.a);
  100401. system.color2 = new BABYLON.Color4(data.color2.r, data.color2.g, data.color2.b, data.color2.a);
  100402. system.colorDead = new BABYLON.Color4(data.colorDead.r, data.colorDead.g, data.colorDead.b, data.colorDead.a);
  100403. // Size of each particle (random between...
  100404. system.minSize = data.minSize;
  100405. system.maxSize = data.maxSize;
  100406. system.minScaleX = data.minScaleX;
  100407. system.maxScaleX = data.maxScaleX;
  100408. system.minScaleY = data.minScaleY;
  100409. system.maxScaleY = data.maxScaleY;
  100410. // Life time of each particle (random between...
  100411. system.minLifeTime = data.minLifeTime;
  100412. system.maxLifeTime = data.maxLifeTime;
  100413. // Emission rate
  100414. system.emitRate = data.emitRate;
  100415. // Blend mode : BLENDMODE_ONEONE, or BLENDMODE_STANDARD
  100416. system.blendMode = data.blendMode;
  100417. // Set the gravity of all particles
  100418. system.gravity = new BABYLON.Vector3(data.gravity.x, data.gravity.y, data.gravity.z);
  100419. // Angular speed, in radians
  100420. system.minAngularSpeed = data.minAngularSpeed;
  100421. system.maxAngularSpeed = data.maxAngularSpeed;
  100422. // Speed
  100423. system.minEmitPower = data.minEmitPower;
  100424. system.maxEmitPower = data.maxEmitPower;
  100425. system.updateSpeed = data.updateSpeed;
  100426. switch (data.emitterType) {
  100427. case "box":
  100428. if (!data.direction1 || !data.direction2) {
  100429. throw new Error("Directions are missing in this particle system.");
  100430. }
  100431. if (!data.minEmitBox || !data.maxEmitBox) {
  100432. throw new Error("EmitBox is missing in this particle system.");
  100433. }
  100434. 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));
  100435. break;
  100436. case "sphere":
  100437. system.createSphereEmitter(data.radius);
  100438. break;
  100439. case "directed_sphere":
  100440. if (!data.direction1 || !data.direction2) {
  100441. throw new Error("Directions are missing in this particle system.");
  100442. }
  100443. 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));
  100444. break;
  100445. case "cone":
  100446. system.createConeEmitter(data.radius, data.angle);
  100447. break;
  100448. default:
  100449. break;
  100450. }
  100451. };
  100452. /**
  100453. * Static function used to export a particle system to a IParticleSystemData variable.
  100454. * Please note that texture file name is not exported and must be added manually
  100455. * @param system defines the particle system to export
  100456. */
  100457. ParticleHelper.ExportSystem = function (system) {
  100458. var outData = {};
  100459. // Colors of all particles
  100460. outData.color1 = { r: system.color1.r, g: system.color1.g, b: system.color1.b, a: system.color1.a };
  100461. outData.color2 = { r: system.color2.r, g: system.color2.g, b: system.color2.b, a: system.color2.a };
  100462. outData.colorDead = { r: system.colorDead.r, g: system.colorDead.g, b: system.colorDead.b, a: system.colorDead.a };
  100463. // Size of each particle (random between...
  100464. outData.minSize = system.minSize;
  100465. outData.maxSize = system.maxSize;
  100466. outData.minScaleX = system.minScaleX;
  100467. outData.maxScaleX = system.maxScaleX;
  100468. outData.minScaleY = system.minScaleY;
  100469. outData.maxScaleY = system.maxScaleY;
  100470. // Life time of each particle (random between...
  100471. outData.minLifeTime = system.minLifeTime;
  100472. outData.maxLifeTime = system.maxLifeTime;
  100473. // Emission rate
  100474. outData.emitRate = system.emitRate;
  100475. // Blend mode : BLENDMODE_ONEONE, or BLENDMODE_STANDARD
  100476. outData.blendMode = system.blendMode;
  100477. // Set the gravity of all particles
  100478. outData.gravity = { x: system.gravity.x, y: system.gravity.y, z: system.gravity.z };
  100479. // Angular speed, in radians
  100480. outData.minAngularSpeed = system.minAngularSpeed;
  100481. outData.maxAngularSpeed = system.maxAngularSpeed;
  100482. // Speed
  100483. outData.minEmitPower = system.minEmitPower;
  100484. outData.maxEmitPower = system.maxEmitPower;
  100485. outData.updateSpeed = system.updateSpeed;
  100486. switch (system.particleEmitterType.getClassName()) {
  100487. case "BoxEmitter":
  100488. outData.emitterType = "box";
  100489. outData.direction1 = { x: system.direction1.x, y: system.direction1.y, z: system.direction1.z };
  100490. outData.direction2 = { x: system.direction2.x, y: system.direction2.y, z: system.direction2.z };
  100491. outData.minEmitBox = { x: system.minEmitBox.x, y: system.minEmitBox.y, z: system.minEmitBox.z };
  100492. outData.maxEmitBox = { x: system.maxEmitBox.x, y: system.maxEmitBox.y, z: system.maxEmitBox.z };
  100493. break;
  100494. case "SphereParticleEmitter":
  100495. outData.emitterType = "sphere";
  100496. outData.radius = system.particleEmitterType.radius;
  100497. break;
  100498. case "SphereDirectedParticleEmitter":
  100499. outData.emitterType = "directed_sphere";
  100500. var sphereDirectedParticleEmitter = system.particleEmitterType;
  100501. outData.radius = sphereDirectedParticleEmitter.radius;
  100502. outData.direction1 = { x: sphereDirectedParticleEmitter.direction1.x, y: sphereDirectedParticleEmitter.direction1.y, z: sphereDirectedParticleEmitter.direction1.z };
  100503. outData.direction2 = { x: sphereDirectedParticleEmitter.direction2.x, y: sphereDirectedParticleEmitter.direction2.y, z: sphereDirectedParticleEmitter.direction2.z };
  100504. break;
  100505. case "ConeEmitter":
  100506. outData.emitterType = "cone";
  100507. outData.radius = system.particleEmitterType.radius;
  100508. outData.angle = system.particleEmitterType.angle;
  100509. break;
  100510. default:
  100511. break;
  100512. }
  100513. return outData;
  100514. };
  100515. /**
  100516. * Base Assets URL.
  100517. */
  100518. ParticleHelper._baseAssetsUrl = "https://assets.babylonjs.com/particles";
  100519. return ParticleHelper;
  100520. }());
  100521. BABYLON.ParticleHelper = ParticleHelper;
  100522. })(BABYLON || (BABYLON = {}));
  100523. //# sourceMappingURL=babylon.particleHelper.js.map
  100524. var BABYLON;
  100525. (function (BABYLON) {
  100526. /**
  100527. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  100528. * As a subclass of Node, this allow parenting to the camera or multiple videos with different locations in the scene.
  100529. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  100530. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  100531. */
  100532. var VideoDome = /** @class */ (function (_super) {
  100533. __extends(VideoDome, _super);
  100534. /**
  100535. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  100536. * @param name Element's name, child elements will append suffixes for their own names.
  100537. * @param urlsOrVideo defines the url(s) or the video element to use
  100538. * @param options An object containing optional or exposed sub element properties
  100539. */
  100540. function VideoDome(name, urlsOrVideo, options, scene) {
  100541. var _this = _super.call(this, name, scene) || this;
  100542. // set defaults and manage values
  100543. name = name || "videoDome";
  100544. options.resolution = (Math.abs(options.resolution) | 0) || 12;
  100545. options.clickToPlay = Boolean(options.clickToPlay);
  100546. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  100547. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  100548. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  100549. // create
  100550. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true };
  100551. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  100552. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  100553. _this._mesh = BABYLON.MeshBuilder.CreateIcoSphere(name + "_mesh", {
  100554. flat: false,
  100555. radius: options.size,
  100556. subdivisions: options.resolution,
  100557. sideOrientation: BABYLON.Mesh.BACKSIDE // needs to be inside out
  100558. }, scene);
  100559. // configure material
  100560. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  100561. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE; // always clamp the up/down
  100562. material.reflectionTexture = _this._videoTexture;
  100563. material.useEquirectangularFOV = true;
  100564. material.fovMultiplier = 1.0;
  100565. // configure mesh
  100566. _this._mesh.material = material;
  100567. _this._mesh.parent = _this;
  100568. // optional configuration
  100569. if (options.clickToPlay) {
  100570. scene.onPointerUp = function () {
  100571. _this._videoTexture.video.play();
  100572. };
  100573. }
  100574. return _this;
  100575. }
  100576. Object.defineProperty(VideoDome.prototype, "videoTexture", {
  100577. /**
  100578. * Gets the video texture being displayed on the sphere
  100579. */
  100580. get: function () {
  100581. return this._videoTexture;
  100582. },
  100583. enumerable: true,
  100584. configurable: true
  100585. });
  100586. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  100587. /**
  100588. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  100589. * Also see the options.resolution property.
  100590. */
  100591. get: function () {
  100592. return this._material.fovMultiplier;
  100593. },
  100594. set: function (value) {
  100595. this._material.fovMultiplier = value;
  100596. },
  100597. enumerable: true,
  100598. configurable: true
  100599. });
  100600. /**
  100601. * Releases resources associated with this node.
  100602. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  100603. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  100604. */
  100605. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  100606. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  100607. this._videoTexture.dispose();
  100608. this._mesh.dispose();
  100609. this._material.dispose();
  100610. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  100611. };
  100612. return VideoDome;
  100613. }(BABYLON.Node));
  100614. BABYLON.VideoDome = VideoDome;
  100615. })(BABYLON || (BABYLON = {}));
  100616. //# sourceMappingURL=babylon.videoDome.js.map
  100617. var BABYLON;
  100618. (function (BABYLON) {
  100619. /**
  100620. * Display a 360 degree photo on an approximately spherical surface, useful for VR applications or skyboxes.
  100621. * As a subclass of Node, this allow parenting to the camera with different locations in the scene.
  100622. * This class achieves its effect with a Texture and a correctly configured BackgroundMaterial on an inverted sphere.
  100623. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  100624. */
  100625. var PhotoDome = /** @class */ (function (_super) {
  100626. __extends(PhotoDome, _super);
  100627. /**
  100628. * Create an instance of this class and pass through the parameters to the relevant classes, Texture, StandardMaterial, and Mesh.
  100629. * @param name Element's name, child elements will append suffixes for their own names.
  100630. * @param urlsOfPhoto define the url of the photo to display
  100631. * @param options An object containing optional or exposed sub element properties
  100632. */
  100633. function PhotoDome(name, urlOfPhoto, options, scene) {
  100634. var _this = _super.call(this, name, scene) || this;
  100635. // set defaults and manage values
  100636. name = name || "photoDome";
  100637. options.resolution = (Math.abs(options.resolution) | 0) || 12;
  100638. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  100639. // create
  100640. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  100641. var texture = _this._photoTexture = new BABYLON.Texture(urlOfPhoto, scene);
  100642. _this._mesh = BABYLON.MeshBuilder.CreateIcoSphere(name + "_mesh", {
  100643. flat: false,
  100644. radius: options.size,
  100645. subdivisions: options.resolution,
  100646. sideOrientation: BABYLON.Mesh.BACKSIDE // needs to be inside out
  100647. }, scene);
  100648. // configure material
  100649. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  100650. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE; // always clamp the up/down
  100651. material.reflectionTexture = _this._photoTexture;
  100652. material.useEquirectangularFOV = true;
  100653. material.fovMultiplier = 1.0;
  100654. // configure mesh
  100655. _this._mesh.material = material;
  100656. _this._mesh.parent = _this;
  100657. return _this;
  100658. }
  100659. Object.defineProperty(PhotoDome.prototype, "photoTexture", {
  100660. /**
  100661. * Gets the texture being displayed on the sphere
  100662. */
  100663. get: function () {
  100664. return this._photoTexture;
  100665. },
  100666. enumerable: true,
  100667. configurable: true
  100668. });
  100669. Object.defineProperty(PhotoDome.prototype, "fovMultiplier", {
  100670. /**
  100671. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  100672. * Also see the options.resolution property.
  100673. */
  100674. get: function () {
  100675. return this._material.fovMultiplier;
  100676. },
  100677. set: function (value) {
  100678. this._material.fovMultiplier = value;
  100679. },
  100680. enumerable: true,
  100681. configurable: true
  100682. });
  100683. /**
  100684. * Releases resources associated with this node.
  100685. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  100686. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  100687. */
  100688. PhotoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  100689. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  100690. this._photoTexture.dispose();
  100691. this._mesh.dispose();
  100692. this._material.dispose();
  100693. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  100694. };
  100695. return PhotoDome;
  100696. }(BABYLON.Node));
  100697. BABYLON.PhotoDome = PhotoDome;
  100698. })(BABYLON || (BABYLON = {}));
  100699. //# sourceMappingURL=babylon.photoDome.js.map
  100700. 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"};
  100701. 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};"};
  100702. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  100703. globalObject["BABYLON"] = BABYLON;
  100704. //backwards compatibility
  100705. if(typeof earcut !== 'undefined') {
  100706. globalObject["Earcut"] = {
  100707. earcut: earcut
  100708. };
  100709. }
  100710. return BABYLON;
  100711. });
  100712. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(17)))
  100713. /***/ }),
  100714. /* 1 */
  100715. /***/ (function(module, exports, __webpack_require__) {
  100716. "use strict";
  100717. Object.defineProperty(exports, "__esModule", { value: true });
  100718. var deepmerge = __webpack_require__(21);
  100719. var expDm = deepmerge['default'];
  100720. exports.deepmerge = expDm;
  100721. /**
  100722. * Is the provided string a URL?
  100723. *
  100724. * @param urlToCheck the url to inspect
  100725. */
  100726. function isUrl(urlToCheck) {
  100727. if (urlToCheck.indexOf('http') === 0 || urlToCheck.indexOf('/') === 0 || urlToCheck.indexOf('./') === 0 || urlToCheck.indexOf('../') === 0) {
  100728. return true;
  100729. }
  100730. return false;
  100731. }
  100732. exports.isUrl = isUrl;
  100733. /**
  100734. * Convert a string from kebab-case to camelCase
  100735. * @param s string to convert
  100736. */
  100737. function kebabToCamel(s) {
  100738. return s.replace(/(\-\w)/g, function (m) { return m[1].toUpperCase(); });
  100739. }
  100740. exports.kebabToCamel = kebabToCamel;
  100741. //https://gist.github.com/youssman/745578062609e8acac9f
  100742. /**
  100743. * Convert a string from camelCase to kebab-case
  100744. * @param str string to convert
  100745. */
  100746. function camelToKebab(str) {
  100747. return !str ? null : str.replace(/([A-Z])/g, function (g) { return '-' + g[0].toLowerCase(); });
  100748. }
  100749. exports.camelToKebab = camelToKebab;
  100750. /**
  100751. * This will extend an object with configuration values.
  100752. * What it practically does it take the keys from the configuration and set them on the object.
  100753. * I the configuration is a tree, it will traverse into the tree.
  100754. * @param object the object to extend
  100755. * @param config the configuration object that will extend the object
  100756. */
  100757. function extendClassWithConfig(object, config) {
  100758. if (!config)
  100759. return;
  100760. Object.keys(config).forEach(function (key) {
  100761. if (key in object && typeof object[key] !== 'function') {
  100762. // if (typeof object[key] === 'function') return;
  100763. // if it is an object, iterate internally until reaching basic types
  100764. if (typeof object[key] === 'object') {
  100765. extendClassWithConfig(object[key], config[key]);
  100766. }
  100767. else {
  100768. if (config[key] !== undefined) {
  100769. object[key] = config[key];
  100770. }
  100771. }
  100772. }
  100773. });
  100774. }
  100775. exports.extendClassWithConfig = extendClassWithConfig;
  100776. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW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UksT0FBTyxHQUFHLEdBQUcsQ0FBQyxDQUFDLENBQUMsQ0FBQyxDQUFDLFdBQVcsRUFBRSxDQUFBLENBQUMsQ0FBQyxDQUFDLENBQUM7QUFDbkcsQ0FBQztBQUZELG9DQUVDO0FBRUQ7Ozs7OztHQU1HO0FBQ0gsK0JBQXNDLE1BQVcsRUFBRSxNQUFXO0lBQzFELElBQUksQ0FBQyxNQUFNO1FBQUUsT0FBTztJQUNwQixNQUFNLENBQUMsSUFBSSxDQUFDLE1BQU0sQ0FBQyxDQUFDLE9BQU8sQ0FBQyxVQUFBLEdBQUc7UUFDM0IsSUFBSSxHQUFHLElBQUksTUFBTSxJQUFJLE9BQU8sTUFBTSxDQUFDLEdBQUcsQ0FBQyxLQUFLLFVBQVUsRUFBRTtZQUNwRCxpREFBaUQ7WUFDakQsb0VBQW9FO1lBQ3BFLElBQUksT0FBTyxNQUFNLENBQUMsR0FBRyxDQUFDLEtBQUssUUFBUSxFQUFFO2dCQUNqQyxxQkFBcUIsQ0FBQyxNQUFNLENBQUMsR0FBRyxDQUFDLEVBQUUsTUFBTSxDQUFDLEdBQUcsQ0FBQyxDQUFDLENBQUM7YUFDbkQ7aUJBQU07Z0JBQ0gsSUFBSSxNQUFNLENBQUMsR0FBRyxDQUFDLEtBQUssU0FBUyxFQUFFO29CQUMzQixNQUFNLENBQUMsR0FBRyxDQUFDLEdBQUcsTUFBTSxDQUFDLEdBQUcsQ0FBQyxDQUFDO2lCQUM3QjthQUNKO1NBQ0o7SUFDTCxDQUFDLENBQUMsQ0FBQztBQUNQLENBQUM7QUFmRCxzREFlQyJ9
  100777. /***/ }),
  100778. /* 2 */
  100779. /***/ (function(module, exports, __webpack_require__) {
  100780. "use strict";
  100781. function __export(m) {
  100782. for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
  100783. }
  100784. Object.defineProperty(exports, "__esModule", { value: true });
  100785. __export(__webpack_require__(31));
  100786. __export(__webpack_require__(33));
  100787. __export(__webpack_require__(39));
  100788. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi9zcmMvYXNzZXRzL2luZGV4LnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7Ozs7O0FBQUEsNEJBQXVCO0FBQ3ZCLDJCQUFzQjtBQUN0QixpQ0FBNEIifQ==
  100789. /***/ }),
  100790. /* 3 */
  100791. /***/ (function(module, exports, __webpack_require__) {
  100792. "use strict";
  100793. Object.defineProperty(exports, "__esModule", { value: true });
  100794. var babylonjs_1 = __webpack_require__(0);
  100795. var _1 = __webpack_require__(1);
  100796. /**
  100797. * This is a simple HTML mapper.
  100798. * This mapper parses a single HTML element and returns the configuration from its attributes.
  100799. * it parses numbers and boolean values to the corresponding variable types.
  100800. * The following HTML element:
  100801. * <div test="1" random-flag="true" a.string.object="test"> will result in the following configuration:
  100802. *
  100803. * {
  100804. * test: 1, //a number!
  100805. * randomFlag: boolean, //camelCase and boolean
  100806. * a: {
  100807. * string: {
  100808. * object: "test" //dot-separated object levels
  100809. * }
  100810. * }
  100811. * }
  100812. */
  100813. var HTMLMapper = /** @class */ (function () {
  100814. function HTMLMapper() {
  100815. }
  100816. /**
  100817. * Map a specific element and get configuration from it
  100818. * @param element the HTML element to analyze.
  100819. */
  100820. HTMLMapper.prototype.map = function (element) {
  100821. var config = {};
  100822. var _loop_1 = function (attrIdx) {
  100823. var attr = element.attributes.item(attrIdx);
  100824. if (!attr) {
  100825. return "continue";
  100826. }
  100827. // map "object.property" to the right configuration place.
  100828. var split = attr.nodeName.split('.');
  100829. split.reduce(function (currentConfig, key, idx) {
  100830. //convert html-style to json-style
  100831. var camelKey = _1.kebabToCamel(key);
  100832. if (idx === split.length - 1) {
  100833. var val = attr.nodeValue; // firefox warns nodeValue is deprecated, but I found no sign of it anywhere.
  100834. if (val === "true") {
  100835. val = true;
  100836. }
  100837. else if (val === "false") {
  100838. val = false;
  100839. }
  100840. else {
  100841. var isnum = !isNaN(parseFloat(val)) && isFinite(val); ///^\d+$/.test(val);
  100842. if (isnum) {
  100843. var number = parseFloat(val);
  100844. if (!isNaN(number)) {
  100845. val = number;
  100846. }
  100847. }
  100848. }
  100849. currentConfig[camelKey] = val;
  100850. }
  100851. else {
  100852. currentConfig[camelKey] = currentConfig[camelKey] || {};
  100853. }
  100854. return currentConfig[camelKey];
  100855. }, config);
  100856. };
  100857. for (var attrIdx = 0; attrIdx < element.attributes.length; ++attrIdx) {
  100858. _loop_1(attrIdx);
  100859. }
  100860. return config;
  100861. };
  100862. return HTMLMapper;
  100863. }());
  100864. /**
  100865. * A simple string-to-JSON mapper.
  100866. * This is the main mapper, used to analyze downloaded JSON-Configuration or JSON payload
  100867. */
  100868. var JSONMapper = /** @class */ (function () {
  100869. function JSONMapper() {
  100870. }
  100871. JSONMapper.prototype.map = function (rawSource) {
  100872. return JSON.parse(rawSource);
  100873. };
  100874. return JSONMapper;
  100875. }());
  100876. /**
  100877. * The DOM Mapper will traverse an entire DOM Tree and will load the configuration from the
  100878. * DOM elements and attributes.
  100879. */
  100880. var DOMMapper = /** @class */ (function () {
  100881. function DOMMapper() {
  100882. }
  100883. /**
  100884. * The mapping function that will convert HTML data to a viewer configuration object
  100885. * @param baseElement the baseElement from which to start traversing
  100886. * @returns a ViewerCOnfiguration object from the provided HTML Element
  100887. */
  100888. DOMMapper.prototype.map = function (baseElement) {
  100889. var htmlMapper = new HTMLMapper();
  100890. var config = htmlMapper.map(baseElement);
  100891. var traverseChildren = function (element, partConfig) {
  100892. var children = element.children;
  100893. if (children.length) {
  100894. for (var i = 0; i < children.length; ++i) {
  100895. var item = children.item(i);
  100896. // use the HTML Mapper to read configuration from a single element
  100897. var configMapped = htmlMapper.map(item);
  100898. var key = _1.kebabToCamel(item.nodeName.toLowerCase());
  100899. if (item.attributes.getNamedItem('array') && item.attributes.getNamedItem('array').nodeValue === 'true') {
  100900. partConfig[key] = [];
  100901. }
  100902. else {
  100903. if (element.attributes.getNamedItem('array') && element.attributes.getNamedItem('array').nodeValue === 'true') {
  100904. partConfig.push(configMapped);
  100905. }
  100906. else if (partConfig[key]) {
  100907. //exists already! probably an array
  100908. element.setAttribute('array', 'true');
  100909. var oldItem = partConfig[key];
  100910. partConfig = [oldItem, configMapped];
  100911. }
  100912. else {
  100913. partConfig[key] = configMapped;
  100914. }
  100915. }
  100916. traverseChildren(item, partConfig[key] || configMapped);
  100917. }
  100918. }
  100919. return partConfig;
  100920. };
  100921. traverseChildren(baseElement, config);
  100922. return config;
  100923. };
  100924. return DOMMapper;
  100925. }());
  100926. /**
  100927. * The MapperManager manages the different implemented mappers.
  100928. * It allows the user to register new mappers as well and use them to parse their own configuration data
  100929. */
  100930. var MapperManager = /** @class */ (function () {
  100931. function MapperManager() {
  100932. this._mappers = {
  100933. "html": new HTMLMapper(),
  100934. "json": new JSONMapper(),
  100935. "dom": new DOMMapper()
  100936. };
  100937. }
  100938. /**
  100939. * Get a specific configuration mapper.
  100940. *
  100941. * @param type the name of the mapper to load
  100942. */
  100943. MapperManager.prototype.getMapper = function (type) {
  100944. if (!this._mappers[type]) {
  100945. babylonjs_1.Tools.Error("No mapper defined for " + type);
  100946. }
  100947. return this._mappers[type];
  100948. };
  100949. /**
  100950. * Use this functio to register your own configuration mapper.
  100951. * After a mapper is registered, it can be used to parse the specific type fo configuration to the standard ViewerConfiguration.
  100952. * @param type the name of the mapper. This will be used to define the configuration type and/or to get the mapper
  100953. * @param mapper The implemented mapper
  100954. */
  100955. MapperManager.prototype.registerMapper = function (type, mapper) {
  100956. this._mappers[type] = mapper;
  100957. };
  100958. /**
  100959. * Dispose the mapper manager and all of its mappers.
  100960. */
  100961. MapperManager.prototype.dispose = function () {
  100962. this._mappers = {};
  100963. };
  100964. /**
  100965. * The default mapper is the JSON mapper.
  100966. */
  100967. MapperManager.DefaultMapper = 'json';
  100968. return MapperManager;
  100969. }());
  100970. exports.MapperManager = MapperManager;
  100971. /**
  100972. * mapperManager is a singleton of the type MapperManager.
  100973. * The mapperManager can be disposed directly with calling mapperManager.dispose()
  100974. * or indirectly with using BabylonViewer.disposeAll()
  100975. */
  100976. exports.mapperManager = new MapperManager();
  100977. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoibWFwcGVycy5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uL3NyYy9jb25maWd1cmF0aW9uL21hcHBlcnMudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFBQSx1Q0FBa0M7QUFHbEMsK0JBQTBDO0FBUzFDOzs7Ozs7Ozs7Ozs7Ozs7O0dBZ0JHO0FBQ0g7SUFBQTtJQTRDQSxDQUFDO0lBMUNHOzs7T0FHRztJQUNILHdCQUFHLEdBQUgsVUFBSSxPQUFvQjtRQUVwQixJQUFJLE1BQU0sR0FBRyxFQUFFLENBQUM7Z0NBQ1AsT0FBTztZQUNaLElBQUksSUFBSSxHQUFHLE9BQU8sQ0FBQyxVQUFVLENBQUMsSUFBSSxDQUFDLE9BQU8sQ0FBQyxDQUFDO1lBQzVDLElBQUksQ0FBQyxJQUFJLEVBQUU7O2FBRVY7WUFDRCwwREFBMEQ7WUFDMUQsSUFBSSxLQUFLLEdBQUcsSUFBSSxDQUFDLFFBQVEsQ0FBQyxLQUFLLENBQUMsR0FBRyxDQUFDLENBQUM7WUFDckMsS0FBSyxDQUFDLE1BQU0sQ0FBQyxVQUFDLGFBQWEsRUFBRSxHQUFHLEVBQUUsR0FBRztnQkFDakMsa0NBQWtDO2dCQUNsQyxJQUFJLFFBQVEsR0FBRyxlQUFZLENBQUMsR0FBRyxDQUFDLENBQUM7Z0JBQ2pDLElBQUksR0FBRyxLQUFLLEtBQUssQ0FBQyxNQUFNLEdBQUcsQ0FBQyxFQUFFO29CQUMxQixJQUFJLEdBQUcsR0FBUSxJQUFLLENBQUMsU0FBUyxD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ELElBNkNDO0FBRUQ7OztHQUdHO0FBQ0g7SUFRSTtRQUNJLElBQUksQ0FBQyxRQUFRLEdBQUc7WUFDWixNQUFNLEVBQUUsSUFBSSxVQUFVLEVBQUU7WUFDeEIsTUFBTSxFQUFFLElBQUksVUFBVSxFQUFFO1lBQ3hCLEtBQUssRUFBRSxJQUFJLFNBQVMsRUFBRTtTQUN6QixDQUFBO0lBQ0wsQ0FBQztJQUVEOzs7O09BSUc7SUFDSSxpQ0FBUyxHQUFoQixVQUFpQixJQUFZO1FBQ3pCLElBQUksQ0FBQyxJQUFJLENBQUMsUUFBUSxDQUFDLElBQUksQ0FBQyxFQUFFO1lBQ3RCLGlCQUFLLENBQUMsS0FBSyxDQUFDLHdCQUF3QixHQUFHLElBQUksQ0FBQyxDQUFDO1NBQ2hEO1FBQ0QsT0FBTyxJQUFJLENBQUMsUUFBUSxDQUFDLElBQUksQ0FBQyxDQUFDO0lBQy9CLENBQUM7SUFFRDs7Ozs7T0FLRztJQUNJLHNDQUFjLEdBQXJCLFVBQXNCLElBQVksRUFBRSxNQUFlO1FBQy9DLElBQUksQ0FBQyxRQUFRLENBQUMsSUFBSSxDQUFDLEdBQUcsTUFBTSxDQUFDO0lBQ2pDLENBQUM7SUFFRDs7T0FFRztJQUNJLCtCQUFPLEdBQWQ7UUFDSSxJQUFJLENBQUMsUUFBUSxHQUFHLEVBQUUsQ0FBQztJQUN2QixDQUFDO0lBeENEOztPQUVHO0lBQ1csMkJBQWEsR0FBRyxNQUFNLENBQUM7SUF1Q3pDLG9CQUFDO0NBQUEsQUE3Q0QsSUE2Q0M7QUE3Q1ksc0NBQWE7QUErQzFCOzs7O0dBSUc7QUFDUSxRQUFBLGFBQWEsR0FBRyxJQUFJLGFBQWEsRUFBRSxDQUFDIn0=
  100978. /***/ }),
  100979. /* 4 */
  100980. /***/ (function(module, exports, __webpack_require__) {
  100981. "use strict";
  100982. Object.defineProperty(exports, "__esModule", { value: true });
  100983. var babylonjs_1 = __webpack_require__(0);
  100984. var ViewerGlobals = /** @class */ (function () {
  100985. function ViewerGlobals() {
  100986. this.disableInit = false;
  100987. this.disableWebGL2Support = false;
  100988. }
  100989. Object.defineProperty(ViewerGlobals.prototype, "version", {
  100990. get: function () {
  100991. return babylonjs_1.Engine.Version;
  100992. },
  100993. enumerable: true,
  100994. configurable: true
  100995. });
  100996. return ViewerGlobals;
  100997. }());
  100998. exports.ViewerGlobals = ViewerGlobals;
  100999. exports.viewerGlobals = new ViewerGlobals();
  101000. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZ2xvYmFscy5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uL3NyYy9jb25maWd1cmF0aW9uL2dsb2JhbHMudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFBQSx1Q0FBbUM7QUFFbkM7SUFBQTtRQUVXLGdCQUFXLEdBQVksS0FBSyxDQUFDO1FBQzdCLHlCQUFvQixHQUFZLEtBQUssQ0FBQztJQU1qRCxDQUFDO0lBSkcsc0JBQVcsa0NBQU87YUFBbEI7WUFDSSxPQUFPLGtCQUFNLENBQUMsT0FBTyxDQUFDO1FBQzFCLENBQUM7OztPQUFBO0lBRUwsb0JBQUM7QUFBRCxDQUFDLEFBVEQsSUFTQztBQVRZLHNDQUFhO0FBV2YsUUFBQSxhQUFhLEdBQWtCLElBQUksYUFBYSxFQUFFLENBQUMifQ==
  101001. /***/ }),
  101002. /* 5 */
  101003. /***/ (function(module, exports, __webpack_require__) {
  101004. "use strict";
  101005. Object.defineProperty(exports, "__esModule", { value: true });
  101006. var babylonjs_1 = __webpack_require__(0);
  101007. var modelAnimation_1 = __webpack_require__(23);
  101008. var _1 = __webpack_require__(1);
  101009. /**
  101010. * The current state of the model
  101011. */
  101012. var ModelState;
  101013. (function (ModelState) {
  101014. ModelState[ModelState["INIT"] = 0] = "INIT";
  101015. ModelState[ModelState["LOADING"] = 1] = "LOADING";
  101016. ModelState[ModelState["LOADED"] = 2] = "LOADED";
  101017. ModelState[ModelState["ENTRY"] = 3] = "ENTRY";
  101018. ModelState[ModelState["ENTRYDONE"] = 4] = "ENTRYDONE";
  101019. ModelState[ModelState["COMPLETE"] = 5] = "COMPLETE";
  101020. ModelState[ModelState["CANCELED"] = 6] = "CANCELED";
  101021. ModelState[ModelState["ERROR"] = 7] = "ERROR";
  101022. })(ModelState = exports.ModelState || (exports.ModelState = {}));
  101023. /**
  101024. * The viewer model is a container for all assets representing a sngle loaded model.
  101025. */
  101026. var ViewerModel = /** @class */ (function () {
  101027. function ViewerModel(_observablesManager, modelConfiguration, _configurationContainer) {
  101028. var _this = this;
  101029. this._observablesManager = _observablesManager;
  101030. this._configurationContainer = _configurationContainer;
  101031. /**
  101032. * the list of meshes that are a part of this model
  101033. */
  101034. this._meshes = [];
  101035. /**
  101036. * ParticleSystems connected to this model
  101037. */
  101038. this.particleSystems = [];
  101039. /**
  101040. * Skeletons defined in this model
  101041. */
  101042. this.skeletons = [];
  101043. this._loaderDone = false;
  101044. this._animatables = [];
  101045. this._frameRate = 60;
  101046. this._shadowsRenderedAfterLoad = false;
  101047. this.onLoadedObservable = new babylonjs_1.Observable();
  101048. this.onLoadErrorObservable = new babylonjs_1.Observable();
  101049. this.onLoadProgressObservable = new babylonjs_1.Observable();
  101050. this.onCompleteObservable = new babylonjs_1.Observable();
  101051. this.onAfterConfigure = new babylonjs_1.Observable();
  101052. this.state = ModelState.INIT;
  101053. this.rootMesh = new babylonjs_1.AbstractMesh("modelRootMesh");
  101054. this._pivotMesh = new babylonjs_1.AbstractMesh("pivotMesh");
  101055. this._pivotMesh.parent = this.rootMesh;
  101056. // rotate 180, gltf fun
  101057. this._pivotMesh.rotation.y += Math.PI;
  101058. this._scaleTransition = new babylonjs_1.Animation("scaleAnimation", "scaling", this._frameRate, babylonjs_1.Animation.ANIMATIONTYPE_VECTOR3, babylonjs_1.Animation.ANIMATIONLOOPMODE_CONSTANT);
  101059. this._animations = [];
  101060. //create a copy of the configuration to make sure it doesn't change even after it is changed in the viewer
  101061. this._modelConfiguration = _1.deepmerge((this._configurationContainer && this._configurationContainer.configuration.model) || {}, modelConfiguration);
  101062. if (this._observablesManager) {
  101063. this._observablesManager.onModelAddedObservable.notifyObservers(this);
  101064. }
  101065. if (this._modelConfiguration.entryAnimation) {
  101066. this.rootMesh.setEnabled(false);
  101067. }
  101068. this.onLoadedObservable.add(function () {
  101069. _this.updateConfiguration(_this._modelConfiguration);
  101070. if (_this._observablesManager) {
  101071. _this._observablesManager.onModelLoadedObservable.notifyObservers(_this);
  101072. }
  101073. _this._initAnimations();
  101074. });
  101075. this.onCompleteObservable.add(function () {
  101076. _this.state = ModelState.COMPLETE;
  101077. });
  101078. }
  101079. Object.defineProperty(ViewerModel.prototype, "shadowsRenderedAfterLoad", {
  101080. get: function () {
  101081. return this._shadowsRenderedAfterLoad;
  101082. },
  101083. set: function (rendered) {
  101084. if (!rendered) {
  101085. throw new Error("can only be enabled");
  101086. }
  101087. else {
  101088. this._shadowsRenderedAfterLoad = rendered;
  101089. }
  101090. },
  101091. enumerable: true,
  101092. configurable: true
  101093. });
  101094. ViewerModel.prototype.getViewerId = function () {
  101095. return this._configurationContainer && this._configurationContainer.viewerId;
  101096. };
  101097. Object.defineProperty(ViewerModel.prototype, "enabled", {
  101098. /**
  101099. * Is this model enabled?
  101100. */
  101101. get: function () {
  101102. return this.rootMesh.isEnabled();
  101103. },
  101104. /**
  101105. * Set whether this model is enabled or not.
  101106. */
  101107. set: function (enable) {
  101108. this.rootMesh.setEnabled(enable);
  101109. },
  101110. enumerable: true,
  101111. configurable: true
  101112. });
  101113. Object.defineProperty(ViewerModel.prototype, "loaderDone", {
  101114. set: function (done) {
  101115. this._loaderDone = done;
  101116. this._checkCompleteState();
  101117. },
  101118. enumerable: true,
  101119. configurable: true
  101120. });
  101121. ViewerModel.prototype._checkCompleteState = function () {
  101122. if (this._loaderDone && (this.state === ModelState.ENTRYDONE)) {
  101123. this._modelComplete();
  101124. }
  101125. };
  101126. /**
  101127. * Add a mesh to this model.
  101128. * Any mesh that has no parent will be provided with the root mesh as its new parent.
  101129. *
  101130. * @param mesh the new mesh to add
  101131. * @param triggerLoaded should this mesh trigger the onLoaded observable. Used when adding meshes manually.
  101132. */
  101133. ViewerModel.prototype.addMesh = function (mesh, triggerLoaded) {
  101134. if (!mesh.parent) {
  101135. mesh.parent = this._pivotMesh;
  101136. }
  101137. mesh.receiveShadows = !!this.configuration.receiveShadows;
  101138. this._meshes.push(mesh);
  101139. if (triggerLoaded) {
  101140. return this.onLoadedObservable.notifyObserversWithPromise(this);
  101141. }
  101142. };
  101143. Object.defineProperty(ViewerModel.prototype, "meshes", {
  101144. /**
  101145. * get the list of meshes (excluding the root mesh)
  101146. */
  101147. get: function () {
  101148. return this._meshes;
  101149. },
  101150. enumerable: true,
  101151. configurable: true
  101152. });
  101153. Object.defineProperty(ViewerModel.prototype, "configuration", {
  101154. /**
  101155. * Get the model's configuration
  101156. */
  101157. get: function () {
  101158. return this._modelConfiguration;
  101159. },
  101160. /**
  101161. * (Re-)set the model's entire configuration
  101162. * @param newConfiguration the new configuration to replace the new one
  101163. */
  101164. set: function (newConfiguration) {
  101165. this._modelConfiguration = newConfiguration;
  101166. this._configureModel();
  101167. },
  101168. enumerable: true,
  101169. configurable: true
  101170. });
  101171. /**
  101172. * Update the current configuration with new values.
  101173. * Configuration will not be overwritten, but merged with the new configuration.
  101174. * Priority is to the new configuration
  101175. * @param newConfiguration the configuration to be merged into the current configuration;
  101176. */
  101177. ViewerModel.prototype.updateConfiguration = function (newConfiguration) {
  101178. this._modelConfiguration = _1.deepmerge(this._modelConfiguration, newConfiguration);
  101179. this._configureModel();
  101180. };
  101181. ViewerModel.prototype._initAnimations = function () {
  101182. var _this = this;
  101183. // check if this is not a gltf loader and init the animations
  101184. if (this.skeletons.length) {
  101185. this.skeletons.forEach(function (skeleton, idx) {
  101186. var ag = new babylonjs_1.AnimationGroup("animation-" + idx);
  101187. skeleton.getAnimatables().forEach(function (a) {
  101188. if (a.animations[0]) {
  101189. ag.addTargetedAnimation(a.animations[0], a);
  101190. }
  101191. });
  101192. _this.addAnimationGroup(ag);
  101193. });
  101194. }
  101195. var completeCallback = function () {
  101196. };
  101197. if (this._modelConfiguration.animation) {
  101198. if (this._modelConfiguration.animation.playOnce) {
  101199. this._animations.forEach(function (a) {
  101200. a.playMode = 0 /* ONCE */;
  101201. });
  101202. }
  101203. if (this._modelConfiguration.animation.autoStart && this._animations.length) {
  101204. var animationName_1 = this._modelConfiguration.animation.autoStart === true ?
  101205. this._animations[0].name : this._modelConfiguration.animation.autoStart;
  101206. completeCallback = function () {
  101207. _this.playAnimation(animationName_1);
  101208. };
  101209. }
  101210. }
  101211. this._enterScene(completeCallback);
  101212. };
  101213. /**
  101214. * Animates the model from the current position to the default position
  101215. * @param completeCallback A function to call when the animation has completed
  101216. */
  101217. ViewerModel.prototype._enterScene = function (completeCallback) {
  101218. var _this = this;
  101219. var scene = this.rootMesh.getScene();
  101220. var previousValue = scene.animationPropertiesOverride.enableBlending;
  101221. var callback = function () {
  101222. _this.state = ModelState.ENTRYDONE;
  101223. scene.animationPropertiesOverride.enableBlending = previousValue;
  101224. _this._checkCompleteState();
  101225. if (completeCallback)
  101226. completeCallback();
  101227. };
  101228. if (!this._entryAnimation) {
  101229. callback();
  101230. return;
  101231. }
  101232. this.rootMesh.setEnabled(true);
  101233. // disable blending for the sake of the entry animation;
  101234. scene.animationPropertiesOverride.enableBlending = false;
  101235. this._applyAnimation(this._entryAnimation, true, callback);
  101236. };
  101237. /**
  101238. * Animates the model from the current position to the exit-screen position
  101239. * @param completeCallback A function to call when the animation has completed
  101240. */
  101241. ViewerModel.prototype._exitScene = function (completeCallback) {
  101242. if (!this._exitAnimation) {
  101243. completeCallback();
  101244. return;
  101245. }
  101246. this._applyAnimation(this._exitAnimation, false, completeCallback);
  101247. };
  101248. ViewerModel.prototype._modelComplete = function () {
  101249. var _this = this;
  101250. //reapply material defines to be sure:
  101251. var meshes = this._pivotMesh.getChildMeshes(false);
  101252. meshes.filter(function (m) { return m.material; }).forEach(function (mesh) {
  101253. _this._applyModelMaterialConfiguration(mesh.material);
  101254. });
  101255. this.state = ModelState.COMPLETE;
  101256. this.onCompleteObservable.notifyObservers(this);
  101257. };
  101258. /**
  101259. * Add a new animation group to this model.
  101260. * @param animationGroup the new animation group to be added
  101261. */
  101262. ViewerModel.prototype.addAnimationGroup = function (animationGroup) {
  101263. this._animations.push(new modelAnimation_1.GroupModelAnimation(animationGroup));
  101264. };
  101265. /**
  101266. * Get the ModelAnimation array
  101267. */
  101268. ViewerModel.prototype.getAnimations = function () {
  101269. return this._animations;
  101270. };
  101271. /**
  101272. * Get the animations' names. Using the names you can play a specific animation.
  101273. */
  101274. ViewerModel.prototype.getAnimationNames = function () {
  101275. return this._animations.map(function (a) { return a.name; });
  101276. };
  101277. /**
  101278. * Get an animation by the provided name. Used mainly when playing n animation.
  101279. * @param name the name of the animation to find
  101280. */
  101281. ViewerModel.prototype._getAnimationByName = function (name) {
  101282. // can't use .find, noe available on IE
  101283. var filtered = this._animations.filter(function (a) { return a.name === name; });
  101284. // what the next line means - if two animations have the same name, they will not be returned!
  101285. if (filtered.length === 1) {
  101286. return filtered[0];
  101287. }
  101288. else {
  101289. return null;
  101290. }
  101291. };
  101292. /**
  101293. * Choose an initialized animation using its name and start playing it
  101294. * @param name the name of the animation to play
  101295. * @returns The model aniamtion to be played.
  101296. */
  101297. ViewerModel.prototype.playAnimation = function (name) {
  101298. var animation = this.setCurrentAnimationByName(name);
  101299. if (animation) {
  101300. animation.start();
  101301. }
  101302. return animation;
  101303. };
  101304. ViewerModel.prototype.setCurrentAnimationByName = function (name) {
  101305. var animation = this._getAnimationByName(name);
  101306. if (animation) {
  101307. if (this.currentAnimation && this.currentAnimation.state !== 3 /* STOPPED */) {
  101308. this.currentAnimation.stop();
  101309. }
  101310. this.currentAnimation = animation;
  101311. return animation;
  101312. }
  101313. else {
  101314. throw new Error("animation not found - " + name);
  101315. }
  101316. };
  101317. ViewerModel.prototype._configureModel = function () {
  101318. var _this = this;
  101319. // this can be changed to the meshes that have rootMesh a parent without breaking anything.
  101320. var meshesWithNoParent = [this.rootMesh]; //this._meshes.filter(m => m.parent === this.rootMesh);
  101321. var updateMeshesWithNoParent = function (variable, value, param) {
  101322. meshesWithNoParent.forEach(function (mesh) {
  101323. if (param) {
  101324. mesh[variable][param] = value;
  101325. }
  101326. else {
  101327. mesh[variable] = value;
  101328. }
  101329. });
  101330. };
  101331. var updateXYZ = function (variable, configValues) {
  101332. if (configValues.x !== undefined) {
  101333. updateMeshesWithNoParent(variable, configValues.x, 'x');
  101334. }
  101335. if (configValues.y !== undefined) {
  101336. updateMeshesWithNoParent(variable, configValues.y, 'y');
  101337. }
  101338. if (configValues.z !== undefined) {
  101339. updateMeshesWithNoParent(variable, configValues.z, 'z');
  101340. }
  101341. if (configValues.w !== undefined) {
  101342. updateMeshesWithNoParent(variable, configValues.w, 'w');
  101343. }
  101344. };
  101345. if (this._modelConfiguration.normalize) {
  101346. var center = false;
  101347. var unitSize = false;
  101348. var parentIndex = void 0;
  101349. if (this._modelConfiguration.normalize === true) {
  101350. center = true;
  101351. unitSize = true;
  101352. }
  101353. else {
  101354. center = !!this._modelConfiguration.normalize.center;
  101355. unitSize = !!this._modelConfiguration.normalize.unitSize;
  101356. parentIndex = this._modelConfiguration.normalize.parentIndex;
  101357. }
  101358. var meshesToNormalize = [];
  101359. if (parentIndex !== undefined) {
  101360. meshesToNormalize.push(this._meshes[parentIndex]);
  101361. }
  101362. else {
  101363. meshesToNormalize = this._pivotMesh.getChildMeshes(true).length === 1 ? [this._pivotMesh] : meshesWithNoParent;
  101364. }
  101365. if (unitSize) {
  101366. meshesToNormalize.forEach(function (mesh) {
  101367. mesh.normalizeToUnitCube(true);
  101368. mesh.computeWorldMatrix(true);
  101369. });
  101370. }
  101371. if (center) {
  101372. meshesToNormalize.forEach(function (mesh) {
  101373. var boundingInfo = mesh.getHierarchyBoundingVectors(true);
  101374. var sizeVec = boundingInfo.max.subtract(boundingInfo.min);
  101375. var halfSizeVec = sizeVec.scale(0.5);
  101376. var center = boundingInfo.min.add(halfSizeVec);
  101377. mesh.position = center.scale(-1);
  101378. mesh.position.y += halfSizeVec.y;
  101379. // Recompute Info.
  101380. mesh.computeWorldMatrix(true);
  101381. });
  101382. }
  101383. }
  101384. else {
  101385. // if centered, should be done here
  101386. }
  101387. // position?
  101388. if (this._modelConfiguration.position) {
  101389. updateXYZ('position', this._modelConfiguration.position);
  101390. }
  101391. if (this._modelConfiguration.rotation) {
  101392. //quaternion?
  101393. if (this._modelConfiguration.rotation.w) {
  101394. meshesWithNoParent.forEach(function (mesh) {
  101395. if (!mesh.rotationQuaternion) {
  101396. mesh.rotationQuaternion = new babylonjs_1.Quaternion();
  101397. }
  101398. });
  101399. updateXYZ('rotationQuaternion', this._modelConfiguration.rotation);
  101400. }
  101401. else {
  101402. updateXYZ('rotation', this._modelConfiguration.rotation);
  101403. }
  101404. }
  101405. if (this._modelConfiguration.rotationOffsetAxis) {
  101406. var rotationAxis_1 = new babylonjs_1.Vector3(0, 0, 0).copyFrom(this._modelConfiguration.rotationOffsetAxis);
  101407. meshesWithNoParent.forEach(function (m) {
  101408. if (_this._modelConfiguration.rotationOffsetAngle) {
  101409. m.rotate(rotationAxis_1, _this._modelConfiguration.rotationOffsetAngle);
  101410. }
  101411. });
  101412. }
  101413. if (this._modelConfiguration.scaling) {
  101414. updateXYZ('scaling', this._modelConfiguration.scaling);
  101415. }
  101416. if (this._modelConfiguration.castShadow) {
  101417. this._meshes.forEach(function (mesh) {
  101418. babylonjs_1.Tags.AddTagsTo(mesh, 'castShadow');
  101419. });
  101420. }
  101421. var meshes = this._pivotMesh.getChildMeshes(false);
  101422. meshes.filter(function (m) { return m.material; }).forEach(function (mesh) {
  101423. _this._applyModelMaterialConfiguration(mesh.material);
  101424. });
  101425. if (this._modelConfiguration.entryAnimation) {
  101426. this._entryAnimation = this._modelAnimationConfigurationToObject(this._modelConfiguration.entryAnimation);
  101427. }
  101428. if (this._modelConfiguration.exitAnimation) {
  101429. this._exitAnimation = this._modelAnimationConfigurationToObject(this._modelConfiguration.exitAnimation);
  101430. }
  101431. this.onAfterConfigure.notifyObservers(this);
  101432. };
  101433. ViewerModel.prototype._modelAnimationConfigurationToObject = function (animConfig) {
  101434. var anim = {
  101435. time: 0.5
  101436. };
  101437. if (animConfig.scaling) {
  101438. anim.scaling = babylonjs_1.Vector3.Zero();
  101439. }
  101440. if (animConfig.easingFunction !== undefined) {
  101441. anim.easingFunction = animConfig.easingFunction;
  101442. }
  101443. if (animConfig.easingMode !== undefined) {
  101444. anim.easingMode = animConfig.easingMode;
  101445. }
  101446. _1.extendClassWithConfig(anim, animConfig);
  101447. return anim;
  101448. };
  101449. /**
  101450. * Apply a material configuration to a material
  101451. * @param material Material to apply configuration to
  101452. */
  101453. ViewerModel.prototype._applyModelMaterialConfiguration = function (material) {
  101454. if (!this._modelConfiguration.material)
  101455. return;
  101456. _1.extendClassWithConfig(material, this._modelConfiguration.material);
  101457. if (material instanceof babylonjs_1.PBRMaterial) {
  101458. if (this._modelConfiguration.material.directIntensity !== undefined) {
  101459. material.directIntensity = this._modelConfiguration.material.directIntensity;
  101460. }
  101461. if (this._modelConfiguration.material.emissiveIntensity !== undefined) {
  101462. material.emissiveIntensity = this._modelConfiguration.material.emissiveIntensity;
  101463. }
  101464. if (this._modelConfiguration.material.environmentIntensity !== undefined) {
  101465. material.environmentIntensity = this._modelConfiguration.material.environmentIntensity;
  101466. }
  101467. if (this._modelConfiguration.material.directEnabled !== undefined) {
  101468. material.disableLighting = !this._modelConfiguration.material.directEnabled;
  101469. }
  101470. if (this._configurationContainer && this._configurationContainer.reflectionColor) {
  101471. material.reflectionColor = this._configurationContainer.reflectionColor;
  101472. }
  101473. }
  101474. else if (material instanceof babylonjs_1.MultiMaterial) {
  101475. for (var i = 0; i < material.subMaterials.length; i++) {
  101476. var subMaterial = material.subMaterials[i];
  101477. if (subMaterial) {
  101478. this._applyModelMaterialConfiguration(subMaterial);
  101479. }
  101480. }
  101481. }
  101482. };
  101483. /**
  101484. * Start entry/exit animation given an animation configuration
  101485. * @param animationConfiguration Entry/Exit animation configuration
  101486. * @param isEntry Pass true if the animation is an entry animation
  101487. * @param completeCallback Callback to execute when the animation completes
  101488. */
  101489. ViewerModel.prototype._applyAnimation = function (animationConfiguration, isEntry, completeCallback) {
  101490. var animations = [];
  101491. //scale
  101492. if (animationConfiguration.scaling) {
  101493. var scaleStart = isEntry ? animationConfiguration.scaling : new babylonjs_1.Vector3(1, 1, 1);
  101494. var scaleEnd = isEntry ? new babylonjs_1.Vector3(1, 1, 1) : animationConfiguration.scaling;
  101495. if (!scaleStart.equals(scaleEnd)) {
  101496. this.rootMesh.scaling = scaleStart;
  101497. this._setLinearKeys(this._scaleTransition, this.rootMesh.scaling, scaleEnd, animationConfiguration.time);
  101498. animations.push(this._scaleTransition);
  101499. }
  101500. }
  101501. //Start the animation(s)
  101502. this.transitionTo(animations, animationConfiguration.time, this._createEasingFunction(animationConfiguration.easingFunction), animationConfiguration.easingMode, function () { if (completeCallback)
  101503. completeCallback(); });
  101504. };
  101505. /**
  101506. * Begin @animations with the specified @easingFunction
  101507. * @param animations The BABYLON Animations to begin
  101508. * @param duration of transition, in seconds
  101509. * @param easingFunction An easing function to apply
  101510. * @param easingMode A easing mode to apply to the easingFunction
  101511. * @param onAnimationEnd Call back trigger at the end of the animation.
  101512. */
  101513. ViewerModel.prototype.transitionTo = function (animations, duration, easingFunction, easingMode, onAnimationEnd) {
  101514. if (easingMode === void 0) { easingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT; }
  101515. if (easingFunction) {
  101516. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  101517. var animation = animations_1[_i];
  101518. easingFunction.setEasingMode(easingMode);
  101519. animation.setEasingFunction(easingFunction);
  101520. }
  101521. }
  101522. //Stop any current animations before starting the new one - merging not yet supported.
  101523. this.stopAllAnimations();
  101524. this.rootMesh.animations = animations;
  101525. if (this.rootMesh.getScene().beginAnimation) {
  101526. var animatable = this.rootMesh.getScene().beginAnimation(this.rootMesh, 0, this._frameRate * duration, false, 1, function () {
  101527. if (onAnimationEnd) {
  101528. onAnimationEnd();
  101529. }
  101530. });
  101531. this._animatables.push(animatable);
  101532. }
  101533. };
  101534. /**
  101535. * Sets key values on an Animation from first to last frame.
  101536. * @param animation The Babylon animation object to set keys on
  101537. * @param startValue The value of the first key
  101538. * @param endValue The value of the last key
  101539. * @param duration The duration of the animation, used to determine the end frame
  101540. */
  101541. ViewerModel.prototype._setLinearKeys = function (animation, startValue, endValue, duration) {
  101542. animation.setKeys([
  101543. {
  101544. frame: 0,
  101545. value: startValue
  101546. },
  101547. {
  101548. frame: this._frameRate * duration,
  101549. value: endValue
  101550. }
  101551. ]);
  101552. };
  101553. /**
  101554. * Creates and returns a Babylon easing funtion object based on a string representing the Easing function
  101555. * @param easingFunctionID The enum of the easing funtion to create
  101556. * @return The newly created Babylon easing function object
  101557. */
  101558. ViewerModel.prototype._createEasingFunction = function (easingFunctionID) {
  101559. var easingFunction;
  101560. switch (easingFunctionID) {
  101561. case 1 /* CircleEase */:
  101562. easingFunction = new babylonjs_1.CircleEase();
  101563. break;
  101564. case 2 /* BackEase */:
  101565. easingFunction = new babylonjs_1.BackEase(0.3);
  101566. break;
  101567. case 3 /* BounceEase */:
  101568. easingFunction = new babylonjs_1.BounceEase();
  101569. break;
  101570. case 4 /* CubicEase */:
  101571. easingFunction = new babylonjs_1.CubicEase();
  101572. break;
  101573. case 5 /* ElasticEase */:
  101574. easingFunction = new babylonjs_1.ElasticEase();
  101575. break;
  101576. case 6 /* ExponentialEase */:
  101577. easingFunction = new babylonjs_1.ExponentialEase();
  101578. break;
  101579. case 7 /* PowerEase */:
  101580. easingFunction = new babylonjs_1.PowerEase();
  101581. break;
  101582. case 8 /* QuadraticEase */:
  101583. easingFunction = new babylonjs_1.QuadraticEase();
  101584. break;
  101585. case 9 /* QuarticEase */:
  101586. easingFunction = new babylonjs_1.QuarticEase();
  101587. break;
  101588. case 10 /* QuinticEase */:
  101589. easingFunction = new babylonjs_1.QuinticEase();
  101590. break;
  101591. case 11 /* SineEase */:
  101592. easingFunction = new babylonjs_1.SineEase();
  101593. break;
  101594. default:
  101595. babylonjs_1.Tools.Log("No ease function found");
  101596. break;
  101597. }
  101598. return easingFunction;
  101599. };
  101600. /**
  101601. * Stops and removes all animations that have been applied to the model
  101602. */
  101603. ViewerModel.prototype.stopAllAnimations = function () {
  101604. if (this.rootMesh) {
  101605. this.rootMesh.animations = [];
  101606. }
  101607. if (this.currentAnimation) {
  101608. this.currentAnimation.stop();
  101609. }
  101610. while (this._animatables.length) {
  101611. this._animatables[0].onAnimationEnd = null;
  101612. this._animatables[0].stop();
  101613. this._animatables.shift();
  101614. }
  101615. };
  101616. /**
  101617. * Will remove this model from the viewer (but NOT dispose it).
  101618. */
  101619. ViewerModel.prototype.remove = function () {
  101620. this.stopAllAnimations();
  101621. // hide it
  101622. this.rootMesh.isVisible = false;
  101623. if (this._observablesManager) {
  101624. this._observablesManager.onModelRemovedObservable.notifyObservers(this);
  101625. }
  101626. };
  101627. /**
  101628. * Dispose this model, including all of its associated assets.
  101629. */
  101630. ViewerModel.prototype.dispose = function () {
  101631. this.remove();
  101632. this.onAfterConfigure.clear();
  101633. this.onLoadedObservable.clear();
  101634. this.onLoadErrorObservable.clear();
  101635. this.onLoadProgressObservable.clear();
  101636. if (this.loader && this.loader.name === "gltf") {
  101637. this.loader.dispose();
  101638. }
  101639. this.particleSystems.forEach(function (ps) { return ps.dispose(); });
  101640. this.particleSystems.length = 0;
  101641. this.skeletons.forEach(function (s) { return s.dispose(); });
  101642. this.skeletons.length = 0;
  101643. this._animations.forEach(function (ag) { return ag.dispose(); });
  101644. this._animations.length = 0;
  101645. this.rootMesh.dispose(false, true);
  101646. };
  101647. return ViewerModel;
  101648. }());
  101649. exports.View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Q==
  101651. /***/ }),
  101652. /* 6 */
  101653. /***/ (function(module, exports, __webpack_require__) {
  101654. "use strict";
  101655. Object.defineProperty(exports, "__esModule", { value: true });
  101656. var babylonjs_1 = __webpack_require__(0);
  101657. /**
  101658. * Receives Telemetry events and raises events to the API
  101659. */
  101660. var TelemetryManager = /** @class */ (function () {
  101661. function TelemetryManager() {
  101662. this.onEventBroadcastedObservable = new babylonjs_1.Observable();
  101663. this._event = this._eventEnabled;
  101664. }
  101665. Object.defineProperty(TelemetryManager.prototype, "broadcast", {
  101666. /**
  101667. * Receives a telemetry event
  101668. * @param event The name of the Telemetry event
  101669. * @param details An additional value, or an object containing a list of property/value pairs
  101670. */
  101671. get: function () {
  101672. return this._event;
  101673. },
  101674. enumerable: true,
  101675. configurable: true
  101676. });
  101677. /**
  101678. * Log a Telemetry event for errors raised on the WebGL context.
  101679. * @param engine The Babylon engine with the WebGL context.
  101680. */
  101681. TelemetryManager.prototype.flushWebGLErrors = function (engine, viewerId) {
  101682. if (!engine) {
  101683. return;
  101684. }
  101685. var logErrors = true;
  101686. while (logErrors) {
  101687. var gl = engine._gl;
  101688. if (gl && gl.getError) {
  101689. var error = gl.getError();
  101690. if (error === gl.NO_ERROR) {
  101691. logErrors = false;
  101692. }
  101693. else {
  101694. this.broadcast("WebGL Error", viewerId, { error: error });
  101695. }
  101696. }
  101697. else {
  101698. logErrors = false;
  101699. }
  101700. }
  101701. };
  101702. Object.defineProperty(TelemetryManager.prototype, "enable", {
  101703. /**
  101704. * Enable or disable telemetry events
  101705. * @param enabled Boolan, true if events are enabled
  101706. */
  101707. set: function (enabled) {
  101708. if (enabled) {
  101709. this._event = this._eventEnabled;
  101710. }
  101711. else {
  101712. this._event = this._eventDisabled;
  101713. }
  101714. },
  101715. enumerable: true,
  101716. configurable: true
  101717. });
  101718. /**
  101719. * Called on event when disabled, typically do nothing here
  101720. */
  101721. TelemetryManager.prototype._eventDisabled = function () {
  101722. // nothing to do
  101723. };
  101724. /**
  101725. * Called on event when enabled
  101726. * @param event - The name of the Telemetry event
  101727. * @param details An additional value, or an object containing a list of property/value pairs
  101728. */
  101729. TelemetryManager.prototype._eventEnabled = function (event, viewerId, details) {
  101730. var telemetryData = {
  101731. viewerId: viewerId,
  101732. event: event,
  101733. session: this.session,
  101734. date: new Date(),
  101735. now: window.performance ? window.performance.now() : Date.now(),
  101736. detail: null
  101737. };
  101738. if (typeof details === "object") {
  101739. for (var attr in details) {
  101740. if (details.hasOwnProperty(attr)) {
  101741. telemetryData[attr] = details[attr];
  101742. }
  101743. }
  101744. }
  101745. else if (details) {
  101746. telemetryData.detail = details;
  101747. }
  101748. this.onEventBroadcastedObservable.notifyObservers(telemetryData);
  101749. };
  101750. Object.defineProperty(TelemetryManager.prototype, "session", {
  101751. /**
  101752. * Returns the current session ID or creates one if it doesn't exixt
  101753. * @return The current session ID
  101754. */
  101755. get: function () {
  101756. if (!this._currentSessionId) {
  101757. //String + Timestamp + Random Integer
  101758. this._currentSessionId = "SESSION_" + Date.now() + Math.floor(Math.random() * 0x10000);
  101759. }
  101760. return this._currentSessionId;
  101761. },
  101762. enumerable: true,
  101763. configurable: true
  101764. });
  101765. /**
  101766. * Disposes the telemetry manager
  101767. */
  101768. TelemetryManager.prototype.dispose = function () {
  101769. this.onEventBroadcastedObservable.clear();
  101770. delete this.onEventBroadcastedObservable;
  101771. };
  101772. return TelemetryManager;
  101773. }());
  101774. exports.TelemetryManager = TelemetryManager;
  101775. exports.telemetryManager = new TelemetryManager();
  101776. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidGVsZW1ldHJ5TWFuYWdlci5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uL3NyYy9tYW5hZ2Vycy90ZWxlbWV0cnlNYW5hZ2VyLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7O0FBQUEsdUNBQStDO0FBYy9DOztHQUVHO0FBQ0g7SUFBQ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lBTUQsc0JBQVcscUNBQU87UUFKbEI7OztXQUdHO2FBQ0g7WUFDSSxJQUFJLENBQUMsSUFBSSxDQUFDLGlCQUFpQixFQUFFO2dCQUN6QixxQ0FBcUM7Z0JBQ3JDLElBQUksQ0FBQyxpQkFBaUIsR0FBRyxVQUFVLEdBQUcsSUFBSSxDQUFDLEdBQUcsRUFBRSxHQUFHLElBQUksQ0FBQyxLQUFLLENBQUMsSUFBSSxDQUFDLE1BQU0sRUFBRSxHQUFHLE9BQU8sQ0FBQyxDQUFDO2FBQzFGO1lBQ0QsT0FBTyxJQUFJLENBQUMsaUJBQWlCLENBQUM7UUFDbEMsQ0FBQzs7O09BQUE7SUFFRDs7T0FFRztJQUNJLGtDQUFPLEdBQWQ7UUFDSSxJQUFJLENBQUMsNEJBQTRCLENBQUMsS0FBSyxFQUFFLENBQUM7UUFDMUMsT0FBTyxJQUFJLENBQUMsNEJBQTRCLENBQUM7SUFDN0MsQ0FBQztJQUNMLHVCQUFDO0FBQUQsQ0FBQyxBQTVHRCxJQTRHQztBQTVHWSw0Q0FBZ0I7QUE4R2hCLFFBQUEsZ0JBQWdCLEdBQUcsSUFBSSxnQkFBZ0IsRUFBRSxDQUFDIn0=
  101777. /***/ }),
  101778. /* 7 */
  101779. /***/ (function(module, exports, __webpack_require__) {
  101780. "use strict";
  101781. Object.defineProperty(exports, "__esModule", { value: true });
  101782. var babylonjs_1 = __webpack_require__(0);
  101783. /**
  101784. * The viewer manager is the container for all viewers currently registered on this page.
  101785. * It is possible to have more than one viewer on a single page.
  101786. */
  101787. var ViewerManager = /** @class */ (function () {
  101788. function ViewerManager() {
  101789. this._viewers = {};
  101790. this.onViewerAddedObservable = new babylonjs_1.Observable();
  101791. this.onViewerRemovedObservable = new babylonjs_1.Observable();
  101792. }
  101793. /**
  101794. * Adding a new viewer to the viewer manager and start tracking it.
  101795. * @param viewer the viewer to add
  101796. */
  101797. ViewerManager.prototype.addViewer = function (viewer) {
  101798. this._viewers[viewer.getBaseId()] = viewer;
  101799. this._onViewerAdded(viewer);
  101800. };
  101801. /**
  101802. * remove a viewer from the viewer manager
  101803. * @param viewer the viewer to remove
  101804. */
  101805. ViewerManager.prototype.removeViewer = function (viewer) {
  101806. var id = viewer.getBaseId();
  101807. delete this._viewers[id];
  101808. this.onViewerRemovedObservable.notifyObservers(id);
  101809. };
  101810. /**
  101811. * 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)
  101812. * @param id the id of the HTMl element (or the viewer's, if none provided)
  101813. */
  101814. ViewerManager.prototype.getViewerById = function (id) {
  101815. return this._viewers[id];
  101816. };
  101817. /**
  101818. * Get a viewer using a container element
  101819. * @param element the HTML element to search viewers associated with
  101820. */
  101821. ViewerManager.prototype.getViewerByHTMLElement = function (element) {
  101822. for (var id in this._viewers) {
  101823. if (this._viewers[id].containerElement === element) {
  101824. return this.getViewerById(id);
  101825. }
  101826. }
  101827. };
  101828. /**
  101829. * Get a promise that will fullfil when this viewer was initialized.
  101830. * Since viewer initialization and template injection is asynchronous, using the promise will guaranty that
  101831. * you will get the viewer after everything was already configured.
  101832. * @param id the viewer id to find
  101833. */
  101834. ViewerManager.prototype.getViewerPromiseById = function (id) {
  101835. var _this = this;
  101836. return new Promise(function (resolve, reject) {
  101837. var localViewer = _this.getViewerById(id);
  101838. if (localViewer) {
  101839. return resolve(localViewer);
  101840. }
  101841. var viewerFunction = function (viewer) {
  101842. if (viewer.getBaseId() === id) {
  101843. resolve(viewer);
  101844. _this.onViewerAddedObservable.removeCallback(viewerFunction);
  101845. }
  101846. };
  101847. _this.onViewerAddedObservable.add(viewerFunction);
  101848. });
  101849. };
  101850. ViewerManager.prototype._onViewerAdded = function (viewer) {
  101851. this.onViewerAdded && this.onViewerAdded(viewer);
  101852. this.onViewerAddedObservable.notifyObservers(viewer);
  101853. };
  101854. /**
  101855. * dispose the manager and all of its associated viewers
  101856. */
  101857. ViewerManager.prototype.dispose = function () {
  101858. delete this._onViewerAdded;
  101859. for (var id in this._viewers) {
  101860. this._viewers[id].dispose();
  101861. }
  101862. this.onViewerAddedObservable.clear();
  101863. this.onViewerRemovedObservable.clear();
  101864. };
  101865. return ViewerManager;
  101866. }());
  101867. exports.ViewerManager = ViewerManager;
  101868. exports.viewerManager = new ViewerManager();
  101869. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidmlld2VyTWFuYWdlci5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uL3NyYy92aWV3ZXIvdmlld2VyTWFuYWdlci50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUFBLHVDQUF1QztBQUd2Qzs7O0dBR0c7QUFDSDtJQWlCSTtRQUNJLElBQUksQ0FBQyxRQUFRLEdBQUcsRUFBRSxDQUFDO1FBQ25CLElBQUksQ0FBQyx1QkFBdUIsR0FBRyxJQUFJLHNCQUFVLEVBQUUsQ0FBQztRQUNoRCxJQUFJLENBQUMseUJBQXlCLEdBQUcsSUFBSSxzQkFBVSxFQUFFLENBQUM7SUFDdEQsQ0FBQztJQUVEOzs7T0FHRztJQUNJLGlDQUFTLEdBQWhCLFVBQWlCLE1BQXNCO1FBQ25DLElBQUksQ0FBQyxRQUFRLENBQUMsTUFBTSxDQUFDLFNBQVMsRUFBRSxDQUFDLEdBQUcsTUFBTSxDQUFDO1FBQzNDLElBQUksQ0FBQyxjQUFjLENBQUMsTUFBTSxDQUFDLENBQUM7SUFDaEMsQ0FBQztJQUVEOzs7T0FHRztJQUNJLG9DQUFZLEdBQW5CLFVBQW9CLE1BQXNCO1FBQ3RDLElBQUksRUFBRSxHQUFHLE1BQU0sQ0FBQyxTQUFTLEVBQUUsQ0FBQztRQUM1QixPQUFPLElBQUksQ0FBQyxRQUFRLENBQUMsRUFBRSxDQUFDLENBQUM7UUFDekIsSUFBSSxDQUFDLHlCQUF5QixDQUFDLGVBQWUsQ0FBQyxFQUFFLENBQUMsQ0FBQztJQUN2RCx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0FBQztRQUNyRCxDQUFDLENBQUMsQ0FBQztJQUNQLENBQUM7SUFFTyxzQ0FBYyxHQUF0QixVQUF1QixNQUFzQjtRQUN6QyxJQUFJLENBQUMsYUFBYSxJQUFJLElBQUksQ0FBQyxhQUFhLENBQUMsTUFBTSxDQUFDLENBQUM7UUFDakQsSUFBSSxDQUFDLHVCQUF1QixDQUFDLGVBQWUsQ0FBQyxNQUFNLENBQUMsQ0FBQztJQUN6RCxDQUFDO0lBRUQ7O09BRUc7SUFDSSwrQkFBTyxHQUFkO1FBQ0ksT0FBTyxJQUFJLENBQUMsY0FBYyxDQUFDO1FBRTNCLEtBQUssSUFBSSxFQUFFLElBQUksSUFBSSxDQUFDLFFBQVEsRUFBRTtZQUMxQixJQUFJLENBQUMsUUFBUSxDQUFDLEVBQUUsQ0FBQyxDQUFDLE9BQU8sRUFBRSxDQUFDO1NBQy9CO1FBRUQsSUFBSSxDQUFDLHVCQUF1QixDQUFDLEtBQUssRUFBRSxDQUFDO1FBQ3JDLElBQUksQ0FBQyx5QkFBeUIsQ0FBQyxLQUFLLEVBQUUsQ0FBQztJQUMzQyxDQUFDO0lBQ0wsb0JBQUM7QUFBRCxDQUFDLEFBdEdELElBc0dDO0FBdEdZLHNDQUFhO0FBd0dmLFFBQUEsYUFBYSxHQUFHLElBQUksYUFBYSxFQUFFLENBQUMifQ==
  101870. /***/ }),
  101871. /* 8 */
  101872. /***/ (function(module, exports, __webpack_require__) {
  101873. "use strict";
  101874. var __extends = (this && this.__extends) || (function () {
  101875. var extendStatics = Object.setPrototypeOf ||
  101876. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  101877. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  101878. return function (d, b) {
  101879. extendStatics(d, b);
  101880. function __() { this.constructor = d; }
  101881. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  101882. };
  101883. })();
  101884. Object.defineProperty(exports, "__esModule", { value: true });
  101885. var viewer_1 = __webpack_require__(9);
  101886. var babylonjs_1 = __webpack_require__(0);
  101887. /**
  101888. * The Default viewer is the default implementation of the AbstractViewer.
  101889. * It uses the templating system to render a new canvas and controls.
  101890. */
  101891. var DefaultViewer = /** @class */ (function (_super) {
  101892. __extends(DefaultViewer, _super);
  101893. /**
  101894. * Create a new default viewer
  101895. * @param containerElement the element in which the templates will be rendered
  101896. * @param initialConfiguration the initial configuration. Defaults to extending the default configuration
  101897. */
  101898. function DefaultViewer(containerElement, initialConfiguration) {
  101899. if (initialConfiguration === void 0) { initialConfiguration = { extends: 'default' }; }
  101900. var _this = _super.call(this, containerElement, initialConfiguration) || this;
  101901. _this.containerElement = containerElement;
  101902. _this._handlePointerDown = function (event) {
  101903. var pointerDown = event.event;
  101904. if (pointerDown.button !== 0)
  101905. return;
  101906. var element = event.event.target;
  101907. if (!element) {
  101908. return;
  101909. }
  101910. var parentClasses = element.parentElement.classList;
  101911. switch (element.id) {
  101912. case "speed-button":
  101913. case "types-button":
  101914. if (parentClasses.contains("open")) {
  101915. parentClasses.remove("open");
  101916. }
  101917. else {
  101918. parentClasses.add("open");
  101919. }
  101920. break;
  101921. case "play-pause-button":
  101922. _this._togglePlayPause();
  101923. break;
  101924. case "label-option-button":
  101925. var label = element.dataset["value"];
  101926. if (label) {
  101927. _this._updateAnimationType(label);
  101928. }
  101929. break;
  101930. case "speed-option-button":
  101931. if (!_this._currentAnimation) {
  101932. return;
  101933. }
  101934. var speed = element.dataset["value"];
  101935. if (speed)
  101936. _this._updateAnimationSpeed(speed);
  101937. break;
  101938. case "progress-wrapper":
  101939. _this._resumePlay = !_this._isAnimationPaused;
  101940. if (_this._resumePlay) {
  101941. _this._togglePlayPause(true);
  101942. }
  101943. break;
  101944. case "fullscreen-button":
  101945. _this.toggleFullscreen();
  101946. break;
  101947. default:
  101948. return;
  101949. }
  101950. };
  101951. /**
  101952. * Plays or Pauses animation
  101953. */
  101954. _this._togglePlayPause = function (noUiUpdate) {
  101955. if (!_this._currentAnimation) {
  101956. return;
  101957. }
  101958. if (_this._isAnimationPaused) {
  101959. _this._currentAnimation.restart();
  101960. }
  101961. else {
  101962. _this._currentAnimation.pause();
  101963. }
  101964. _this._isAnimationPaused = !_this._isAnimationPaused;
  101965. if (noUiUpdate)
  101966. return;
  101967. var navbar = _this.templateManager.getTemplate('navBar');
  101968. if (!navbar)
  101969. return;
  101970. navbar.updateParams({
  101971. paused: _this._isAnimationPaused,
  101972. });
  101973. };
  101974. /**
  101975. * Control progress bar position based on animation current frame
  101976. */
  101977. _this._updateProgressBar = function () {
  101978. var navbar = _this.templateManager.getTemplate('navBar');
  101979. if (!navbar)
  101980. return;
  101981. var progressSlider = navbar.parent.querySelector("input#progress-wrapper");
  101982. if (progressSlider && _this._currentAnimation) {
  101983. var progress = _this._currentAnimation.currentFrame / _this._currentAnimation.frames * 100;
  101984. var currentValue = progressSlider.valueAsNumber;
  101985. if (Math.abs(currentValue - progress) > 0.5) { // Only move if greater than a 1% change
  101986. progressSlider.value = '' + progress;
  101987. }
  101988. if (_this._currentAnimation.state === 1 /* PLAYING */) {
  101989. if (_this.sceneManager.camera.autoRotationBehavior && !_this._oldIdleRotationValue) {
  101990. _this._oldIdleRotationValue = _this.sceneManager.camera.autoRotationBehavior.idleRotationSpeed;
  101991. _this.sceneManager.camera.autoRotationBehavior.idleRotationSpeed = 0;
  101992. }
  101993. }
  101994. else {
  101995. if (_this.sceneManager.camera.autoRotationBehavior && _this._oldIdleRotationValue) {
  101996. _this.sceneManager.camera.autoRotationBehavior.idleRotationSpeed = _this._oldIdleRotationValue;
  101997. _this._oldIdleRotationValue = 0;
  101998. }
  101999. }
  102000. }
  102001. };
  102002. /**
  102003. * Update Current Animation Speed
  102004. */
  102005. _this._updateAnimationSpeed = function (speed, paramsObject) {
  102006. var navbar = _this.templateManager.getTemplate('navBar');
  102007. if (!navbar)
  102008. return;
  102009. if (speed && _this._currentAnimation) {
  102010. _this._currentAnimation.speedRatio = parseFloat(speed);
  102011. if (!_this._isAnimationPaused) {
  102012. _this._currentAnimation.restart();
  102013. }
  102014. if (paramsObject) {
  102015. paramsObject.selectedSpeed = speed + "x";
  102016. }
  102017. else {
  102018. navbar.updateParams({
  102019. selectedSpeed: speed + "x",
  102020. });
  102021. }
  102022. }
  102023. };
  102024. /**
  102025. * Update Current Animation Type
  102026. */
  102027. _this._updateAnimationType = function (label, paramsObject) {
  102028. var navbar = _this.templateManager.getTemplate('navBar');
  102029. if (!navbar)
  102030. return;
  102031. if (label) {
  102032. _this._currentAnimation = _this.sceneManager.models[0].setCurrentAnimationByName(label);
  102033. }
  102034. if (paramsObject) {
  102035. paramsObject.selectedAnimation = (_this._animationList.indexOf(label) + 1);
  102036. paramsObject.selectedAnimationName = label;
  102037. }
  102038. else {
  102039. navbar.updateParams({
  102040. selectedAnimation: (_this._animationList.indexOf(label) + 1),
  102041. selectedAnimationName: label
  102042. });
  102043. }
  102044. _this._updateAnimationSpeed("1.0", paramsObject);
  102045. };
  102046. /**
  102047. * Toggle fullscreen of the entire viewer
  102048. */
  102049. _this.toggleFullscreen = function () {
  102050. var viewerTemplate = _this.templateManager.getTemplate('viewer');
  102051. var viewerElement = viewerTemplate && viewerTemplate.parent;
  102052. if (viewerElement) {
  102053. var fullscreenElement = document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement;
  102054. if (!fullscreenElement) {
  102055. var requestFullScreen = viewerElement.requestFullscreen || viewerElement.webkitRequestFullscreen || viewerElement.msRequestFullscreen || viewerElement.mozRequestFullScreen;
  102056. requestFullScreen.call(viewerElement);
  102057. }
  102058. else {
  102059. var exitFullscreen = document.exitFullscreen || document.webkitExitFullscreen || document.msExitFullscreen || document.mozCancelFullScreen;
  102060. exitFullscreen.call(document);
  102061. }
  102062. }
  102063. };
  102064. _this._onModelLoaded = function (model) {
  102065. _this._configureTemplate(model);
  102066. // with a short timeout, making sure everything is there already.
  102067. var hideLoadingDelay = 20;
  102068. if (_this.configuration.lab && _this.configuration.lab.hideLoadingDelay !== undefined) {
  102069. hideLoadingDelay = _this.configuration.lab.hideLoadingDelay;
  102070. }
  102071. setTimeout(function () {
  102072. _this.sceneManager.scene.executeWhenReady(function () {
  102073. _this.hideLoadingScreen();
  102074. });
  102075. }, hideLoadingDelay);
  102076. return;
  102077. };
  102078. _this.onModelLoadedObservable.add(_this._onModelLoaded);
  102079. _this.onModelRemovedObservable.add(function () {
  102080. _this._configureTemplate();
  102081. });
  102082. _this.onEngineInitObservable.add(function () {
  102083. _this.sceneManager.onLightsConfiguredObservable.add(function (data) {
  102084. _this._configureLights(data.newConfiguration, data.model);
  102085. });
  102086. });
  102087. return _this;
  102088. }
  102089. /**
  102090. * This will be executed when the templates initialize.
  102091. */
  102092. DefaultViewer.prototype._onTemplatesLoaded = function () {
  102093. var _this = this;
  102094. this.showLoadingScreen();
  102095. // navbar
  102096. this._initNavbar();
  102097. // close overlay button
  102098. var closeButton = document.getElementById('close-button');
  102099. if (closeButton) {
  102100. closeButton.addEventListener('pointerdown', function () {
  102101. _this.hideOverlayScreen();
  102102. });
  102103. }
  102104. if (this.configuration.templates && this.configuration.templates.viewer) {
  102105. if (this.configuration.templates.viewer.params && this.configuration.templates.viewer.params.enableDragAndDrop) {
  102106. var filesInput = new babylonjs_1.FilesInput(this.engine, this.sceneManager.scene, function () {
  102107. }, function () {
  102108. }, function () {
  102109. }, function () {
  102110. }, function () {
  102111. }, function (file) {
  102112. _this.loadModel(file);
  102113. }, function () {
  102114. });
  102115. filesInput.monitorElementForDragNDrop(this.templateManager.getCanvas());
  102116. }
  102117. }
  102118. return _super.prototype._onTemplatesLoaded.call(this);
  102119. };
  102120. DefaultViewer.prototype._dropped = function (evt) {
  102121. };
  102122. DefaultViewer.prototype._initNavbar = function () {
  102123. var _this = this;
  102124. var navbar = this.templateManager.getTemplate('navBar');
  102125. if (navbar) {
  102126. this.onFrameRenderedObservable.add(this._updateProgressBar);
  102127. this.templateManager.eventManager.registerCallback('navBar', this._handlePointerDown, 'pointerdown');
  102128. // an example how to trigger the help button. publiclly available
  102129. this.templateManager.eventManager.registerCallback("navBar", function () {
  102130. // do your thing
  102131. }, "pointerdown", "#help-button");
  102132. this.templateManager.eventManager.registerCallback("navBar", function (event) {
  102133. var evt = event.event;
  102134. var element = (evt.target);
  102135. if (!_this._currentAnimation)
  102136. return;
  102137. var gotoFrame = +element.value / 100 * _this._currentAnimation.frames;
  102138. if (isNaN(gotoFrame))
  102139. return;
  102140. _this._currentAnimation.goToFrame(gotoFrame);
  102141. }, "input");
  102142. this.templateManager.eventManager.registerCallback("navBar", function (e) {
  102143. if (_this._resumePlay) {
  102144. _this._togglePlayPause(true);
  102145. }
  102146. _this._resumePlay = false;
  102147. }, "pointerup", "#progress-wrapper");
  102148. }
  102149. };
  102150. /**
  102151. * Preparing the container element to present the viewer
  102152. */
  102153. DefaultViewer.prototype._prepareContainerElement = function () {
  102154. this.containerElement.style.position = 'relative';
  102155. this.containerElement.style.height = '100%';
  102156. this.containerElement.style.display = 'flex';
  102157. };
  102158. /**
  102159. * This function will configure the templates and update them after a model was loaded
  102160. * It is mainly responsible to changing the title and subtitle etc'.
  102161. * @param model the model to be used to configure the templates by
  102162. */
  102163. DefaultViewer.prototype._configureTemplate = function (model) {
  102164. var navbar = this.templateManager.getTemplate('navBar');
  102165. if (!navbar)
  102166. return;
  102167. var newParams = navbar.configuration.params || {};
  102168. if (!model) {
  102169. newParams.animations = null;
  102170. }
  102171. else {
  102172. var animationNames = model.getAnimationNames();
  102173. newParams.animations = animationNames;
  102174. if (animationNames.length) {
  102175. this._isAnimationPaused = (model.configuration.animation && !model.configuration.animation.autoStart) || !model.configuration.animation;
  102176. this._animationList = animationNames;
  102177. newParams.paused = this._isAnimationPaused;
  102178. var animationIndex = 0;
  102179. if (model.configuration.animation && typeof model.configuration.animation.autoStart === 'string') {
  102180. animationIndex = animationNames.indexOf(model.configuration.animation.autoStart);
  102181. if (animationIndex === -1) {
  102182. animationIndex = 0;
  102183. }
  102184. }
  102185. this._updateAnimationType(animationNames[animationIndex], newParams);
  102186. }
  102187. else {
  102188. newParams.animations = null;
  102189. }
  102190. if (model.configuration.thumbnail) {
  102191. newParams.logoImage = model.configuration.thumbnail;
  102192. }
  102193. }
  102194. navbar.updateParams(newParams, false);
  102195. };
  102196. /**
  102197. * This will load a new model to the default viewer
  102198. * overriding the AbstractViewer's loadModel.
  102199. * The scene will automatically be cleared of the old models, if exist.
  102200. * @param model the configuration object (or URL) to load.
  102201. */
  102202. DefaultViewer.prototype.loadModel = function (model) {
  102203. var _this = this;
  102204. if (!model) {
  102205. model = this.configuration.model;
  102206. }
  102207. this.showLoadingScreen();
  102208. return _super.prototype.loadModel.call(this, model, true).catch(function (error) {
  102209. console.log(error);
  102210. _this.hideLoadingScreen();
  102211. _this.showOverlayScreen('error');
  102212. return Promise.reject(error);
  102213. });
  102214. };
  102215. /**
  102216. * Show the overlay and the defined sub-screen.
  102217. * Mainly used for help and errors
  102218. * @param subScreen the name of the subScreen. Those can be defined in the configuration object
  102219. */
  102220. DefaultViewer.prototype.showOverlayScreen = function (subScreen) {
  102221. var _this = this;
  102222. var template = this.templateManager.getTemplate('overlay');
  102223. if (!template)
  102224. return Promise.resolve('Overlay template not found');
  102225. return template.show((function (template) {
  102226. var canvasRect = _this.containerElement.getBoundingClientRect();
  102227. template.parent.style.display = 'flex';
  102228. template.parent.style.width = canvasRect.width + "px";
  102229. template.parent.style.height = canvasRect.height + "px";
  102230. template.parent.style.opacity = "1";
  102231. var subTemplate = _this.templateManager.getTemplate(subScreen);
  102232. if (!subTemplate) {
  102233. return Promise.reject(subScreen + ' template not found');
  102234. }
  102235. return subTemplate.show((function (template) {
  102236. template.parent.style.display = 'flex';
  102237. return Promise.resolve(template);
  102238. }));
  102239. }));
  102240. };
  102241. /**
  102242. * Hide the overlay screen.
  102243. */
  102244. DefaultViewer.prototype.hideOverlayScreen = function () {
  102245. var template = this.templateManager.getTemplate('overlay');
  102246. if (!template)
  102247. return Promise.resolve('Overlay template not found');
  102248. return template.hide((function (template) {
  102249. template.parent.style.opacity = "0";
  102250. var onTransitionEnd = function () {
  102251. template.parent.removeEventListener("transitionend", onTransitionEnd);
  102252. template.parent.style.display = 'none';
  102253. };
  102254. template.parent.addEventListener("transitionend", onTransitionEnd);
  102255. var overlays = template.parent.querySelectorAll('.overlay');
  102256. if (overlays) {
  102257. for (var i = 0; i < overlays.length; ++i) {
  102258. var htmlElement = overlays.item(i);
  102259. htmlElement.style.display = 'none';
  102260. }
  102261. }
  102262. return Promise.resolve(template);
  102263. }));
  102264. };
  102265. /**
  102266. * show the viewer (in case it was hidden)
  102267. *
  102268. * @param visibilityFunction an optional function to execute in order to show the container
  102269. */
  102270. DefaultViewer.prototype.show = function (visibilityFunction) {
  102271. var template = this.templateManager.getTemplate('main');
  102272. //not possible, but yet:
  102273. if (!template)
  102274. return Promise.reject('Main template not found');
  102275. return template.show(visibilityFunction);
  102276. };
  102277. /**
  102278. * hide the viewer (in case it is visible)
  102279. *
  102280. * @param visibilityFunction an optional function to execute in order to hide the container
  102281. */
  102282. DefaultViewer.prototype.hide = function (visibilityFunction) {
  102283. var template = this.templateManager.getTemplate('main');
  102284. //not possible, but yet:
  102285. if (!template)
  102286. return Promise.reject('Main template not found');
  102287. return template.hide(visibilityFunction);
  102288. };
  102289. /**
  102290. * Show the loading screen.
  102291. * The loading screen can be configured using the configuration object
  102292. */
  102293. DefaultViewer.prototype.showLoadingScreen = function () {
  102294. var _this = this;
  102295. var template = this.templateManager.getTemplate('loadingScreen');
  102296. if (!template)
  102297. return Promise.resolve('Loading Screen template not found');
  102298. return template.show((function (template) {
  102299. var canvasRect = _this.containerElement.getBoundingClientRect();
  102300. // var canvasPositioning = window.getComputedStyle(this.containerElement).position;
  102301. template.parent.style.display = 'flex';
  102302. template.parent.style.width = canvasRect.width + "px";
  102303. template.parent.style.height = canvasRect.height + "px";
  102304. template.parent.style.opacity = "1";
  102305. // from the configuration!!!
  102306. var color = "black";
  102307. if (_this.configuration.templates && _this.configuration.templates.loadingScreen) {
  102308. color = (_this.configuration.templates.loadingScreen.params &&
  102309. _this.configuration.templates.loadingScreen.params.backgroundColor) || color;
  102310. }
  102311. template.parent.style.backgroundColor = color;
  102312. return Promise.resolve(template);
  102313. }));
  102314. };
  102315. /**
  102316. * Hide the loading screen
  102317. */
  102318. DefaultViewer.prototype.hideLoadingScreen = function () {
  102319. var template = this.templateManager.getTemplate('loadingScreen');
  102320. if (!template)
  102321. return Promise.resolve('Loading Screen template not found');
  102322. return template.hide((function (template) {
  102323. template.parent.style.opacity = "0";
  102324. var onTransitionEnd = function () {
  102325. template.parent.removeEventListener("transitionend", onTransitionEnd);
  102326. template.parent.style.display = 'none';
  102327. };
  102328. template.parent.addEventListener("transitionend", onTransitionEnd);
  102329. return Promise.resolve(template);
  102330. }));
  102331. };
  102332. DefaultViewer.prototype.dispose = function () {
  102333. this.templateManager.dispose();
  102334. _super.prototype.dispose.call(this);
  102335. };
  102336. DefaultViewer.prototype._onConfigurationLoaded = function (configuration) {
  102337. var _this = this;
  102338. _super.prototype._onConfigurationLoaded.call(this, configuration);
  102339. // initialize the templates
  102340. var templateConfiguration = this.configuration.templates || {};
  102341. this.templateManager.initTemplate(templateConfiguration);
  102342. // when done, execute onTemplatesLoaded()
  102343. this.templateManager.onAllLoaded.add(function () {
  102344. var canvas = _this.templateManager.getCanvas();
  102345. if (canvas) {
  102346. _this._canvas = canvas;
  102347. }
  102348. _this._onTemplateLoaded();
  102349. });
  102350. };
  102351. /**
  102352. * An extension of the light configuration of the abstract viewer.
  102353. * @param lightsConfiguration the light configuration to use
  102354. * @param model the model that will be used to configure the lights (if the lights are model-dependant)
  102355. */
  102356. DefaultViewer.prototype._configureLights = function (lightsConfiguration, model) {
  102357. var _this = this;
  102358. if (lightsConfiguration === void 0) { lightsConfiguration = {}; }
  102359. // labs feature - flashlight
  102360. if (this.configuration.lab && this.configuration.lab.flashlight) {
  102361. var pointerPosition = babylonjs_1.Vector3.Zero();
  102362. var lightTarget_1;
  102363. var angle = 0.5;
  102364. var exponent = Math.PI / 2;
  102365. if (typeof this.configuration.lab.flashlight === "object") {
  102366. exponent = this.configuration.lab.flashlight.exponent || exponent;
  102367. angle = this.configuration.lab.flashlight.angle || angle;
  102368. }
  102369. var flashlight = new babylonjs_1.SpotLight("flashlight", babylonjs_1.Vector3.Zero(), babylonjs_1.Vector3.Zero(), exponent, angle, this.sceneManager.scene);
  102370. if (typeof this.configuration.lab.flashlight === "object") {
  102371. flashlight.intensity = this.configuration.lab.flashlight.intensity || flashlight.intensity;
  102372. if (this.configuration.lab.flashlight.diffuse) {
  102373. flashlight.diffuse.r = this.configuration.lab.flashlight.diffuse.r;
  102374. flashlight.diffuse.g = this.configuration.lab.flashlight.diffuse.g;
  102375. flashlight.diffuse.b = this.configuration.lab.flashlight.diffuse.b;
  102376. }
  102377. if (this.configuration.lab.flashlight.specular) {
  102378. flashlight.specular.r = this.configuration.lab.flashlight.specular.r;
  102379. flashlight.specular.g = this.configuration.lab.flashlight.specular.g;
  102380. flashlight.specular.b = this.configuration.lab.flashlight.specular.b;
  102381. }
  102382. }
  102383. this.sceneManager.scene.constantlyUpdateMeshUnderPointer = true;
  102384. this.sceneManager.scene.onPointerObservable.add(function (eventData, eventState) {
  102385. if (eventData.type === 4 && eventData.pickInfo) {
  102386. lightTarget_1 = (eventData.pickInfo.pickedPoint);
  102387. }
  102388. else {
  102389. lightTarget_1 = undefined;
  102390. }
  102391. });
  102392. var updateFlashlightFunction = function () {
  102393. if (_this.sceneManager.camera && flashlight) {
  102394. flashlight.position.copyFrom(_this.sceneManager.camera.position);
  102395. if (lightTarget_1) {
  102396. lightTarget_1.subtractToRef(flashlight.position, flashlight.direction);
  102397. }
  102398. }
  102399. };
  102400. this.sceneManager.scene.registerBeforeRender(updateFlashlightFunction);
  102401. this._registeredOnBeforeRenderFunctions.push(updateFlashlightFunction);
  102402. }
  102403. };
  102404. return DefaultViewer;
  102405. }(viewer_1.AbstractViewer));
  102406. exports.Default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Q0FBYSJ9
  102408. /***/ }),
  102409. /* 9 */
  102410. /***/ (function(module, exports, __webpack_require__) {
  102411. "use strict";
  102412. Object.defineProperty(exports, "__esModule", { value: true });
  102413. var viewerManager_1 = __webpack_require__(7);
  102414. var sceneManager_1 = __webpack_require__(22);
  102415. var loader_1 = __webpack_require__(28);
  102416. var babylonjs_1 = __webpack_require__(0);
  102417. var modelLoader_1 = __webpack_require__(13);
  102418. var globals_1 = __webpack_require__(4);
  102419. var telemetryManager_1 = __webpack_require__(6);
  102420. var _1 = __webpack_require__(1);
  102421. var observablesManager_1 = __webpack_require__(59);
  102422. var configurationContainer_1 = __webpack_require__(60);
  102423. var templateManager_1 = __webpack_require__(61);
  102424. /**
  102425. * The AbstractViewr is the center of Babylon's viewer.
  102426. * It is the basic implementation of the default viewer and is responsible of loading and showing the model and the templates
  102427. */
  102428. var AbstractViewer = /** @class */ (function () {
  102429. function AbstractViewer(containerElement, initialConfiguration) {
  102430. if (initialConfiguration === void 0) { initialConfiguration = {}; }
  102431. var _this = this;
  102432. this.containerElement = containerElement;
  102433. /**
  102434. * A flag that controls whether or not the render loop should be executed
  102435. */
  102436. this.runRenderLoop = true;
  102437. /**
  102438. * is this viewer disposed?
  102439. */
  102440. this._isDisposed = false;
  102441. /**
  102442. * The resize function that will be registered with the window object
  102443. */
  102444. this._resize = function () {
  102445. // Only resize if Canvas is in the DOM
  102446. if (!_this.isCanvasInDOM()) {
  102447. return;
  102448. }
  102449. if (_this.canvas.clientWidth <= 0 || _this.canvas.clientHeight <= 0) {
  102450. return;
  102451. }
  102452. if (_this.configuration.engine && _this.configuration.engine.disableResize) {
  102453. return;
  102454. }
  102455. _this.engine.resize();
  102456. };
  102457. /**
  102458. * render loop that will be executed by the engine
  102459. */
  102460. this._render = function (force) {
  102461. if (force === void 0) { force = false; }
  102462. if (force || (_this.sceneManager.scene && _this.sceneManager.scene.activeCamera)) {
  102463. if (_this.runRenderLoop || force) {
  102464. _this.engine.performanceMonitor.enable();
  102465. _this.sceneManager.scene.render();
  102466. _this.onFrameRenderedObservable.notifyObservers(_this);
  102467. }
  102468. else {
  102469. _this.engine.performanceMonitor.disable();
  102470. // update camera instead of rendering
  102471. _this.sceneManager.scene.activeCamera && _this.sceneManager.scene.activeCamera.update();
  102472. }
  102473. }
  102474. };
  102475. // if exists, use the container id. otherwise, generate a random string.
  102476. if (containerElement.id) {
  102477. this.baseId = containerElement.id;
  102478. }
  102479. else {
  102480. this.baseId = containerElement.id = 'bjs' + Math.random().toString(32).substr(2, 8);
  102481. }
  102482. this._registeredOnBeforeRenderFunctions = [];
  102483. this._configurationContainer = new configurationContainer_1.ConfigurationContainer();
  102484. // add this viewer to the viewer manager
  102485. viewerManager_1.viewerManager.addViewer(this);
  102486. this.observablesManager = new observablesManager_1.ObservablesManager();
  102487. this.modelLoader = new modelLoader_1.ModelLoader(this.observablesManager, this._configurationContainer);
  102488. babylonjs_1.RenderingManager.AUTOCLEAR = false;
  102489. // extend the configuration
  102490. this._configurationLoader = new loader_1.ConfigurationLoader();
  102491. this._configurationLoader.loadConfiguration(initialConfiguration, function (configuration) {
  102492. _this._onConfigurationLoaded(configuration);
  102493. });
  102494. this.onSceneInitObservable.add(function () {
  102495. _this.updateConfiguration();
  102496. });
  102497. this.onInitDoneObservable.add(function () {
  102498. _this._isInit = true;
  102499. _this.engine.runRenderLoop(_this._render);
  102500. });
  102501. this._prepareContainerElement();
  102502. }
  102503. Object.defineProperty(AbstractViewer.prototype, "onSceneInitObservable", {
  102504. // observables
  102505. /**
  102506. * Will notify when the scene was initialized
  102507. */
  102508. get: function () {
  102509. return this.observablesManager.onSceneInitObservable;
  102510. },
  102511. enumerable: true,
  102512. configurable: true
  102513. });
  102514. Object.defineProperty(AbstractViewer.prototype, "onEngineInitObservable", {
  102515. /**
  102516. * will notify when the engine was initialized
  102517. */
  102518. get: function () {
  102519. return this.observablesManager.onEngineInitObservable;
  102520. },
  102521. enumerable: true,
  102522. configurable: true
  102523. });
  102524. Object.defineProperty(AbstractViewer.prototype, "onModelAddedObservable", {
  102525. /**
  102526. * Will notify when a new model was added to the scene.
  102527. * Note that added does not neccessarily mean loaded!
  102528. */
  102529. get: function () {
  102530. return this.observablesManager.onModelAddedObservable;
  102531. },
  102532. enumerable: true,
  102533. configurable: true
  102534. });
  102535. Object.defineProperty(AbstractViewer.prototype, "onModelLoadedObservable", {
  102536. /**
  102537. * will notify after every model load
  102538. */
  102539. get: function () {
  102540. return this.observablesManager.onModelLoadedObservable;
  102541. },
  102542. enumerable: true,
  102543. configurable: true
  102544. });
  102545. Object.defineProperty(AbstractViewer.prototype, "onModelLoadProgressObservable", {
  102546. /**
  102547. * will notify when any model notify of progress
  102548. */
  102549. get: function () {
  102550. return this.observablesManager.onModelLoadProgressObservable;
  102551. },
  102552. enumerable: true,
  102553. configurable: true
  102554. });
  102555. Object.defineProperty(AbstractViewer.prototype, "onModelLoadErrorObservable", {
  102556. /**
  102557. * will notify when any model load failed.
  102558. */
  102559. get: function () {
  102560. return this.observablesManager.onModelLoadErrorObservable;
  102561. },
  102562. enumerable: true,
  102563. configurable: true
  102564. });
  102565. Object.defineProperty(AbstractViewer.prototype, "onModelRemovedObservable", {
  102566. /**
  102567. * Will notify when a model was removed from the scene;
  102568. */
  102569. get: function () {
  102570. return this.observablesManager.onModelRemovedObservable;
  102571. },
  102572. enumerable: true,
  102573. configurable: true
  102574. });
  102575. Object.defineProperty(AbstractViewer.prototype, "onLoaderInitObservable", {
  102576. /**
  102577. * will notify when a new loader was initialized.
  102578. * Used mainly to know when a model starts loading.
  102579. */
  102580. get: function () {
  102581. return this.observablesManager.onLoaderInitObservable;
  102582. },
  102583. enumerable: true,
  102584. configurable: true
  102585. });
  102586. Object.defineProperty(AbstractViewer.prototype, "onInitDoneObservable", {
  102587. /**
  102588. * Observers registered here will be executed when the entire load process has finished.
  102589. */
  102590. get: function () {
  102591. return this.observablesManager.onViewerInitDoneObservable;
  102592. },
  102593. enumerable: true,
  102594. configurable: true
  102595. });
  102596. Object.defineProperty(AbstractViewer.prototype, "onFrameRenderedObservable", {
  102597. /**
  102598. * Functions added to this observable will be executed on each frame rendered.
  102599. */
  102600. get: function () {
  102601. return this.observablesManager.onFrameRenderedObservable;
  102602. },
  102603. enumerable: true,
  102604. configurable: true
  102605. });
  102606. Object.defineProperty(AbstractViewer.prototype, "canvas", {
  102607. /**
  102608. * The (single) canvas of this viewer
  102609. */
  102610. get: function () {
  102611. return this._canvas;
  102612. },
  102613. enumerable: true,
  102614. configurable: true
  102615. });
  102616. Object.defineProperty(AbstractViewer.prototype, "configurationContainer", {
  102617. get: function () {
  102618. return this._configurationContainer;
  102619. },
  102620. enumerable: true,
  102621. configurable: true
  102622. });
  102623. /**
  102624. * get the baseId of this viewer
  102625. */
  102626. AbstractViewer.prototype.getBaseId = function () {
  102627. return this.baseId;
  102628. };
  102629. /**
  102630. * Do we have a canvas to render on, and is it a part of the scene
  102631. */
  102632. AbstractViewer.prototype.isCanvasInDOM = function () {
  102633. return !!this._canvas && !!this._canvas.parentElement;
  102634. };
  102635. Object.defineProperty(AbstractViewer.prototype, "renderInBackground", {
  102636. /**
  102637. * Is the engine currently set to rende even when the page is in background
  102638. */
  102639. get: function () {
  102640. return this.engine && this.engine.renderEvenInBackground;
  102641. },
  102642. /**
  102643. * Set the viewer's background rendering flag.
  102644. */
  102645. set: function (value) {
  102646. if (this.engine) {
  102647. this.engine.renderEvenInBackground = value;
  102648. }
  102649. },
  102650. enumerable: true,
  102651. configurable: true
  102652. });
  102653. Object.defineProperty(AbstractViewer.prototype, "configuration", {
  102654. /**
  102655. * Get the configuration object. This is a reference only.
  102656. * The configuration can ONLY be updated using the updateConfiguration function.
  102657. * changing this object will have no direct effect on the scene.
  102658. */
  102659. get: function () {
  102660. return this._configurationContainer.configuration;
  102661. },
  102662. enumerable: true,
  102663. configurable: true
  102664. });
  102665. /**
  102666. * force resizing the engine.
  102667. */
  102668. AbstractViewer.prototype.forceResize = function () {
  102669. this._resize();
  102670. };
  102671. AbstractViewer.prototype._onConfigurationLoaded = function (configuration) {
  102672. var _this = this;
  102673. this._configurationContainer.configuration = _1.deepmerge(this.configuration || {}, configuration);
  102674. if (this.configuration.observers) {
  102675. this._configureObservers(this.configuration.observers);
  102676. }
  102677. // TODO remove this after testing, as this is done in the updateCOnfiguration as well.
  102678. if (this.configuration.loaderPlugins) {
  102679. Object.keys(this.configuration.loaderPlugins).forEach((function (name) {
  102680. if (_this.configuration.loaderPlugins && _this.configuration.loaderPlugins[name]) {
  102681. _this.modelLoader.addPlugin(name);
  102682. }
  102683. }));
  102684. }
  102685. this.templateManager = new templateManager_1.TemplateManager(this.containerElement);
  102686. };
  102687. /**
  102688. * Force a single render loop execution.
  102689. */
  102690. AbstractViewer.prototype.forceRender = function () {
  102691. this._render(true);
  102692. };
  102693. /**
  102694. * Takes a screenshot of the scene and returns it as a base64 encoded png.
  102695. * @param callback optional callback that will be triggered when screenshot is done.
  102696. * @param width Optional screenshot width (default to 512).
  102697. * @param height Optional screenshot height (default to 512).
  102698. * @returns a promise with the screenshot data
  102699. */
  102700. AbstractViewer.prototype.takeScreenshot = function (callback, width, height) {
  102701. var _this = this;
  102702. if (width === void 0) { width = 0; }
  102703. if (height === void 0) { height = 0; }
  102704. width = width || this.canvas.clientWidth;
  102705. height = height || this.canvas.clientHeight;
  102706. // Create the screenshot
  102707. return new Promise(function (resolve, reject) {
  102708. try {
  102709. BABYLON.Tools.CreateScreenshot(_this.engine, _this.sceneManager.camera, { width: width, height: height }, function (data) {
  102710. if (callback) {
  102711. callback(data);
  102712. }
  102713. resolve(data);
  102714. });
  102715. }
  102716. catch (e) {
  102717. reject(e);
  102718. }
  102719. });
  102720. };
  102721. /**
  102722. * Update the current viewer configuration with new values.
  102723. * Only provided information will be updated, old configuration values will be kept.
  102724. * If this.configuration was manually changed, you can trigger this function with no parameters,
  102725. * and the entire configuration will be updated.
  102726. * @param newConfiguration the partial configuration to update
  102727. *
  102728. */
  102729. AbstractViewer.prototype.updateConfiguration = function (newConfiguration) {
  102730. var _this = this;
  102731. if (newConfiguration === void 0) { newConfiguration = this.configuration; }
  102732. // update this.configuration with the new data
  102733. this._configurationContainer.configuration = _1.deepmerge(this.configuration || {}, newConfiguration);
  102734. this.sceneManager.updateConfiguration(newConfiguration);
  102735. // observers in configuration
  102736. if (newConfiguration.observers) {
  102737. this._configureObservers(newConfiguration.observers);
  102738. }
  102739. if (newConfiguration.loaderPlugins) {
  102740. Object.keys(newConfiguration.loaderPlugins).forEach((function (name) {
  102741. if (newConfiguration.loaderPlugins && newConfiguration.loaderPlugins[name]) {
  102742. _this.modelLoader.addPlugin(name);
  102743. }
  102744. }));
  102745. }
  102746. };
  102747. /**
  102748. * this is used to register native functions using the configuration object.
  102749. * This will configure the observers.
  102750. * @param observersConfiguration observers configuration
  102751. */
  102752. AbstractViewer.prototype._configureObservers = function (observersConfiguration) {
  102753. if (observersConfiguration.onEngineInit) {
  102754. this.onEngineInitObservable.add(window[observersConfiguration.onEngineInit]);
  102755. }
  102756. else {
  102757. if (observersConfiguration.onEngineInit === '' && this.configuration.observers && this.configuration.observers.onEngineInit) {
  102758. this.onEngineInitObservable.removeCallback(window[this.configuration.observers.onEngineInit]);
  102759. }
  102760. }
  102761. if (observersConfiguration.onSceneInit) {
  102762. this.onSceneInitObservable.add(window[observersConfiguration.onSceneInit]);
  102763. }
  102764. else {
  102765. if (observersConfiguration.onSceneInit === '' && this.configuration.observers && this.configuration.observers.onSceneInit) {
  102766. this.onSceneInitObservable.removeCallback(window[this.configuration.observers.onSceneInit]);
  102767. }
  102768. }
  102769. if (observersConfiguration.onModelLoaded) {
  102770. this.onModelLoadedObservable.add(window[observersConfiguration.onModelLoaded]);
  102771. }
  102772. else {
  102773. if (observersConfiguration.onModelLoaded === '' && this.configuration.observers && this.configuration.observers.onModelLoaded) {
  102774. this.onModelLoadedObservable.removeCallback(window[this.configuration.observers.onModelLoaded]);
  102775. }
  102776. }
  102777. };
  102778. /**
  102779. * Dispoe the entire viewer including the scene and the engine
  102780. */
  102781. AbstractViewer.prototype.dispose = function () {
  102782. if (this._isDisposed) {
  102783. return;
  102784. }
  102785. window.removeEventListener('resize', this._resize);
  102786. if (this.sceneManager) {
  102787. if (this.sceneManager.scene && this.sceneManager.scene.activeCamera) {
  102788. this.sceneManager.scene.activeCamera.detachControl(this.canvas);
  102789. }
  102790. this.sceneManager.dispose();
  102791. }
  102792. this._fpsTimeoutInterval && clearInterval(this._fpsTimeoutInterval);
  102793. this.observablesManager.dispose();
  102794. this.modelLoader.dispose();
  102795. if (this.engine) {
  102796. this.engine.dispose();
  102797. }
  102798. viewerManager_1.viewerManager.removeViewer(this);
  102799. this._isDisposed = true;
  102800. };
  102801. /**
  102802. * This function will execute when the HTML templates finished initializing.
  102803. * It should initialize the engine and continue execution.
  102804. *
  102805. * @returns {Promise<AbstractViewer>} The viewer object will be returned after the object was loaded.
  102806. */
  102807. AbstractViewer.prototype._onTemplatesLoaded = function () {
  102808. return Promise.resolve(this);
  102809. };
  102810. /**
  102811. * This will force the creation of an engine and a scene.
  102812. * It will also load a model if preconfigured.
  102813. * But first - it will load the extendible onTemplateLoaded()!
  102814. */
  102815. AbstractViewer.prototype._onTemplateLoaded = function () {
  102816. var _this = this;
  102817. // check if viewer was disposed right after created
  102818. if (this._isDisposed) {
  102819. return Promise.reject("viewer was disposed");
  102820. }
  102821. return this._onTemplatesLoaded().then(function () {
  102822. var autoLoad = typeof _this.configuration.model === 'string' || (_this.configuration.model && _this.configuration.model.url);
  102823. return _this._initEngine().then(function (engine) {
  102824. return _this.onEngineInitObservable.notifyObserversWithPromise(engine);
  102825. }).then(function () {
  102826. _this._initTelemetryEvents();
  102827. if (autoLoad) {
  102828. return _this.loadModel(_this.configuration.model).catch(function (e) { }).then(function () { return _this.sceneManager.scene; });
  102829. }
  102830. else {
  102831. return _this.sceneManager.scene || _this.sceneManager.initScene(_this.configuration.scene);
  102832. }
  102833. }).then(function () {
  102834. return _this.onInitDoneObservable.notifyObserversWithPromise(_this);
  102835. }).catch(function (e) {
  102836. babylonjs_1.Tools.Warn(e.toString());
  102837. return _this;
  102838. });
  102839. });
  102840. };
  102841. /**
  102842. * Initialize the engine. Retruns a promise in case async calls are needed.
  102843. *
  102844. * @protected
  102845. * @returns {Promise<Engine>}
  102846. * @memberof Viewer
  102847. */
  102848. AbstractViewer.prototype._initEngine = function () {
  102849. // init custom shaders
  102850. this._injectCustomShaders();
  102851. //let canvasElement = this.templateManager.getCanvas();
  102852. if (!this.canvas) {
  102853. return Promise.reject('Canvas element not found!');
  102854. }
  102855. var config = this.configuration.engine || {};
  102856. // TDO enable further configuration
  102857. // check for webgl2 support, force-disable if needed.
  102858. if (globals_1.viewerGlobals.disableWebGL2Support) {
  102859. config.engineOptions = config.engineOptions || {};
  102860. config.engineOptions.disableWebGL2Support = true;
  102861. }
  102862. this.engine = new babylonjs_1.Engine(this.canvas, !!config.antialiasing, config.engineOptions);
  102863. // Disable manifest checking
  102864. babylonjs_1.Database.IDBStorageEnabled = false;
  102865. if (!config.disableResize) {
  102866. window.addEventListener('resize', this._resize);
  102867. }
  102868. if (this.configuration.engine && this.configuration.engine.adaptiveQuality) {
  102869. var scale = Math.max(0.5, 1 / (window.devicePixelRatio || 2));
  102870. this.engine.setHardwareScalingLevel(scale);
  102871. }
  102872. // create a new template manager for this viewer
  102873. this.sceneManager = new sceneManager_1.SceneManager(this.engine, this._configurationContainer, this.observablesManager);
  102874. return Promise.resolve(this.engine);
  102875. };
  102876. /**
  102877. * Initialize a model loading. The returned object (a ViewerModel object) will be loaded in the background.
  102878. * The difference between this and loadModel is that loadModel will fulfill the promise when the model finished loading.
  102879. *
  102880. * @param modelConfig model configuration to use when loading the model.
  102881. * @param clearScene should the scene be cleared before loading this model
  102882. * @returns a ViewerModel object that is not yet fully loaded.
  102883. */
  102884. AbstractViewer.prototype.initModel = function (modelConfig, clearScene) {
  102885. var _this = this;
  102886. if (clearScene === void 0) { clearScene = true; }
  102887. var configuration;
  102888. if (typeof modelConfig === 'string') {
  102889. configuration = {
  102890. url: modelConfig
  102891. };
  102892. }
  102893. else if (modelConfig instanceof File) {
  102894. configuration = {
  102895. file: modelConfig,
  102896. root: "file:"
  102897. };
  102898. }
  102899. else {
  102900. configuration = modelConfig;
  102901. }
  102902. if (!configuration.url && !configuration.file) {
  102903. throw new Error("no model provided");
  102904. }
  102905. if (clearScene) {
  102906. this.sceneManager.clearScene(true, false);
  102907. }
  102908. //merge the configuration for future models:
  102909. if (this.configuration.model && typeof this.configuration.model === 'object') {
  102910. var globalConfig = _1.deepmerge({}, this.configuration.model);
  102911. configuration = _1.deepmerge(globalConfig, configuration);
  102912. if (modelConfig instanceof File) {
  102913. configuration.file = modelConfig;
  102914. }
  102915. }
  102916. else {
  102917. this.configuration.model = configuration;
  102918. }
  102919. this._isLoading = true;
  102920. var model = this.modelLoader.load(configuration);
  102921. this.lastUsedLoader = model.loader;
  102922. model.onLoadErrorObservable.add(function (errorObject) {
  102923. _this.onModelLoadErrorObservable.notifyObserversWithPromise(errorObject);
  102924. });
  102925. model.onLoadProgressObservable.add(function (progressEvent) {
  102926. _this.onModelLoadProgressObservable.notifyObserversWithPromise(progressEvent);
  102927. });
  102928. this.onLoaderInitObservable.notifyObserversWithPromise(this.lastUsedLoader);
  102929. model.onLoadedObservable.add(function () {
  102930. _this._isLoading = false;
  102931. });
  102932. return model;
  102933. };
  102934. /**
  102935. * load a model using the provided configuration.
  102936. * This function, as opposed to initModel, will return a promise that resolves when the model is loaded, and rejects with error.
  102937. * If you want to attach to the observables of the model, use initModle instead.
  102938. *
  102939. * @param modelConfig the model configuration or URL to load.
  102940. * @param clearScene Should the scene be cleared before loading the model
  102941. * @returns a Promise the fulfills when the model finished loading successfully.
  102942. */
  102943. AbstractViewer.prototype.loadModel = function (modelConfig, clearScene) {
  102944. var _this = this;
  102945. if (clearScene === void 0) { clearScene = true; }
  102946. if (this._isLoading) {
  102947. // We can decide here whether or not to cancel the lst load, but the developer can do that.
  102948. return Promise.reject("another model is curently being loaded.");
  102949. }
  102950. return Promise.resolve(this.sceneManager.scene).then(function (scene) {
  102951. if (!scene)
  102952. return _this.sceneManager.initScene(_this.configuration.scene, _this.configuration.optimizer);
  102953. return scene;
  102954. }).then(function () {
  102955. var model = _this.initModel(modelConfig, clearScene);
  102956. return new Promise(function (resolve, reject) {
  102957. // at this point, configuration.model is an object, not a string
  102958. model.onLoadedObservable.add(function () {
  102959. resolve(model);
  102960. });
  102961. model.onLoadErrorObservable.add(function (error) {
  102962. reject(error);
  102963. });
  102964. });
  102965. });
  102966. };
  102967. AbstractViewer.prototype._initTelemetryEvents = function () {
  102968. var _this = this;
  102969. telemetryManager_1.telemetryManager.broadcast("Engine Capabilities", this.baseId, this.engine.getCaps());
  102970. telemetryManager_1.telemetryManager.broadcast("Platform Details", this.baseId, {
  102971. userAgent: navigator.userAgent,
  102972. platform: navigator.platform
  102973. });
  102974. telemetryManager_1.telemetryManager.flushWebGLErrors(this.engine, this.baseId);
  102975. var trackFPS = function () {
  102976. telemetryManager_1.telemetryManager.broadcast("Current FPS", _this.baseId, { fps: _this.engine.getFps() });
  102977. };
  102978. trackFPS();
  102979. // Track the FPS again after 60 seconds
  102980. this._fpsTimeoutInterval = window.setInterval(trackFPS, 60 * 1000);
  102981. };
  102982. /**
  102983. * Injects all the spectre shader in the babylon shader store
  102984. */
  102985. AbstractViewer.prototype._injectCustomShaders = function () {
  102986. var customShaders = this.configuration.customShaders;
  102987. // Inject all the spectre shader in the babylon shader store.
  102988. if (!customShaders) {
  102989. return;
  102990. }
  102991. if (customShaders.shaders) {
  102992. Object.keys(customShaders.shaders).forEach(function (key) {
  102993. // typescript considers a callback "unsafe", so... '!'
  102994. babylonjs_1.Effect.ShadersStore[key] = customShaders.shaders[key];
  102995. });
  102996. }
  102997. if (customShaders.includes) {
  102998. Object.keys(customShaders.includes).forEach(function (key) {
  102999. // typescript considers a callback "unsafe", so... '!'
  103000. babylonjs_1.Effect.IncludesShadersStore[key] = customShaders.includes[key];
  103001. });
  103002. }
  103003. };
  103004. return AbstractViewer;
  103005. }());
  103006. exports.AbstractViewer = AbstractViewer;
  103007. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidmlld2VyLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vLi4vc3JjL3ZpZXdlci92aWV3ZXIudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFBQSxpREFBZ0Q7QUFDaEQseURBQXdEO0FBQ3hELGtEQUE4RDtBQUM5RCx1Q0FBbWdCO0FBS25nQixxREFBb0Q7QUFFcEQsb0RBQXlEO0FBRXpELGlFQUFnRTtBQUNoRSwrQkFBdUM7QUFDdkMscUVBQW9FO0FBQ3BFLGtGQUFpRjtBQUNqRixpRUFBZ0U7QUFFaEU7OztHQUdHO0FBQ0g7SUFnSkksd0JBQW1CLGdCQUE2QixFQUFFLG9CQUE4QztRQUE5QyxxQ0FBQSxFQUFBLHlCQUE4QztRQUFoRyxpQkFzQ0M7UUF0Q2tCLHFCQUFnQixHQUFoQixnQkFBZ0IsQ0FBYTtRQXJIaEQ7O1dBRUc7UUFDSSxrQkFBYSxHQUFZLElBQUksQ0FBQztRQXdGckM7O1dBRUc7UUFDTyxnQkFBVyxHQUFZLEtBQUssQ0FBQztRQTZHdkM7O1dBRUc7UUFDTyxZQUFPLEdBQUc7WUFDaEIsc0NBQXNDO1lBQ3RDLElBQUksQ0FBQyxLQUFJLENBQUMsYUFBYSxFQUFFLEVBQUU7Z0JBQ3ZCLE9BQU87YUFDVjtZQUVELElBQUksS0FBSSxDQUFDLE1BQU0sQ0FBQyxXQUFXLElBQUksQ0FBQyxJQUFJLEtBQUksQ0FBQyxNQUFNLENBQUMsWUFBWSxJQUFJLENBQUMsRUFBRTtnQkFDL0QsT0FBTzthQUNWO1lBRUQsSUFBSSxLQUFJLENBQUMsYUFBYSxDQUFDLE1BQU0sSUFBSSxLQUFJLENBQUMsYUFBYSxDQUFDLE1BQU0s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2REFBNkQ7UUFDN0QsSUFBSSxDQUFDLGFBQWEsRUFBRTtZQUNoQixPQUFPO1NBQ1Y7UUFDRCxJQUFJLGFBQWEsQ0FBQyxPQUFPLEVBQUU7WUFDdkIsTUFBTSxDQUFDLElBQUksQ0FBQyxhQUFhLENBQUMsT0FBTyxDQUFDLENBQUMsT0FBTyxDQUFDLFVBQUEsR0FBRztnQkFDMUMsc0RBQXNEO2dCQUN0RCxrQkFBTSxDQUFDLFlBQVksQ0FBQyxHQUFHLENBQUMsR0FBRyxhQUFjLENBQUMsT0FBUSxDQUFDLEdBQUcsQ0FBQyxDQUFDO1lBQzVELENBQUMsQ0FBQyxDQUFDO1NBQ047UUFDRCxJQUFJLGFBQWEsQ0FBQyxRQUFRLEVBQUU7WUFDeEIsTUFBTSxDQUFDLElBQUksQ0FBQyxhQUFhLENBQUMsUUFBUSxDQUFDLENBQUMsT0FBTyxDQUFDLFVBQUEsR0FBRztnQkFDM0Msc0RBQXNEO2dCQUN0RCxrQkFBTSxDQUFDLG9CQUFvQixDQUFDLEdBQUcsQ0FBQyxHQUFHLGFBQWMsQ0FBQyxRQUFTLENBQUMsR0FBRyxDQUFDLENBQUM7WUFDckUsQ0FBQyxDQUFDLENBQUM7U0FDTjtJQUNMLENBQUM7SUFDTCxxQkFBQztBQUFELENBQUMsQUE5bkJELElBOG5CQztBQTluQnFCLHdDQUFjIn0=
  103008. /***/ }),
  103009. /* 10 */
  103010. /***/ (function(module, exports, __webpack_require__) {
  103011. "use strict";
  103012. function __export(m) {
  103013. for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
  103014. }
  103015. Object.defineProperty(exports, "__esModule", { value: true });
  103016. __export(__webpack_require__(11));
  103017. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi9zcmMvY29uZmlndXJhdGlvbi9pbmRleC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOzs7OztBQUFBLHFDQUFnQyJ9
  103018. /***/ }),
  103019. /* 11 */
  103020. /***/ (function(module, exports, __webpack_require__) {
  103021. "use strict";
  103022. Object.defineProperty(exports, "__esModule", { value: true });
  103023. function getConfigurationKey(key, configObject) {
  103024. var splits = key.split('.');
  103025. if (splits.length === 0 || !configObject)
  103026. return;
  103027. else if (splits.length === 1) {
  103028. if (configObject[key] !== undefined) {
  103029. return configObject[key];
  103030. }
  103031. }
  103032. else {
  103033. var firstKey = splits.shift();
  103034. return getConfigurationKey(splits.join("."), configObject[firstKey]);
  103035. }
  103036. }
  103037. exports.getConfigurationKey = getConfigurationKey;
  103038. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiY29uZmlndXJhdGlvbi5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uL3NyYy9jb25maWd1cmF0aW9uL2NvbmZpZ3VyYXRpb24udHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFHQSw2QkFBb0MsR0FBVyxFQUFFLFlBQWlCO0lBQzlELElBQUksTUFBTSxHQUFHLEdBQUcsQ0FBQyxLQUFLLENBQUMsR0FBRyxDQUFDLENBQUM7SUFFNUIsSUFBSSxNQUFNLENBQUMsTUFBTSxLQUFLLENBQUMsSUFBSSxDQUFDLFlBQVk7UUFBRSxPQUFPO1NBQzVDLElBQUksTUFBTSxDQUFDLE1BQU0sS0FBSyxDQUFDLEVBQUU7UUFDMUIsSUFBSSxZQUFZLENBQUMsR0FBRyxDQUFDLEtBQUssU0FBUyxFQUFFO1lBQ2pDLE9BQU8sWUFBWSxDQUFDLEdBQUcsQ0FBQyxDQUFDO1NBQzVCO0tBQ0o7U0FBTTtRQUNILElBQUksUUFBUSxHQUFHLE1BQU0sQ0FBQyxLQUFLLEVBQUUsQ0FBQztRQUM5QixPQUFPLG1CQUFtQixDQUFDLE1BQU0sQ0FBQyxJQUFJLENBQUMsR0FBRyxDQUFDLEVBQUUsWUFBWSxDQUFDLFFBQVMsQ0FBQyxDQUFDLENBQUE7S0FDeEU7QUFDTCxDQUFDO0FBWkQsa0RBWUMifQ==
  103039. /***/ }),
  103040. /* 12 */
  103041. /***/ (function(module, exports, __webpack_require__) {
  103042. "use strict";
  103043. Object.defineProperty(exports, "__esModule", { value: true });
  103044. var babylonjs_1 = __webpack_require__(0);
  103045. /**
  103046. * A minimal WebGL cubemap descriptor
  103047. */
  103048. var TextureCube = /** @class */ (function () {
  103049. /**
  103050. * constructor
  103051. * @param internalFormat WebGL pixel format for the texture on the GPU
  103052. * @param type WebGL pixel type of the supplied data and texture on the GPU
  103053. * @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
  103054. */
  103055. function TextureCube(internalFormat, type, source) {
  103056. if (source === void 0) { source = []; }
  103057. this.internalFormat = internalFormat;
  103058. this.type = type;
  103059. this.source = source;
  103060. }
  103061. Object.defineProperty(TextureCube.prototype, "Width", {
  103062. /**
  103063. * Returns the width of a face of the texture or 0 if not available
  103064. */
  103065. get: function () {
  103066. return (this.source && this.source[0] && this.source[0][0]) ? this.source[0][0].width : 0;
  103067. },
  103068. enumerable: true,
  103069. configurable: true
  103070. });
  103071. Object.defineProperty(TextureCube.prototype, "Height", {
  103072. /**
  103073. * Returns the height of a face of the texture or 0 if not available
  103074. */
  103075. get: function () {
  103076. return (this.source && this.source[0] && this.source[0][0]) ? this.source[0][0].height : 0;
  103077. },
  103078. enumerable: true,
  103079. configurable: true
  103080. });
  103081. return TextureCube;
  103082. }());
  103083. exports.TextureCube = TextureCube;
  103084. /**
  103085. * A static class providing methods to aid working with Bablyon textures.
  103086. */
  103087. var TextureUtils = /** @class */ (function () {
  103088. function TextureUtils() {
  103089. }
  103090. /**
  103091. * Returns a BabylonCubeTexture instance from a Spectre texture cube, subject to sampling parameters.
  103092. * If such a texture has already been requested in the past, this texture will be returned, otherwise a new one will be created.
  103093. * The advantage of this is to enable working with texture objects without the need to initialize on the GPU until desired.
  103094. * @param scene A Babylon Scene instance
  103095. * @param textureCube A Spectre TextureCube object
  103096. * @param parameters WebGL texture sampling parameters
  103097. * @param automaticMipmaps Pass true to enable automatic mipmap generation where possible (requires power of images)
  103098. * @param environment Specifies that the texture will be used as an environment
  103099. * @param singleLod Specifies that the texture will be a singleLod (for environment)
  103100. * @return Babylon cube texture
  103101. */
  103102. TextureUtils.GetBabylonCubeTexture = function (scene, textureCube, automaticMipmaps, environment, singleLod) {
  103103. if (environment === void 0) { environment = false; }
  103104. if (singleLod === void 0) { singleLod = false; }
  103105. if (!textureCube)
  103106. throw new Error("no texture cube provided");
  103107. var parameters;
  103108. if (environment) {
  103109. parameters = singleLod ? TextureUtils._EnvironmentSingleMipSampling : TextureUtils._EnvironmentSampling;
  103110. }
  103111. else {
  103112. parameters = {
  103113. magFilter: 9728 /* NEAREST */,
  103114. minFilter: 9728 /* NEAREST */,
  103115. wrapS: 33071 /* CLAMP_TO_EDGE */,
  103116. wrapT: 33071 /* CLAMP_TO_EDGE */
  103117. };
  103118. }
  103119. var key = TextureUtils.BabylonTextureKeyPrefix + parameters.magFilter + '' + parameters.minFilter + '' + parameters.wrapS + '' + parameters.wrapT;
  103120. var babylonTexture = textureCube[key];
  103121. if (!babylonTexture) {
  103122. //initialize babylon texture
  103123. babylonTexture = new babylonjs_1.CubeTexture('', scene);
  103124. if (environment) {
  103125. babylonTexture.lodGenerationOffset = TextureUtils.EnvironmentLODOffset;
  103126. babylonTexture.lodGenerationScale = TextureUtils.EnvironmentLODScale;
  103127. }
  103128. babylonTexture.gammaSpace = false;
  103129. var internalTexture_1 = new babylonjs_1.InternalTexture(scene.getEngine(), babylonjs_1.InternalTexture.DATASOURCE_CUBERAW);
  103130. var glTexture_1 = internalTexture_1._webGLTexture;
  103131. //babylon properties
  103132. internalTexture_1.isCube = true;
  103133. internalTexture_1.generateMipMaps = false;
  103134. babylonTexture._texture = internalTexture_1;
  103135. TextureUtils.ApplySamplingParameters(babylonTexture, parameters);
  103136. var maxMipLevel_1 = automaticMipmaps ? 0 : textureCube.source.length - 1;
  103137. var texturesUploaded_1 = 0;
  103138. var textureComplete = function () {
  103139. return texturesUploaded_1 === ((maxMipLevel_1 + 1) * 6);
  103140. };
  103141. var uploadFace = function (i, level, face) {
  103142. if (!glTexture_1)
  103143. return;
  103144. if (i === 0 && level === 0) {
  103145. internalTexture_1.width = face.width;
  103146. internalTexture_1.height = face.height;
  103147. }
  103148. var gl = (scene.getEngine())._gl;
  103149. gl.bindTexture(gl.TEXTURE_CUBE_MAP, glTexture_1);
  103150. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  103151. if (face instanceof HTMLElement || face instanceof ImageData) {
  103152. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, level, textureCube.internalFormat, textureCube.internalFormat, textureCube.type, face);
  103153. }
  103154. else {
  103155. var textureData = face;
  103156. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, level, textureCube.internalFormat, textureData.width, textureData.height, 0, textureData.format, textureCube.type, textureData.data);
  103157. }
  103158. texturesUploaded_1++;
  103159. if (textureComplete()) {
  103160. //generate mipmaps
  103161. if (automaticMipmaps) {
  103162. var w = face.width;
  103163. var h = face.height;
  103164. var isPot = (((w !== 0) && (w & (w - 1))) === 0) && (((h !== 0) && (h & (h - 1))) === 0);
  103165. if (isPot) {
  103166. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  103167. }
  103168. }
  103169. // Upload Separate lods in case there is no support for texture lod.
  103170. if (environment && !scene.getEngine().getCaps().textureLOD && !singleLod) {
  103171. var mipSlices = 3;
  103172. for (var i_1 = 0; i_1 < mipSlices; i_1++) {
  103173. var lodKey = TextureUtils.BabylonTextureKeyPrefix + 'lod' + i_1;
  103174. var lod = textureCube[lodKey];
  103175. //initialize lod texture if it doesn't already exist
  103176. if (lod == null && textureCube.Width) {
  103177. //compute LOD from even spacing in smoothness (matching shader calculation)
  103178. var smoothness = i_1 / (mipSlices - 1);
  103179. var roughness = 1 - smoothness;
  103180. var kMinimumVariance = 0.0005;
  103181. var alphaG = roughness * roughness + kMinimumVariance;
  103182. var microsurfaceAverageSlopeTexels = alphaG * textureCube.Width;
  103183. var environmentSpecularLOD = TextureUtils.EnvironmentLODScale * (babylonjs_1.Scalar.Log2(microsurfaceAverageSlopeTexels)) + TextureUtils.EnvironmentLODOffset;
  103184. var maxLODIndex = textureCube.source.length - 1;
  103185. var mipmapIndex = Math.min(Math.max(Math.round(environmentSpecularLOD), 0), maxLODIndex);
  103186. lod = TextureUtils.GetBabylonCubeTexture(scene, new TextureCube(6408 /* RGBA */, 5121 /* UNSIGNED_BYTE */, [textureCube.source[mipmapIndex]]), false, true, true);
  103187. if (i_1 === 0) {
  103188. internalTexture_1._lodTextureLow = lod;
  103189. }
  103190. else if (i_1 === 1) {
  103191. internalTexture_1._lodTextureMid = lod;
  103192. }
  103193. else {
  103194. internalTexture_1._lodTextureHigh = lod;
  103195. }
  103196. textureCube[lodKey] = lod;
  103197. }
  103198. }
  103199. }
  103200. internalTexture_1.isReady = true;
  103201. }
  103202. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  103203. scene.getEngine().resetTextureCache();
  103204. };
  103205. var _loop_1 = function (i) {
  103206. var faces = textureCube.source[i];
  103207. var _loop_2 = function (j) {
  103208. var face = faces[j];
  103209. if (face instanceof HTMLImageElement && !face.complete) {
  103210. face.addEventListener('load', function () {
  103211. uploadFace(j, i, face);
  103212. }, false);
  103213. }
  103214. else {
  103215. uploadFace(j, i, face);
  103216. }
  103217. };
  103218. for (var j = 0; j < faces.length; j++) {
  103219. _loop_2(j);
  103220. }
  103221. };
  103222. for (var i = 0; i <= maxMipLevel_1; i++) {
  103223. _loop_1(i);
  103224. }
  103225. scene.getEngine().resetTextureCache();
  103226. babylonTexture.isReady = function () {
  103227. return textureComplete();
  103228. };
  103229. textureCube[key] = babylonTexture;
  103230. }
  103231. return babylonTexture;
  103232. };
  103233. /**
  103234. * Applies Spectre SamplingParameters to a Babylon texture by directly setting texture parameters on the internal WebGLTexture as well as setting Babylon fields
  103235. * @param babylonTexture Babylon texture to apply texture to (requires the Babylon texture has an initialize _texture field)
  103236. * @param parameters Spectre SamplingParameters to apply
  103237. */
  103238. TextureUtils.ApplySamplingParameters = function (babylonTexture, parameters) {
  103239. var scene = babylonTexture.getScene();
  103240. if (!scene)
  103241. return;
  103242. var gl = (scene.getEngine())._gl;
  103243. var target = babylonTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  103244. var internalTexture = babylonTexture._texture;
  103245. if (!internalTexture)
  103246. return;
  103247. var glTexture = internalTexture._webGLTexture;
  103248. gl.bindTexture(target, glTexture);
  103249. if (parameters.magFilter != null)
  103250. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, parameters.magFilter);
  103251. if (parameters.minFilter != null)
  103252. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, parameters.minFilter);
  103253. if (parameters.wrapS != null)
  103254. gl.texParameteri(target, gl.TEXTURE_WRAP_S, parameters.wrapS);
  103255. if (parameters.wrapT != null)
  103256. gl.texParameteri(target, gl.TEXTURE_WRAP_T, parameters.wrapT);
  103257. //set babylon wrap modes from sampling parameter
  103258. switch (parameters.wrapS) {
  103259. case 10497 /* REPEAT */:
  103260. babylonTexture.wrapU = babylonjs_1.Texture.WRAP_ADDRESSMODE;
  103261. break;
  103262. case 33071 /* CLAMP_TO_EDGE */:
  103263. babylonTexture.wrapU = babylonjs_1.Texture.CLAMP_ADDRESSMODE;
  103264. break;
  103265. case 33648 /* MIRRORED_REPEAT */:
  103266. babylonTexture.wrapU = babylonjs_1.Texture.MIRROR_ADDRESSMODE;
  103267. break;
  103268. default: babylonTexture.wrapU = babylonjs_1.Texture.CLAMP_ADDRESSMODE;
  103269. }
  103270. switch (parameters.wrapT) {
  103271. case 10497 /* REPEAT */:
  103272. babylonTexture.wrapV = babylonjs_1.Texture.WRAP_ADDRESSMODE;
  103273. break;
  103274. case 33071 /* CLAMP_TO_EDGE */:
  103275. babylonTexture.wrapV = babylonjs_1.Texture.CLAMP_ADDRESSMODE;
  103276. break;
  103277. case 33648 /* MIRRORED_REPEAT */:
  103278. babylonTexture.wrapV = babylonjs_1.Texture.MIRROR_ADDRESSMODE;
  103279. break;
  103280. default: babylonTexture.wrapV = babylonjs_1.Texture.CLAMP_ADDRESSMODE;
  103281. }
  103282. if (parameters.maxAnisotropy != null && parameters.maxAnisotropy > 1) {
  103283. var anisotropicExt = gl.getExtension('EXT_texture_filter_anisotropic');
  103284. if (anisotropicExt) {
  103285. var maxAnisotropicSamples = gl.getParameter(anisotropicExt.MAX_TEXTURE_MAX_ANISOTROPY_EXT);
  103286. var maxAnisotropy = Math.min(parameters.maxAnisotropy, maxAnisotropicSamples);
  103287. gl.texParameterf(target, anisotropicExt.TEXTURE_MAX_ANISOTROPY_EXT, maxAnisotropy);
  103288. babylonTexture.anisotropicFilteringLevel = maxAnisotropy;
  103289. }
  103290. }
  103291. gl.bindTexture(target, null);
  103292. scene.getEngine().resetTextureCache();
  103293. };
  103294. /**
  103295. * A prefix used when storing a babylon texture object reference on a Spectre texture object
  103296. */
  103297. TextureUtils.BabylonTextureKeyPrefix = '__babylonTexture_';
  103298. /**
  103299. * Controls anisotropic filtering for deserialized textures.
  103300. */
  103301. TextureUtils.MaxAnisotropy = 4;
  103302. TextureUtils._EnvironmentSampling = {
  103303. magFilter: 9729 /* LINEAR */,
  103304. minFilter: 9987 /* LINEAR_MIPMAP_LINEAR */,
  103305. wrapS: 33071 /* CLAMP_TO_EDGE */,
  103306. wrapT: 33071 /* CLAMP_TO_EDGE */,
  103307. maxAnisotropy: 1
  103308. };
  103309. TextureUtils._EnvironmentSingleMipSampling = {
  103310. magFilter: 9729 /* LINEAR */,
  103311. minFilter: 9729 /* LINEAR */,
  103312. wrapS: 33071 /* CLAMP_TO_EDGE */,
  103313. wrapT: 33071 /* CLAMP_TO_EDGE */,
  103314. maxAnisotropy: 1
  103315. };
  103316. //from "/Internal/Lighting.EnvironmentFilterScale" in Engine/*/Configuration.cpp
  103317. /**
  103318. * Environment preprocessing dedicated value (Internal Use or Advanced only).
  103319. */
  103320. TextureUtils.EnvironmentLODScale = 0.8;
  103321. /**
  103322. * Environment preprocessing dedicated value (Internal Use or Advanced only)..
  103323. */
  103324. TextureUtils.EnvironmentLODOffset = 1.0;
  103325. return TextureUtils;
  103326. }());
  103327. exports.TextureUtils = TextureUtils;
  103328. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidGV4dHVyZS5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uL3NyYy9sYWJzL3RleHR1cmUudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFBQSx1Q0FBOEY7QUFrSTlGOztHQUVHO0FBQ0g7SUFnQkk7Ozs7O09BS0c7SUFDSCxxQkFBbUIsY0FBMkIsRUFBUyxJQUFlLEVBQVMsTUFBd0I7UUFBeEIsdUJBQUEsRUFBQSxXQUF3QjtRQUFwRixtQkFBYyxHQUFkLGNBQWMsQ0FBYTtRQUFTLFNBQUksR0FBSixJQUFJLENBQVc7UUFBUyxXQUFNLEdBQU4sTUFBTSxDQUFrQjtJQUFJLENBQUM7SUFqQjVHLHNCQUFXLDhCQUFLO1FBSGhCOztXQUVHO2FBQ0g7WUFDSSxPQUFPLENBQUMsSUFBSSxDQUFDLE1BQU0sSUFBSSxJQUFJLENBQUMsTUFBTSxDQUFDLENBQUMsQ0FBQyxJQUFJLElBQUksQ0FBQyxNQUFNLENBQUMsQ0FBQyxDQUFDLENBQUMsQ0FBQyxDQUFDLENBQUMsQ0FBQyxDQUFDLENBQUMsSUFBSSxDQUFDLE1BQU0sQ0FBQyxDQUFDLENBQUMsQ0FBQyxDQUFDLENBQUMsQ0FBQyxLQUFLLENBQUMsQ0FBQyxDQ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QUNwQyxhQUFhLEVBQUUsQ0FBQztLQUNuQixDQUFDO0lBRWEsMENBQTZCLEdBQXVCO1FBQy9ELFNBQVMsbUJBQXlCO1FBQ2xDLFNBQVMsbUJBQXlCO1FBQ2xDLEtBQUssMkJBQStCO1FBQ3BDLEtBQUssMkJBQStCO1FBQ3BDLGFBQWEsRUFBRSxDQUFDO0tBQ25CLENBQUM7SUFFRixnRkFBZ0Y7SUFDaEY7O09BRUc7SUFDVyxnQ0FBbUIsR0FBRyxHQUFHLENBQUM7SUFDeEM7O09BRUc7SUFDVyxpQ0FBb0IsR0FBRyxHQUFHLENBQUM7SUFDN0MsbUJBQUM7Q0FBQSxBQTFQRCxJQTBQQztBQTFQWSxvQ0FBWSJ9
  103329. /***/ }),
  103330. /* 13 */
  103331. /***/ (function(module, exports, __webpack_require__) {
  103332. "use strict";
  103333. Object.defineProperty(exports, "__esModule", { value: true });
  103334. var babylonjs_1 = __webpack_require__(0);
  103335. var babylonjs_loaders_1 = __webpack_require__(14);
  103336. var viewerModel_1 = __webpack_require__(5);
  103337. var _1 = __webpack_require__(54);
  103338. /**
  103339. * An instance of the class is in charge of loading the model correctly.
  103340. * This class will continously be expended with tasks required from the specific loaders Babylon has.
  103341. *
  103342. * A Model loader is unique per (Abstract)Viewer. It is being generated by the viewer
  103343. */
  103344. var ModelLoader = /** @class */ (function () {
  103345. /**
  103346. * Create a new Model loader
  103347. * @param _viewer the viewer using this model loader
  103348. */
  103349. function ModelLoader(_observablesManager, _configurationContainer) {
  103350. this._observablesManager = _observablesManager;
  103351. this._configurationContainer = _configurationContainer;
  103352. this._disposed = false;
  103353. this._loaders = [];
  103354. this._loadId = 0;
  103355. this._plugins = [];
  103356. }
  103357. /**
  103358. * Adds a new plugin to the loader process.
  103359. *
  103360. * @param plugin the plugin name or the plugin itself
  103361. */
  103362. ModelLoader.prototype.addPlugin = function (plugin) {
  103363. var actualPlugin = {};
  103364. if (typeof plugin === 'string') {
  103365. var loadedPlugin = _1.getLoaderPluginByName(plugin);
  103366. if (loadedPlugin) {
  103367. actualPlugin = loadedPlugin;
  103368. }
  103369. }
  103370. else {
  103371. actualPlugin = plugin;
  103372. }
  103373. if (actualPlugin && this._plugins.indexOf(actualPlugin) === -1) {
  103374. this._plugins.push(actualPlugin);
  103375. }
  103376. };
  103377. /**
  103378. * Load a model using predefined configuration
  103379. * @param modelConfiguration the modelConfiguration to use to load the model
  103380. */
  103381. ModelLoader.prototype.load = function (modelConfiguration) {
  103382. var _this = this;
  103383. var model = new viewerModel_1.ViewerModel(this._observablesManager, modelConfiguration);
  103384. model.loadId = this._loadId++;
  103385. if (!modelConfiguration.url) {
  103386. model.state = viewerModel_1.ModelState.ERROR;
  103387. babylonjs_1.Tools.Error("No URL provided");
  103388. return model;
  103389. }
  103390. var base;
  103391. var filename;
  103392. if (modelConfiguration.file) {
  103393. base = "file:";
  103394. filename = modelConfiguration.file;
  103395. }
  103396. else {
  103397. filename = babylonjs_1.Tools.GetFilename(modelConfiguration.url) || modelConfiguration.url;
  103398. base = modelConfiguration.root || babylonjs_1.Tools.GetFolderPath(modelConfiguration.url);
  103399. }
  103400. var plugin = modelConfiguration.loader;
  103401. var scene = model.rootMesh.getScene();
  103402. model.loader = babylonjs_1.SceneLoader.ImportMesh(undefined, base, filename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  103403. meshes.forEach(function (mesh) {
  103404. babylonjs_1.Tags.AddTagsTo(mesh, "viewerMesh");
  103405. model.addMesh(mesh);
  103406. });
  103407. model.particleSystems = particleSystems;
  103408. model.skeletons = skeletons;
  103409. for (var _i = 0, animationGroups_1 = animationGroups; _i < animationGroups_1.length; _i++) {
  103410. var animationGroup = animationGroups_1[_i];
  103411. model.addAnimationGroup(animationGroup);
  103412. }
  103413. _this._checkAndRun("onLoaded", model);
  103414. scene.executeWhenReady(function () {
  103415. model.onLoadedObservable.notifyObservers(model);
  103416. });
  103417. }, function (progressEvent) {
  103418. _this._checkAndRun("onProgress", progressEvent);
  103419. model.onLoadProgressObservable.notifyObserversWithPromise(progressEvent);
  103420. }, function (scene, m, exception) {
  103421. model.state = viewerModel_1.ModelState.ERROR;
  103422. babylonjs_1.Tools.Error("Load Error: There was an error loading the model. " + m);
  103423. _this._checkAndRun("onError", m, exception);
  103424. model.onLoadErrorObservable.notifyObserversWithPromise({ message: m, exception: exception });
  103425. }, plugin);
  103426. if (model.loader.name === "gltf") {
  103427. var gltfLoader_1 = model.loader;
  103428. gltfLoader_1.animationStartMode = babylonjs_loaders_1.GLTFLoaderAnimationStartMode.NONE;
  103429. gltfLoader_1.compileMaterials = true;
  103430. if (!modelConfiguration.file) {
  103431. gltfLoader_1.rewriteRootURL = function (rootURL, responseURL) {
  103432. return modelConfiguration.root || babylonjs_1.Tools.GetFolderPath(responseURL || modelConfiguration.url || '');
  103433. };
  103434. }
  103435. // if ground is set to "mirror":
  103436. if (this._configurationContainer
  103437. && this._configurationContainer.configuration
  103438. && this._configurationContainer.configuration.ground
  103439. && typeof this._configurationContainer.configuration.ground === 'object'
  103440. && this._configurationContainer.configuration.ground.mirror) {
  103441. gltfLoader_1.useClipPlane = true;
  103442. }
  103443. Object.keys(gltfLoader_1).filter(function (name) { return name.indexOf('on') === 0 && name.indexOf('Observable') !== -1; }).forEach(function (functionName) {
  103444. gltfLoader_1[functionName].add(function (payload) {
  103445. _this._checkAndRun(functionName.replace("Observable", ''), payload);
  103446. });
  103447. });
  103448. gltfLoader_1.onParsedObservable.add(function (data) {
  103449. if (data && data.json && data.json['asset']) {
  103450. model.loadInfo = data.json['asset'];
  103451. }
  103452. });
  103453. gltfLoader_1.onCompleteObservable.add(function () {
  103454. model.loaderDone = true;
  103455. });
  103456. }
  103457. else {
  103458. model.loaderDone = true;
  103459. }
  103460. this._checkAndRun("onInit", model.loader, model);
  103461. this._loaders.push(model.loader);
  103462. return model;
  103463. };
  103464. ModelLoader.prototype.cancelLoad = function (model) {
  103465. var loader = model.loader || this._loaders[model.loadId];
  103466. // ATM only available in the GLTF Loader
  103467. if (loader && loader.name === "gltf") {
  103468. var gltfLoader = loader;
  103469. gltfLoader.dispose();
  103470. model.state = viewerModel_1.ModelState.CANCELED;
  103471. }
  103472. else {
  103473. babylonjs_1.Tools.Warn("This type of loader cannot cancel the request");
  103474. }
  103475. };
  103476. /**
  103477. * dispose the model loader.
  103478. * If loaders are registered and are in the middle of loading, they will be disposed and the request(s) will be cancelled.
  103479. */
  103480. ModelLoader.prototype.dispose = function () {
  103481. this._loaders.forEach(function (loader) {
  103482. if (loader.name === "gltf") {
  103483. loader.dispose();
  103484. }
  103485. });
  103486. this._loaders.length = 0;
  103487. this._disposed = true;
  103488. };
  103489. ModelLoader.prototype._checkAndRun = function (functionName) {
  103490. var _this = this;
  103491. var payload = [];
  103492. for (var _i = 1; _i < arguments.length; _i++) {
  103493. payload[_i - 1] = arguments[_i];
  103494. }
  103495. if (this._disposed)
  103496. return;
  103497. this._plugins.filter(function (p) { return p[functionName]; }).forEach(function (plugin) {
  103498. try {
  103499. plugin[functionName].apply(_this, payload);
  103500. }
  103501. catch (e) { }
  103502. });
  103503. };
  103504. return ModelLoader;
  103505. }());
  103506. exports.ModelLoader = ModelLoader;
  103507. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoibW9kZWxMb2FkZXIuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi9zcmMvbG9hZGVyL21vZGVsTG9hZGVyLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7O0FBQUEsdUNBQWtHO0FBQ2xHLHVEQUFpRjtBQUdqRixvREFBK0Q7QUFDL0QsK0JBQXlGO0FBSXpGOzs7OztHQUtHO0FBQ0g7SUFTSTs7O09BR0c7SUFDSCxxQkFBb0IsbUJBQXVDLEVBQVUsdUJBQWdEO1FBQWpHLHdCQUFtQixHQUFuQixtQkFBbUIsQ0FBb0I7UUFBVSw0QkFBdUIsR0FBdkIsdUJBQXVCLENBQXlCO1FBVjdHL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0FBUztZQUFFLE9BQU87UUFDM0IsSUFBSSxDQUFDLFFBQVEsQ0FBQyxNQUFNLENBQUMsVUFBQSxDQUFDLElBQUksT0FBQSxDQUFDLENBQUMsWUFBWSxDQUFDLEVBQWYsQ0FBZSxDQUFDLENBQUMsT0FBTyxDQUFDLFVBQUEsTUFBTTtZQUNyRCxJQUFJO2dCQUNBLE1BQU0sQ0FBQyxZQUFZLENBQUMsQ0FBQyxLQUFLLENBQUMsS0FBSSxFQUFFLE9BQU8sQ0FBQyxDQUFDO2FBQzdDO1lBQUMsT0FBTyxDQUFDLEVBQUUsR0FBRztRQUNuQixDQUFDLENBQUMsQ0FBQTtJQUNOLENBQUM7SUFDTCxrQkFBQztBQUFELENBQUMsQUFoTEQsSUFnTEM7QUFoTFksa0NBQVcifQ==
  103508. /***/ }),
  103509. /* 14 */
  103510. /***/ (function(module, exports, __webpack_require__) {
  103511. (function universalModuleDefinition(root, factory) {
  103512. var amdDependencies = [];
  103513. var BABYLON = root.BABYLON || this.BABYLON;
  103514. if(true) {
  103515. BABYLON = BABYLON || __webpack_require__(0);
  103516. module.exports = factory(BABYLON);
  103517. } else if(typeof define === 'function' && define.amd) {
  103518. amdDependencies.push("babylonjs");
  103519. define("babylonjs-loaders", amdDependencies, factory);
  103520. } else if(typeof exports === 'object') {
  103521. BABYLON = BABYLON || require("babylonjs");
  103522. exports["babylonjs-loaders"] = factory(BABYLON);
  103523. } else {
  103524. root["BABYLON"] = factory(BABYLON);
  103525. }
  103526. })(this, function(BABYLON) {
  103527. BABYLON = BABYLON || this.BABYLON;
  103528. 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};
  103529. 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)}}();
  103530. var BABYLON;
  103531. (function (BABYLON) {
  103532. var STLFileLoader = /** @class */ (function () {
  103533. function STLFileLoader() {
  103534. this.solidPattern = /solid (\S*)([\S\s]*)endsolid[ ]*(\S*)/g;
  103535. this.facetsPattern = /facet([\s\S]*?)endfacet/g;
  103536. 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;
  103537. 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;
  103538. this.name = "stl";
  103539. // force data to come in as an ArrayBuffer
  103540. // we'll convert to string if it looks like it's an ASCII .stl
  103541. this.extensions = {
  103542. ".stl": { isBinary: true },
  103543. };
  103544. }
  103545. STLFileLoader.prototype.importMesh = function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  103546. var matches;
  103547. if (typeof data !== "string") {
  103548. if (this.isBinary(data)) {
  103549. // binary .stl
  103550. var babylonMesh = new BABYLON.Mesh("stlmesh", scene);
  103551. this.parseBinary(babylonMesh, data);
  103552. if (meshes) {
  103553. meshes.push(babylonMesh);
  103554. }
  103555. return true;
  103556. }
  103557. // ASCII .stl
  103558. // convert to string
  103559. var array_buffer = new Uint8Array(data);
  103560. var str = '';
  103561. for (var i = 0; i < data.byteLength; i++) {
  103562. str += String.fromCharCode(array_buffer[i]); // implicitly assumes little-endian
  103563. }
  103564. data = str;
  103565. }
  103566. //if arrived here, data is a string, containing the STLA data.
  103567. while (matches = this.solidPattern.exec(data)) {
  103568. var meshName = matches[1];
  103569. var meshNameFromEnd = matches[3];
  103570. if (meshName != meshNameFromEnd) {
  103571. BABYLON.Tools.Error("Error in STL, solid name != endsolid name");
  103572. return false;
  103573. }
  103574. // check meshesNames
  103575. if (meshesNames && meshName) {
  103576. if (meshesNames instanceof Array) {
  103577. if (!meshesNames.indexOf(meshName)) {
  103578. continue;
  103579. }
  103580. }
  103581. else {
  103582. if (meshName !== meshesNames) {
  103583. continue;
  103584. }
  103585. }
  103586. }
  103587. // stl mesh name can be empty as well
  103588. meshName = meshName || "stlmesh";
  103589. var babylonMesh = new BABYLON.Mesh(meshName, scene);
  103590. this.parseASCII(babylonMesh, matches[2]);
  103591. if (meshes) {
  103592. meshes.push(babylonMesh);
  103593. }
  103594. }
  103595. return true;
  103596. };
  103597. STLFileLoader.prototype.load = function (scene, data, rootUrl) {
  103598. var result = this.importMesh(null, scene, data, rootUrl, null, null, null);
  103599. if (result) {
  103600. scene.createDefaultCameraOrLight();
  103601. }
  103602. return result;
  103603. };
  103604. STLFileLoader.prototype.loadAssetContainer = function (scene, data, rootUrl, onError) {
  103605. var container = new BABYLON.AssetContainer(scene);
  103606. this.importMesh(null, scene, data, rootUrl, container.meshes, null, null);
  103607. container.removeAllFromScene();
  103608. return container;
  103609. };
  103610. STLFileLoader.prototype.isBinary = function (data) {
  103611. // check if file size is correct for binary stl
  103612. var faceSize, nFaces, reader;
  103613. reader = new DataView(data);
  103614. faceSize = (32 / 8 * 3) + ((32 / 8 * 3) * 3) + (16 / 8);
  103615. nFaces = reader.getUint32(80, true);
  103616. if (80 + (32 / 8) + (nFaces * faceSize) === reader.byteLength) {
  103617. return true;
  103618. }
  103619. // check characters higher than ASCII to confirm binary
  103620. var fileLength = reader.byteLength;
  103621. for (var index = 0; index < fileLength; index++) {
  103622. if (reader.getUint8(index) > 127) {
  103623. return true;
  103624. }
  103625. }
  103626. return false;
  103627. };
  103628. STLFileLoader.prototype.parseBinary = function (mesh, data) {
  103629. var reader = new DataView(data);
  103630. var faces = reader.getUint32(80, true);
  103631. var dataOffset = 84;
  103632. var faceLength = 12 * 4 + 2;
  103633. var offset = 0;
  103634. var positions = new Float32Array(faces * 3 * 3);
  103635. var normals = new Float32Array(faces * 3 * 3);
  103636. var indices = new Uint32Array(faces * 3);
  103637. var indicesCount = 0;
  103638. for (var face = 0; face < faces; face++) {
  103639. var start = dataOffset + face * faceLength;
  103640. var normalX = reader.getFloat32(start, true);
  103641. var normalY = reader.getFloat32(start + 4, true);
  103642. var normalZ = reader.getFloat32(start + 8, true);
  103643. for (var i = 1; i <= 3; i++) {
  103644. var vertexstart = start + i * 12;
  103645. // ordering is intentional to match ascii import
  103646. positions[offset] = reader.getFloat32(vertexstart, true);
  103647. positions[offset + 2] = reader.getFloat32(vertexstart + 4, true);
  103648. positions[offset + 1] = reader.getFloat32(vertexstart + 8, true);
  103649. normals[offset] = normalX;
  103650. normals[offset + 2] = normalY;
  103651. normals[offset + 1] = normalZ;
  103652. offset += 3;
  103653. }
  103654. indices[indicesCount] = indicesCount++;
  103655. indices[indicesCount] = indicesCount++;
  103656. indices[indicesCount] = indicesCount++;
  103657. }
  103658. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  103659. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  103660. mesh.setIndices(indices);
  103661. mesh.computeWorldMatrix(true);
  103662. };
  103663. STLFileLoader.prototype.parseASCII = function (mesh, solidData) {
  103664. var positions = [];
  103665. var normals = [];
  103666. var indices = [];
  103667. var indicesCount = 0;
  103668. //load facets, ignoring loop as the standard doesn't define it can contain more than vertices
  103669. var matches;
  103670. while (matches = this.facetsPattern.exec(solidData)) {
  103671. var facet = matches[1];
  103672. //one normal per face
  103673. var normalMatches = this.normalPattern.exec(facet);
  103674. this.normalPattern.lastIndex = 0;
  103675. if (!normalMatches) {
  103676. continue;
  103677. }
  103678. var normal = [Number(normalMatches[1]), Number(normalMatches[5]), Number(normalMatches[3])];
  103679. var vertexMatch;
  103680. while (vertexMatch = this.vertexPattern.exec(facet)) {
  103681. positions.push(Number(vertexMatch[1]), Number(vertexMatch[5]), Number(vertexMatch[3]));
  103682. normals.push(normal[0], normal[1], normal[2]);
  103683. }
  103684. indices.push(indicesCount++, indicesCount++, indicesCount++);
  103685. this.vertexPattern.lastIndex = 0;
  103686. }
  103687. this.facetsPattern.lastIndex = 0;
  103688. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  103689. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  103690. mesh.setIndices(indices);
  103691. mesh.computeWorldMatrix(true);
  103692. };
  103693. return STLFileLoader;
  103694. }());
  103695. BABYLON.STLFileLoader = STLFileLoader;
  103696. if (BABYLON.SceneLoader) {
  103697. BABYLON.SceneLoader.RegisterPlugin(new STLFileLoader());
  103698. }
  103699. })(BABYLON || (BABYLON = {}));
  103700. //# sourceMappingURL=babylon.stlFileLoader.js.map
  103701. var BABYLON;
  103702. (function (BABYLON) {
  103703. /**
  103704. * Class reading and parsing the MTL file bundled with the obj file.
  103705. */
  103706. var MTLFileLoader = /** @class */ (function () {
  103707. function MTLFileLoader() {
  103708. // All material loaded from the mtl will be set here
  103709. this.materials = [];
  103710. }
  103711. /**
  103712. * This function will read the mtl file and create each material described inside
  103713. * This function could be improve by adding :
  103714. * -some component missing (Ni, Tf...)
  103715. * -including the specific options available
  103716. *
  103717. * @param scene
  103718. * @param data
  103719. * @param rootUrl
  103720. */
  103721. MTLFileLoader.prototype.parseMTL = function (scene, data, rootUrl) {
  103722. if (data instanceof ArrayBuffer) {
  103723. return;
  103724. }
  103725. //Split the lines from the file
  103726. var lines = data.split('\n');
  103727. //Space char
  103728. var delimiter_pattern = /\s+/;
  103729. //Array with RGB colors
  103730. var color;
  103731. //New material
  103732. var material = null;
  103733. //Look at each line
  103734. for (var i = 0; i < lines.length; i++) {
  103735. var line = lines[i].trim();
  103736. // Blank line or comment
  103737. if (line.length === 0 || line.charAt(0) === '#') {
  103738. continue;
  103739. }
  103740. //Get the first parameter (keyword)
  103741. var pos = line.indexOf(' ');
  103742. var key = (pos >= 0) ? line.substring(0, pos) : line;
  103743. key = key.toLowerCase();
  103744. //Get the data following the key
  103745. var value = (pos >= 0) ? line.substring(pos + 1).trim() : "";
  103746. //This mtl keyword will create the new material
  103747. if (key === "newmtl") {
  103748. //Check if it is the first material.
  103749. // Materials specifications are described after this keyword.
  103750. if (material) {
  103751. //Add the previous material in the material array.
  103752. this.materials.push(material);
  103753. }
  103754. //Create a new material.
  103755. // value is the name of the material read in the mtl file
  103756. material = new BABYLON.StandardMaterial(value, scene);
  103757. }
  103758. else if (key === "kd" && material) {
  103759. // Diffuse color (color under white light) using RGB values
  103760. //value = "r g b"
  103761. color = value.split(delimiter_pattern, 3).map(parseFloat);
  103762. //color = [r,g,b]
  103763. //Set tghe color into the material
  103764. material.diffuseColor = BABYLON.Color3.FromArray(color);
  103765. }
  103766. else if (key === "ka" && material) {
  103767. // Ambient color (color under shadow) using RGB values
  103768. //value = "r g b"
  103769. color = value.split(delimiter_pattern, 3).map(parseFloat);
  103770. //color = [r,g,b]
  103771. //Set tghe color into the material
  103772. material.ambientColor = BABYLON.Color3.FromArray(color);
  103773. }
  103774. else if (key === "ks" && material) {
  103775. // Specular color (color when light is reflected from shiny surface) using RGB values
  103776. //value = "r g b"
  103777. color = value.split(delimiter_pattern, 3).map(parseFloat);
  103778. //color = [r,g,b]
  103779. //Set the color into the material
  103780. material.specularColor = BABYLON.Color3.FromArray(color);
  103781. }
  103782. else if (key === "ke" && material) {
  103783. // Emissive color using RGB values
  103784. color = value.split(delimiter_pattern, 3).map(parseFloat);
  103785. material.emissiveColor = BABYLON.Color3.FromArray(color);
  103786. }
  103787. else if (key === "ns" && material) {
  103788. //value = "Integer"
  103789. material.specularPower = parseFloat(value);
  103790. }
  103791. else if (key === "d" && material) {
  103792. //d is dissolve for current material. It mean alpha for BABYLON
  103793. material.alpha = parseFloat(value);
  103794. //Texture
  103795. //This part can be improved by adding the possible options of texture
  103796. }
  103797. else if (key === "map_ka" && material) {
  103798. // ambient texture map with a loaded image
  103799. //We must first get the folder of the image
  103800. material.ambientTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  103801. }
  103802. else if (key === "map_kd" && material) {
  103803. // Diffuse texture map with a loaded image
  103804. material.diffuseTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  103805. }
  103806. else if (key === "map_ks" && material) {
  103807. // Specular texture map with a loaded image
  103808. //We must first get the folder of the image
  103809. material.specularTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  103810. }
  103811. else if (key === "map_ns") {
  103812. //Specular
  103813. //Specular highlight component
  103814. //We must first get the folder of the image
  103815. //
  103816. //Not supported by BABYLON
  103817. //
  103818. // continue;
  103819. }
  103820. else if (key === "map_bump" && material) {
  103821. //The bump texture
  103822. material.bumpTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  103823. }
  103824. else if (key === "map_d" && material) {
  103825. // The dissolve of the material
  103826. material.opacityTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  103827. //Options for illumination
  103828. }
  103829. else if (key === "illum") {
  103830. //Illumination
  103831. if (value === "0") {
  103832. //That mean Kd == Kd
  103833. }
  103834. else if (value === "1") {
  103835. //Color on and Ambient on
  103836. }
  103837. else if (value === "2") {
  103838. //Highlight on
  103839. }
  103840. else if (value === "3") {
  103841. //Reflection on and Ray trace on
  103842. }
  103843. else if (value === "4") {
  103844. //Transparency: Glass on, Reflection: Ray trace on
  103845. }
  103846. else if (value === "5") {
  103847. //Reflection: Fresnel on and Ray trace on
  103848. }
  103849. else if (value === "6") {
  103850. //Transparency: Refraction on, Reflection: Fresnel off and Ray trace on
  103851. }
  103852. else if (value === "7") {
  103853. //Transparency: Refraction on, Reflection: Fresnel on and Ray trace on
  103854. }
  103855. else if (value === "8") {
  103856. //Reflection on and Ray trace off
  103857. }
  103858. else if (value === "9") {
  103859. //Transparency: Glass on, Reflection: Ray trace off
  103860. }
  103861. else if (value === "10") {
  103862. //Casts shadows onto invisible surfaces
  103863. }
  103864. }
  103865. else {
  103866. // console.log("Unhandled expression at line : " + i +'\n' + "with value : " + line);
  103867. }
  103868. }
  103869. //At the end of the file, add the last material
  103870. if (material) {
  103871. this.materials.push(material);
  103872. }
  103873. };
  103874. /**
  103875. * Gets the texture for the material.
  103876. *
  103877. * If the material is imported from input file,
  103878. * We sanitize the url to ensure it takes the textre from aside the material.
  103879. *
  103880. * @param rootUrl The root url to load from
  103881. * @param value The value stored in the mtl
  103882. * @return The Texture
  103883. */
  103884. MTLFileLoader._getTexture = function (rootUrl, value, scene) {
  103885. if (!value) {
  103886. return null;
  103887. }
  103888. var url = rootUrl;
  103889. // Load from input file.
  103890. if (rootUrl === "file:") {
  103891. var lastDelimiter = value.lastIndexOf("\\");
  103892. if (lastDelimiter === -1) {
  103893. lastDelimiter = value.lastIndexOf("/");
  103894. }
  103895. if (lastDelimiter > -1) {
  103896. url += value.substr(lastDelimiter + 1);
  103897. }
  103898. else {
  103899. url += value;
  103900. }
  103901. }
  103902. // Not from input file.
  103903. else {
  103904. url += value;
  103905. }
  103906. return new BABYLON.Texture(url, scene);
  103907. };
  103908. return MTLFileLoader;
  103909. }());
  103910. BABYLON.MTLFileLoader = MTLFileLoader;
  103911. var OBJFileLoader = /** @class */ (function () {
  103912. function OBJFileLoader() {
  103913. this.name = "obj";
  103914. this.extensions = ".obj";
  103915. this.obj = /^o/;
  103916. this.group = /^g/;
  103917. this.mtllib = /^mtllib /;
  103918. this.usemtl = /^usemtl /;
  103919. this.smooth = /^s /;
  103920. this.vertexPattern = /v( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  103921. // vn float float float
  103922. this.normalPattern = /vn( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  103923. // vt float float
  103924. this.uvPattern = /vt( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  103925. // f vertex vertex vertex ...
  103926. this.facePattern1 = /f\s+(([\d]{1,}[\s]?){3,})+/;
  103927. // f vertex/uvs vertex/uvs vertex/uvs ...
  103928. this.facePattern2 = /f\s+((([\d]{1,}\/[\d]{1,}[\s]?){3,})+)/;
  103929. // f vertex/uvs/normal vertex/uvs/normal vertex/uvs/normal ...
  103930. this.facePattern3 = /f\s+((([\d]{1,}\/[\d]{1,}\/[\d]{1,}[\s]?){3,})+)/;
  103931. // f vertex//normal vertex//normal vertex//normal ...
  103932. this.facePattern4 = /f\s+((([\d]{1,}\/\/[\d]{1,}[\s]?){3,})+)/;
  103933. }
  103934. /**
  103935. * Calls synchronously the MTL file attached to this obj.
  103936. * Load function or importMesh function don't enable to load 2 files in the same time asynchronously.
  103937. * Without this function materials are not displayed in the first frame (but displayed after).
  103938. * In consequence it is impossible to get material information in your HTML file
  103939. *
  103940. * @param url The URL of the MTL file
  103941. * @param rootUrl
  103942. * @param onSuccess Callback function to be called when the MTL file is loaded
  103943. * @private
  103944. */
  103945. OBJFileLoader.prototype._loadMTL = function (url, rootUrl, onSuccess) {
  103946. //The complete path to the mtl file
  103947. var pathOfFile = BABYLON.Tools.BaseUrl + rootUrl + url;
  103948. // Loads through the babylon tools to allow fileInput search.
  103949. BABYLON.Tools.LoadFile(pathOfFile, onSuccess, undefined, undefined, false, function () { console.warn("Error - Unable to load " + pathOfFile); });
  103950. };
  103951. OBJFileLoader.prototype.importMesh = function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  103952. //get the meshes from OBJ file
  103953. var loadedMeshes = this._parseSolid(meshesNames, scene, data, rootUrl);
  103954. //Push meshes from OBJ file into the variable mesh of this function
  103955. if (meshes) {
  103956. loadedMeshes.forEach(function (mesh) {
  103957. meshes.push(mesh);
  103958. });
  103959. }
  103960. return true;
  103961. };
  103962. OBJFileLoader.prototype.load = function (scene, data, rootUrl) {
  103963. //Get the 3D model
  103964. return this.importMesh(null, scene, data, rootUrl, null, null, null);
  103965. };
  103966. OBJFileLoader.prototype.loadAssetContainer = function (scene, data, rootUrl, onError) {
  103967. var container = new BABYLON.AssetContainer(scene);
  103968. this.importMesh(null, scene, data, rootUrl, container.meshes, null, null);
  103969. container.removeAllFromScene();
  103970. return container;
  103971. };
  103972. /**
  103973. * Read the OBJ file and create an Array of meshes.
  103974. * Each mesh contains all information given by the OBJ and the MTL file.
  103975. * i.e. vertices positions and indices, optional normals values, optional UV values, optional material
  103976. *
  103977. * @param meshesNames
  103978. * @param scene BABYLON.Scene The scene where are displayed the data
  103979. * @param data String The content of the obj file
  103980. * @param rootUrl String The path to the folder
  103981. * @returns Array<AbstractMesh>
  103982. * @private
  103983. */
  103984. OBJFileLoader.prototype._parseSolid = function (meshesNames, scene, data, rootUrl) {
  103985. var positions = []; //values for the positions of vertices
  103986. var normals = []; //Values for the normals
  103987. var uvs = []; //Values for the textures
  103988. var meshesFromObj = []; //[mesh] Contains all the obj meshes
  103989. var handledMesh; //The current mesh of meshes array
  103990. var indicesForBabylon = []; //The list of indices for VertexData
  103991. var wrappedPositionForBabylon = []; //The list of position in vectors
  103992. var wrappedUvsForBabylon = []; //Array with all value of uvs to match with the indices
  103993. var wrappedNormalsForBabylon = []; //Array with all value of normals to match with the indices
  103994. var tuplePosNorm = []; //Create a tuple with indice of Position, Normal, UV [pos, norm, uvs]
  103995. var curPositionInIndices = 0;
  103996. var hasMeshes = false; //Meshes are defined in the file
  103997. var unwrappedPositionsForBabylon = []; //Value of positionForBabylon w/o Vector3() [x,y,z]
  103998. var unwrappedNormalsForBabylon = []; //Value of normalsForBabylon w/o Vector3() [x,y,z]
  103999. var unwrappedUVForBabylon = []; //Value of uvsForBabylon w/o Vector3() [x,y,z]
  104000. var triangles = []; //Indices from new triangles coming from polygons
  104001. var materialNameFromObj = ""; //The name of the current material
  104002. var fileToLoad = ""; //The name of the mtlFile to load
  104003. var materialsFromMTLFile = new MTLFileLoader();
  104004. var objMeshName = ""; //The name of the current obj mesh
  104005. var increment = 1; //Id for meshes created by the multimaterial
  104006. var isFirstMaterial = true;
  104007. /**
  104008. * Search for obj in the given array.
  104009. * This function is called to check if a couple of data already exists in an array.
  104010. *
  104011. * If found, returns the index of the founded tuple index. Returns -1 if not found
  104012. * @param arr Array<{ normals: Array<number>, idx: Array<number> }>
  104013. * @param obj Array<number>
  104014. * @returns {boolean}
  104015. */
  104016. var isInArray = function (arr, obj) {
  104017. if (!arr[obj[0]])
  104018. arr[obj[0]] = { normals: [], idx: [] };
  104019. var idx = arr[obj[0]].normals.indexOf(obj[1]);
  104020. return idx === -1 ? -1 : arr[obj[0]].idx[idx];
  104021. };
  104022. var isInArrayUV = function (arr, obj) {
  104023. if (!arr[obj[0]])
  104024. arr[obj[0]] = { normals: [], idx: [], uv: [] };
  104025. var idx = arr[obj[0]].normals.indexOf(obj[1]);
  104026. if (idx != 1 && (obj[2] == arr[obj[0]].uv[idx])) {
  104027. return arr[obj[0]].idx[idx];
  104028. }
  104029. return -1;
  104030. };
  104031. /**
  104032. * This function set the data for each triangle.
  104033. * Data are position, normals and uvs
  104034. * If a tuple of (position, normal) is not set, add the data into the corresponding array
  104035. * If the tuple already exist, add only their indice
  104036. *
  104037. * @param indicePositionFromObj Integer The index in positions array
  104038. * @param indiceUvsFromObj Integer The index in uvs array
  104039. * @param indiceNormalFromObj Integer The index in normals array
  104040. * @param positionVectorFromOBJ Vector3 The value of position at index objIndice
  104041. * @param textureVectorFromOBJ Vector3 The value of uvs
  104042. * @param normalsVectorFromOBJ Vector3 The value of normals at index objNormale
  104043. */
  104044. var setData = function (indicePositionFromObj, indiceUvsFromObj, indiceNormalFromObj, positionVectorFromOBJ, textureVectorFromOBJ, normalsVectorFromOBJ) {
  104045. //Check if this tuple already exists in the list of tuples
  104046. var _index;
  104047. if (OBJFileLoader.OPTIMIZE_WITH_UV) {
  104048. _index = isInArrayUV(tuplePosNorm, [
  104049. indicePositionFromObj,
  104050. indiceNormalFromObj,
  104051. indiceUvsFromObj
  104052. ]);
  104053. }
  104054. else {
  104055. _index = isInArray(tuplePosNorm, [
  104056. indicePositionFromObj,
  104057. indiceNormalFromObj
  104058. ]);
  104059. }
  104060. //If it not exists
  104061. if (_index == -1) {
  104062. //Add an new indice.
  104063. //The array of indices is only an array with his length equal to the number of triangles - 1.
  104064. //We add vertices data in this order
  104065. indicesForBabylon.push(wrappedPositionForBabylon.length);
  104066. //Push the position of vertice for Babylon
  104067. //Each element is a BABYLON.Vector3(x,y,z)
  104068. wrappedPositionForBabylon.push(positionVectorFromOBJ);
  104069. //Push the uvs for Babylon
  104070. //Each element is a BABYLON.Vector3(u,v)
  104071. wrappedUvsForBabylon.push(textureVectorFromOBJ);
  104072. //Push the normals for Babylon
  104073. //Each element is a BABYLON.Vector3(x,y,z)
  104074. wrappedNormalsForBabylon.push(normalsVectorFromOBJ);
  104075. //Add the tuple in the comparison list
  104076. tuplePosNorm[indicePositionFromObj].normals.push(indiceNormalFromObj);
  104077. tuplePosNorm[indicePositionFromObj].idx.push(curPositionInIndices++);
  104078. if (OBJFileLoader.OPTIMIZE_WITH_UV)
  104079. tuplePosNorm[indicePositionFromObj].uv.push(indiceUvsFromObj);
  104080. }
  104081. else {
  104082. //The tuple already exists
  104083. //Add the index of the already existing tuple
  104084. //At this index we can get the value of position, normal and uvs of vertex
  104085. indicesForBabylon.push(_index);
  104086. }
  104087. };
  104088. /**
  104089. * Transform BABYLON.Vector() object onto 3 digits in an array
  104090. */
  104091. var unwrapData = function () {
  104092. //Every array has the same length
  104093. for (var l = 0; l < wrappedPositionForBabylon.length; l++) {
  104094. //Push the x, y, z values of each element in the unwrapped array
  104095. unwrappedPositionsForBabylon.push(wrappedPositionForBabylon[l].x, wrappedPositionForBabylon[l].y, wrappedPositionForBabylon[l].z);
  104096. unwrappedNormalsForBabylon.push(wrappedNormalsForBabylon[l].x, wrappedNormalsForBabylon[l].y, wrappedNormalsForBabylon[l].z);
  104097. unwrappedUVForBabylon.push(wrappedUvsForBabylon[l].x, wrappedUvsForBabylon[l].y); //z is an optional value not supported by BABYLON
  104098. }
  104099. // Reset arrays for the next new meshes
  104100. wrappedPositionForBabylon = [];
  104101. wrappedNormalsForBabylon = [];
  104102. wrappedUvsForBabylon = [];
  104103. tuplePosNorm = [];
  104104. curPositionInIndices = 0;
  104105. };
  104106. /**
  104107. * Create triangles from polygons by recursion
  104108. * The best to understand how it works is to draw it in the same time you get the recursion.
  104109. * It is important to notice that a triangle is a polygon
  104110. * We get 4 patterns of face defined in OBJ File :
  104111. * facePattern1 = ["1","2","3","4","5","6"]
  104112. * facePattern2 = ["1/1","2/2","3/3","4/4","5/5","6/6"]
  104113. * facePattern3 = ["1/1/1","2/2/2","3/3/3","4/4/4","5/5/5","6/6/6"]
  104114. * facePattern4 = ["1//1","2//2","3//3","4//4","5//5","6//6"]
  104115. * Each pattern is divided by the same method
  104116. * @param face Array[String] The indices of elements
  104117. * @param v Integer The variable to increment
  104118. */
  104119. var getTriangles = function (face, v) {
  104120. //Work for each element of the array
  104121. if (v + 1 < face.length) {
  104122. //Add on the triangle variable the indexes to obtain triangles
  104123. triangles.push(face[0], face[v], face[v + 1]);
  104124. //Incrementation for recursion
  104125. v += 1;
  104126. //Recursion
  104127. getTriangles(face, v);
  104128. }
  104129. //Result obtained after 2 iterations:
  104130. //Pattern1 => triangle = ["1","2","3","1","3","4"];
  104131. //Pattern2 => triangle = ["1/1","2/2","3/3","1/1","3/3","4/4"];
  104132. //Pattern3 => triangle = ["1/1/1","2/2/2","3/3/3","1/1/1","3/3/3","4/4/4"];
  104133. //Pattern4 => triangle = ["1//1","2//2","3//3","1//1","3//3","4//4"];
  104134. };
  104135. /**
  104136. * Create triangles and push the data for each polygon for the pattern 1
  104137. * In this pattern we get vertice positions
  104138. * @param face
  104139. * @param v
  104140. */
  104141. var setDataForCurrentFaceWithPattern1 = function (face, v) {
  104142. //Get the indices of triangles for each polygon
  104143. getTriangles(face, v);
  104144. //For each element in the triangles array.
  104145. //This var could contains 1 to an infinity of triangles
  104146. for (var k = 0; k < triangles.length; k++) {
  104147. // Set position indice
  104148. var indicePositionFromObj = parseInt(triangles[k]) - 1;
  104149. setData(indicePositionFromObj, 0, 0, //In the pattern 1, normals and uvs are not defined
  104150. positions[indicePositionFromObj], //Get the vectors data
  104151. BABYLON.Vector2.Zero(), BABYLON.Vector3.Up() //Create default vectors
  104152. );
  104153. }
  104154. //Reset variable for the next line
  104155. triangles = [];
  104156. };
  104157. /**
  104158. * Create triangles and push the data for each polygon for the pattern 2
  104159. * In this pattern we get vertice positions and uvsu
  104160. * @param face
  104161. * @param v
  104162. */
  104163. var setDataForCurrentFaceWithPattern2 = function (face, v) {
  104164. //Get the indices of triangles for each polygon
  104165. getTriangles(face, v);
  104166. for (var k = 0; k < triangles.length; k++) {
  104167. //triangle[k] = "1/1"
  104168. //Split the data for getting position and uv
  104169. var point = triangles[k].split("/"); // ["1", "1"]
  104170. //Set position indice
  104171. var indicePositionFromObj = parseInt(point[0]) - 1;
  104172. //Set uv indice
  104173. var indiceUvsFromObj = parseInt(point[1]) - 1;
  104174. setData(indicePositionFromObj, indiceUvsFromObj, 0, //Default value for normals
  104175. positions[indicePositionFromObj], //Get the values for each element
  104176. uvs[indiceUvsFromObj], BABYLON.Vector3.Up() //Default value for normals
  104177. );
  104178. }
  104179. //Reset variable for the next line
  104180. triangles = [];
  104181. };
  104182. /**
  104183. * Create triangles and push the data for each polygon for the pattern 3
  104184. * In this pattern we get vertice positions, uvs and normals
  104185. * @param face
  104186. * @param v
  104187. */
  104188. var setDataForCurrentFaceWithPattern3 = function (face, v) {
  104189. //Get the indices of triangles for each polygon
  104190. getTriangles(face, v);
  104191. for (var k = 0; k < triangles.length; k++) {
  104192. //triangle[k] = "1/1/1"
  104193. //Split the data for getting position, uv, and normals
  104194. var point = triangles[k].split("/"); // ["1", "1", "1"]
  104195. // Set position indice
  104196. var indicePositionFromObj = parseInt(point[0]) - 1;
  104197. // Set uv indice
  104198. var indiceUvsFromObj = parseInt(point[1]) - 1;
  104199. // Set normal indice
  104200. var indiceNormalFromObj = parseInt(point[2]) - 1;
  104201. setData(indicePositionFromObj, indiceUvsFromObj, indiceNormalFromObj, positions[indicePositionFromObj], uvs[indiceUvsFromObj], normals[indiceNormalFromObj] //Set the vector for each component
  104202. );
  104203. }
  104204. //Reset variable for the next line
  104205. triangles = [];
  104206. };
  104207. /**
  104208. * Create triangles and push the data for each polygon for the pattern 4
  104209. * In this pattern we get vertice positions and normals
  104210. * @param face
  104211. * @param v
  104212. */
  104213. var setDataForCurrentFaceWithPattern4 = function (face, v) {
  104214. getTriangles(face, v);
  104215. for (var k = 0; k < triangles.length; k++) {
  104216. //triangle[k] = "1//1"
  104217. //Split the data for getting position and normals
  104218. var point = triangles[k].split("//"); // ["1", "1"]
  104219. // We check indices, and normals
  104220. var indicePositionFromObj = parseInt(point[0]) - 1;
  104221. var indiceNormalFromObj = parseInt(point[1]) - 1;
  104222. setData(indicePositionFromObj, 1, //Default value for uv
  104223. indiceNormalFromObj, positions[indicePositionFromObj], //Get each vector of data
  104224. BABYLON.Vector2.Zero(), normals[indiceNormalFromObj]);
  104225. }
  104226. //Reset variable for the next line
  104227. triangles = [];
  104228. };
  104229. var addPreviousObjMesh = function () {
  104230. //Check if it is not the first mesh. Otherwise we don't have data.
  104231. if (meshesFromObj.length > 0) {
  104232. //Get the previous mesh for applying the data about the faces
  104233. //=> in obj file, faces definition append after the name of the mesh
  104234. handledMesh = meshesFromObj[meshesFromObj.length - 1];
  104235. //Set the data into Array for the mesh
  104236. unwrapData();
  104237. // Reverse tab. Otherwise face are displayed in the wrong sens
  104238. indicesForBabylon.reverse();
  104239. //Set the information for the mesh
  104240. //Slice the array to avoid rewriting because of the fact this is the same var which be rewrited
  104241. handledMesh.indices = indicesForBabylon.slice();
  104242. handledMesh.positions = unwrappedPositionsForBabylon.slice();
  104243. handledMesh.normals = unwrappedNormalsForBabylon.slice();
  104244. handledMesh.uvs = unwrappedUVForBabylon.slice();
  104245. //Reset the array for the next mesh
  104246. indicesForBabylon = [];
  104247. unwrappedPositionsForBabylon = [];
  104248. unwrappedNormalsForBabylon = [];
  104249. unwrappedUVForBabylon = [];
  104250. }
  104251. };
  104252. //Main function
  104253. //Split the file into lines
  104254. var lines = data.split('\n');
  104255. //Look at each line
  104256. for (var i = 0; i < lines.length; i++) {
  104257. var line = lines[i].trim();
  104258. var result;
  104259. //Comment or newLine
  104260. if (line.length === 0 || line.charAt(0) === '#') {
  104261. continue;
  104262. //Get information about one position possible for the vertices
  104263. }
  104264. else if ((result = this.vertexPattern.exec(line)) !== null) {
  104265. //Create a Vector3 with the position x, y, z
  104266. //Value of result:
  104267. // ["v 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
  104268. //Add the Vector in the list of positions
  104269. positions.push(new BABYLON.Vector3(parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3])));
  104270. }
  104271. else if ((result = this.normalPattern.exec(line)) !== null) {
  104272. //Create a Vector3 with the normals x, y, z
  104273. //Value of result
  104274. // ["vn 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
  104275. //Add the Vector in the list of normals
  104276. normals.push(new BABYLON.Vector3(parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3])));
  104277. }
  104278. else if ((result = this.uvPattern.exec(line)) !== null) {
  104279. //Create a Vector2 with the normals u, v
  104280. //Value of result
  104281. // ["vt 0.1 0.2 0.3", "0.1", "0.2"]
  104282. //Add the Vector in the list of uvs
  104283. uvs.push(new BABYLON.Vector2(parseFloat(result[1]), parseFloat(result[2])));
  104284. //Identify patterns of faces
  104285. //Face could be defined in different type of pattern
  104286. }
  104287. else if ((result = this.facePattern3.exec(line)) !== null) {
  104288. //Value of result:
  104289. //["f 1/1/1 2/2/2 3/3/3", "1/1/1 2/2/2 3/3/3"...]
  104290. //Set the data for this face
  104291. setDataForCurrentFaceWithPattern3(result[1].trim().split(" "), // ["1/1/1", "2/2/2", "3/3/3"]
  104292. 1);
  104293. }
  104294. else if ((result = this.facePattern4.exec(line)) !== null) {
  104295. //Value of result:
  104296. //["f 1//1 2//2 3//3", "1//1 2//2 3//3"...]
  104297. //Set the data for this face
  104298. setDataForCurrentFaceWithPattern4(result[1].trim().split(" "), // ["1//1", "2//2", "3//3"]
  104299. 1);
  104300. }
  104301. else if ((result = this.facePattern2.exec(line)) !== null) {
  104302. //Value of result:
  104303. //["f 1/1 2/2 3/3", "1/1 2/2 3/3"...]
  104304. //Set the data for this face
  104305. setDataForCurrentFaceWithPattern2(result[1].trim().split(" "), // ["1/1", "2/2", "3/3"]
  104306. 1);
  104307. }
  104308. else if ((result = this.facePattern1.exec(line)) !== null) {
  104309. //Value of result
  104310. //["f 1 2 3", "1 2 3"...]
  104311. //Set the data for this face
  104312. setDataForCurrentFaceWithPattern1(result[1].trim().split(" "), // ["1", "2", "3"]
  104313. 1);
  104314. //Define a mesh or an object
  104315. //Each time this keyword is analysed, create a new Object with all data for creating a babylonMesh
  104316. }
  104317. else if (this.group.test(line) || this.obj.test(line)) {
  104318. //Create a new mesh corresponding to the name of the group.
  104319. //Definition of the mesh
  104320. var objMesh =
  104321. //Set the name of the current obj mesh
  104322. {
  104323. name: line.substring(2).trim(),
  104324. indices: undefined,
  104325. positions: undefined,
  104326. normals: undefined,
  104327. uvs: undefined,
  104328. materialName: ""
  104329. };
  104330. addPreviousObjMesh();
  104331. //Push the last mesh created with only the name
  104332. meshesFromObj.push(objMesh);
  104333. //Set this variable to indicate that now meshesFromObj has objects defined inside
  104334. hasMeshes = true;
  104335. isFirstMaterial = true;
  104336. increment = 1;
  104337. //Keyword for applying a material
  104338. }
  104339. else if (this.usemtl.test(line)) {
  104340. //Get the name of the material
  104341. materialNameFromObj = line.substring(7).trim();
  104342. //If this new material is in the same mesh
  104343. if (!isFirstMaterial) {
  104344. //Set the data for the previous mesh
  104345. addPreviousObjMesh();
  104346. //Create a new mesh
  104347. var objMesh =
  104348. //Set the name of the current obj mesh
  104349. {
  104350. name: objMeshName + "_mm" + increment.toString(),
  104351. indices: undefined,
  104352. positions: undefined,
  104353. normals: undefined,
  104354. uvs: undefined,
  104355. materialName: materialNameFromObj
  104356. };
  104357. increment++;
  104358. //If meshes are already defined
  104359. meshesFromObj.push(objMesh);
  104360. }
  104361. //Set the material name if the previous line define a mesh
  104362. if (hasMeshes && isFirstMaterial) {
  104363. //Set the material name to the previous mesh (1 material per mesh)
  104364. meshesFromObj[meshesFromObj.length - 1].materialName = materialNameFromObj;
  104365. isFirstMaterial = false;
  104366. }
  104367. //Keyword for loading the mtl file
  104368. }
  104369. else if (this.mtllib.test(line)) {
  104370. //Get the name of mtl file
  104371. fileToLoad = line.substring(7).trim();
  104372. //Apply smoothing
  104373. }
  104374. else if (this.smooth.test(line)) {
  104375. // smooth shading => apply smoothing
  104376. //Toda y I don't know it work with babylon and with obj.
  104377. //With the obj file an integer is set
  104378. }
  104379. else {
  104380. //If there is another possibility
  104381. console.log("Unhandled expression at line : " + line);
  104382. }
  104383. }
  104384. //At the end of the file, add the last mesh into the meshesFromObj array
  104385. if (hasMeshes) {
  104386. //Set the data for the last mesh
  104387. handledMesh = meshesFromObj[meshesFromObj.length - 1];
  104388. //Reverse indices for displaying faces in the good sens
  104389. indicesForBabylon.reverse();
  104390. //Get the good array
  104391. unwrapData();
  104392. //Set array
  104393. handledMesh.indices = indicesForBabylon;
  104394. handledMesh.positions = unwrappedPositionsForBabylon;
  104395. handledMesh.normals = unwrappedNormalsForBabylon;
  104396. handledMesh.uvs = unwrappedUVForBabylon;
  104397. }
  104398. //If any o or g keyword found, create a mesj with a random id
  104399. if (!hasMeshes) {
  104400. // reverse tab of indices
  104401. indicesForBabylon.reverse();
  104402. //Get positions normals uvs
  104403. unwrapData();
  104404. //Set data for one mesh
  104405. meshesFromObj.push({
  104406. name: BABYLON.Geometry.RandomId(),
  104407. indices: indicesForBabylon,
  104408. positions: unwrappedPositionsForBabylon,
  104409. normals: unwrappedNormalsForBabylon,
  104410. uvs: unwrappedUVForBabylon,
  104411. materialName: materialNameFromObj
  104412. });
  104413. }
  104414. //Create a BABYLON.Mesh list
  104415. var babylonMeshesArray = []; //The mesh for babylon
  104416. var materialToUse = new Array();
  104417. //Set data for each mesh
  104418. for (var j = 0; j < meshesFromObj.length; j++) {
  104419. //check meshesNames (stlFileLoader)
  104420. if (meshesNames && meshesFromObj[j].name) {
  104421. if (meshesNames instanceof Array) {
  104422. if (meshesNames.indexOf(meshesFromObj[j].name) == -1) {
  104423. continue;
  104424. }
  104425. }
  104426. else {
  104427. if (meshesFromObj[j].name !== meshesNames) {
  104428. continue;
  104429. }
  104430. }
  104431. }
  104432. //Get the current mesh
  104433. //Set the data with VertexBuffer for each mesh
  104434. handledMesh = meshesFromObj[j];
  104435. //Create a BABYLON.Mesh with the name of the obj mesh
  104436. var babylonMesh = new BABYLON.Mesh(meshesFromObj[j].name, scene);
  104437. //Push the name of the material to an array
  104438. //This is indispensable for the importMesh function
  104439. materialToUse.push(meshesFromObj[j].materialName);
  104440. var vertexData = new BABYLON.VertexData(); //The container for the values
  104441. //Set the data for the babylonMesh
  104442. vertexData.positions = handledMesh.positions;
  104443. vertexData.normals = handledMesh.normals;
  104444. vertexData.uvs = handledMesh.uvs;
  104445. vertexData.indices = handledMesh.indices;
  104446. //Set the data from the VertexBuffer to the current BABYLON.Mesh
  104447. vertexData.applyToMesh(babylonMesh);
  104448. if (OBJFileLoader.INVERT_Y) {
  104449. babylonMesh.scaling.y *= -1;
  104450. }
  104451. //Push the mesh into an array
  104452. babylonMeshesArray.push(babylonMesh);
  104453. }
  104454. //load the materials
  104455. //Check if we have a file to load
  104456. if (fileToLoad !== "") {
  104457. //Load the file synchronously
  104458. this._loadMTL(fileToLoad, rootUrl, function (dataLoaded) {
  104459. //Create materials thanks MTLLoader function
  104460. materialsFromMTLFile.parseMTL(scene, dataLoaded, rootUrl);
  104461. //Look at each material loaded in the mtl file
  104462. for (var n = 0; n < materialsFromMTLFile.materials.length; n++) {
  104463. //Three variables to get all meshes with the same material
  104464. var startIndex = 0;
  104465. var _indices = [];
  104466. var _index;
  104467. //The material from MTL file is used in the meshes loaded
  104468. //Push the indice in an array
  104469. //Check if the material is not used for another mesh
  104470. while ((_index = materialToUse.indexOf(materialsFromMTLFile.materials[n].name, startIndex)) > -1) {
  104471. _indices.push(_index);
  104472. startIndex = _index + 1;
  104473. }
  104474. //If the material is not used dispose it
  104475. if (_index == -1 && _indices.length == 0) {
  104476. //If the material is not needed, remove it
  104477. materialsFromMTLFile.materials[n].dispose();
  104478. }
  104479. else {
  104480. for (var o = 0; o < _indices.length; o++) {
  104481. //Apply the material to the BABYLON.Mesh for each mesh with the material
  104482. babylonMeshesArray[_indices[o]].material = materialsFromMTLFile.materials[n];
  104483. }
  104484. }
  104485. }
  104486. });
  104487. }
  104488. //Return an array with all BABYLON.Mesh
  104489. return babylonMeshesArray;
  104490. };
  104491. OBJFileLoader.OPTIMIZE_WITH_UV = false;
  104492. OBJFileLoader.INVERT_Y = false;
  104493. return OBJFileLoader;
  104494. }());
  104495. BABYLON.OBJFileLoader = OBJFileLoader;
  104496. if (BABYLON.SceneLoader) {
  104497. //Add this loader into the register plugin
  104498. BABYLON.SceneLoader.RegisterPlugin(new OBJFileLoader());
  104499. }
  104500. })(BABYLON || (BABYLON = {}));
  104501. //# sourceMappingURL=babylon.objFileLoader.js.map
  104502. var BABYLON;
  104503. (function (BABYLON) {
  104504. /**
  104505. * Mode that determines the coordinate system to use.
  104506. */
  104507. var GLTFLoaderCoordinateSystemMode;
  104508. (function (GLTFLoaderCoordinateSystemMode) {
  104509. /**
  104510. * Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene.
  104511. */
  104512. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  104513. /**
  104514. * Sets the useRightHandedSystem flag on the scene.
  104515. */
  104516. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 1] = "FORCE_RIGHT_HANDED";
  104517. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  104518. /**
  104519. * Mode that determines what animations will start.
  104520. */
  104521. var GLTFLoaderAnimationStartMode;
  104522. (function (GLTFLoaderAnimationStartMode) {
  104523. /**
  104524. * No animation will start.
  104525. */
  104526. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["NONE"] = 0] = "NONE";
  104527. /**
  104528. * The first animation will start.
  104529. */
  104530. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["FIRST"] = 1] = "FIRST";
  104531. /**
  104532. * All animations will start.
  104533. */
  104534. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["ALL"] = 2] = "ALL";
  104535. })(GLTFLoaderAnimationStartMode = BABYLON.GLTFLoaderAnimationStartMode || (BABYLON.GLTFLoaderAnimationStartMode = {}));
  104536. /**
  104537. * Loader state.
  104538. */
  104539. var GLTFLoaderState;
  104540. (function (GLTFLoaderState) {
  104541. /**
  104542. * The asset is loading.
  104543. */
  104544. GLTFLoaderState[GLTFLoaderState["LOADING"] = 0] = "LOADING";
  104545. /**
  104546. * The asset is ready for rendering.
  104547. */
  104548. GLTFLoaderState[GLTFLoaderState["READY"] = 1] = "READY";
  104549. /**
  104550. * The asset is completely loaded.
  104551. */
  104552. GLTFLoaderState[GLTFLoaderState["COMPLETE"] = 2] = "COMPLETE";
  104553. })(GLTFLoaderState = BABYLON.GLTFLoaderState || (BABYLON.GLTFLoaderState = {}));
  104554. /**
  104555. * File loader for loading glTF files into a scene.
  104556. */
  104557. var GLTFFileLoader = /** @class */ (function () {
  104558. function GLTFFileLoader() {
  104559. // #region Common options
  104560. /**
  104561. * Raised when the asset has been parsed
  104562. */
  104563. this.onParsedObservable = new BABYLON.Observable();
  104564. // #endregion
  104565. // #region V2 options
  104566. /**
  104567. * The coordinate system mode. Defaults to AUTO.
  104568. */
  104569. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  104570. /**
  104571. * The animation start mode. Defaults to FIRST.
  104572. */
  104573. this.animationStartMode = GLTFLoaderAnimationStartMode.FIRST;
  104574. /**
  104575. * Defines if the loader should compile materials before raising the success callback. Defaults to false.
  104576. */
  104577. this.compileMaterials = false;
  104578. /**
  104579. * Defines if the loader should also compile materials with clip planes. Defaults to false.
  104580. */
  104581. this.useClipPlane = false;
  104582. /**
  104583. * Defines if the loader should compile shadow generators before raising the success callback. Defaults to false.
  104584. */
  104585. this.compileShadowGenerators = false;
  104586. /**
  104587. * Defines if the Alpha blended materials are only applied as coverage.
  104588. * If false, (default) The luminance of each pixel will reduce its opacity to simulate the behaviour of most physical materials.
  104589. * If true, no extra effects are applied to transparent pixels.
  104590. */
  104591. this.transparencyAsCoverage = false;
  104592. /** @hidden */
  104593. this._normalizeAnimationGroupsToBeginAtZero = true;
  104594. /**
  104595. * Function called before loading a url referenced by the asset.
  104596. */
  104597. this.preprocessUrlAsync = function (url) { return Promise.resolve(url); };
  104598. /**
  104599. * Observable raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  104600. */
  104601. this.onMeshLoadedObservable = new BABYLON.Observable();
  104602. /**
  104603. * Observable raised when the loader creates a texture after parsing the glTF properties of the texture.
  104604. */
  104605. this.onTextureLoadedObservable = new BABYLON.Observable();
  104606. /**
  104607. * Observable raised when the loader creates a material after parsing the glTF properties of the material.
  104608. */
  104609. this.onMaterialLoadedObservable = new BABYLON.Observable();
  104610. /**
  104611. * Observable raised when the loader creates a camera after parsing the glTF properties of the camera.
  104612. */
  104613. this.onCameraLoadedObservable = new BABYLON.Observable();
  104614. /**
  104615. * Observable raised when the asset is completely loaded, immediately before the loader is disposed.
  104616. * For assets with LODs, raised when all of the LODs are complete.
  104617. * For assets without LODs, raised when the model is complete, immediately after the loader resolves the returned promise.
  104618. */
  104619. this.onCompleteObservable = new BABYLON.Observable();
  104620. /**
  104621. * Observable raised after the loader is disposed.
  104622. */
  104623. this.onDisposeObservable = new BABYLON.Observable();
  104624. /**
  104625. * Observable raised after a loader extension is created.
  104626. * Set additional options for a loader extension in this event.
  104627. */
  104628. this.onExtensionLoadedObservable = new BABYLON.Observable();
  104629. // #endregion
  104630. this._loader = null;
  104631. /**
  104632. * Name of the loader ("gltf")
  104633. */
  104634. this.name = "gltf";
  104635. /**
  104636. * Supported file extensions of the loader (.gltf, .glb)
  104637. */
  104638. this.extensions = {
  104639. ".gltf": { isBinary: false },
  104640. ".glb": { isBinary: true }
  104641. };
  104642. this._logIndentLevel = 0;
  104643. this._loggingEnabled = false;
  104644. /** @hidden */
  104645. this._log = this._logDisabled;
  104646. this._capturePerformanceCounters = false;
  104647. /** @hidden */
  104648. this._startPerformanceCounter = this._startPerformanceCounterDisabled;
  104649. /** @hidden */
  104650. this._endPerformanceCounter = this._endPerformanceCounterDisabled;
  104651. }
  104652. Object.defineProperty(GLTFFileLoader.prototype, "onParsed", {
  104653. /**
  104654. * Raised when the asset has been parsed
  104655. */
  104656. set: function (callback) {
  104657. if (this._onParsedObserver) {
  104658. this.onParsedObservable.remove(this._onParsedObserver);
  104659. }
  104660. this._onParsedObserver = this.onParsedObservable.add(callback);
  104661. },
  104662. enumerable: true,
  104663. configurable: true
  104664. });
  104665. Object.defineProperty(GLTFFileLoader.prototype, "onMeshLoaded", {
  104666. /**
  104667. * Callback raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  104668. */
  104669. set: function (callback) {
  104670. if (this._onMeshLoadedObserver) {
  104671. this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver);
  104672. }
  104673. this._onMeshLoadedObserver = this.onMeshLoadedObservable.add(callback);
  104674. },
  104675. enumerable: true,
  104676. configurable: true
  104677. });
  104678. Object.defineProperty(GLTFFileLoader.prototype, "onTextureLoaded", {
  104679. /**
  104680. * Callback raised when the loader creates a texture after parsing the glTF properties of the texture.
  104681. */
  104682. set: function (callback) {
  104683. if (this._onTextureLoadedObserver) {
  104684. this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver);
  104685. }
  104686. this._onTextureLoadedObserver = this.onTextureLoadedObservable.add(callback);
  104687. },
  104688. enumerable: true,
  104689. configurable: true
  104690. });
  104691. Object.defineProperty(GLTFFileLoader.prototype, "onMaterialLoaded", {
  104692. /**
  104693. * Callback raised when the loader creates a material after parsing the glTF properties of the material.
  104694. */
  104695. set: function (callback) {
  104696. if (this._onMaterialLoadedObserver) {
  104697. this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver);
  104698. }
  104699. this._onMaterialLoadedObserver = this.onMaterialLoadedObservable.add(callback);
  104700. },
  104701. enumerable: true,
  104702. configurable: true
  104703. });
  104704. Object.defineProperty(GLTFFileLoader.prototype, "onCameraLoaded", {
  104705. /**
  104706. * Callback raised when the loader creates a camera after parsing the glTF properties of the camera.
  104707. */
  104708. set: function (callback) {
  104709. if (this._onCameraLoadedObserver) {
  104710. this.onCameraLoadedObservable.remove(this._onCameraLoadedObserver);
  104711. }
  104712. this._onCameraLoadedObserver = this.onCameraLoadedObservable.add(callback);
  104713. },
  104714. enumerable: true,
  104715. configurable: true
  104716. });
  104717. Object.defineProperty(GLTFFileLoader.prototype, "onComplete", {
  104718. /**
  104719. * Callback raised when the asset is completely loaded, immediately before the loader is disposed.
  104720. */
  104721. set: function (callback) {
  104722. if (this._onCompleteObserver) {
  104723. this.onCompleteObservable.remove(this._onCompleteObserver);
  104724. }
  104725. this._onCompleteObserver = this.onCompleteObservable.add(callback);
  104726. },
  104727. enumerable: true,
  104728. configurable: true
  104729. });
  104730. Object.defineProperty(GLTFFileLoader.prototype, "onDispose", {
  104731. /**
  104732. * Callback raised after the loader is disposed.
  104733. */
  104734. set: function (callback) {
  104735. if (this._onDisposeObserver) {
  104736. this.onDisposeObservable.remove(this._onDisposeObserver);
  104737. }
  104738. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  104739. },
  104740. enumerable: true,
  104741. configurable: true
  104742. });
  104743. Object.defineProperty(GLTFFileLoader.prototype, "onExtensionLoaded", {
  104744. /**
  104745. * Callback raised after a loader extension is created.
  104746. */
  104747. set: function (callback) {
  104748. if (this._onExtensionLoadedObserver) {
  104749. this.onExtensionLoadedObservable.remove(this._onExtensionLoadedObserver);
  104750. }
  104751. this._onExtensionLoadedObserver = this.onExtensionLoadedObservable.add(callback);
  104752. },
  104753. enumerable: true,
  104754. configurable: true
  104755. });
  104756. /**
  104757. * Returns a promise that resolves when the asset is completely loaded.
  104758. * @returns a promise that resolves when the asset is completely loaded.
  104759. */
  104760. GLTFFileLoader.prototype.whenCompleteAsync = function () {
  104761. var _this = this;
  104762. return new Promise(function (resolve) {
  104763. _this.onCompleteObservable.addOnce(function () {
  104764. resolve();
  104765. });
  104766. });
  104767. };
  104768. Object.defineProperty(GLTFFileLoader.prototype, "loaderState", {
  104769. /**
  104770. * The loader state or null if the loader is not active.
  104771. */
  104772. get: function () {
  104773. return this._loader ? this._loader.state : null;
  104774. },
  104775. enumerable: true,
  104776. configurable: true
  104777. });
  104778. Object.defineProperty(GLTFFileLoader.prototype, "loggingEnabled", {
  104779. /**
  104780. * Defines if the loader logging is enabled.
  104781. */
  104782. get: function () {
  104783. return this._loggingEnabled;
  104784. },
  104785. set: function (value) {
  104786. if (this._loggingEnabled === value) {
  104787. return;
  104788. }
  104789. this._loggingEnabled = value;
  104790. if (this._loggingEnabled) {
  104791. this._log = this._logEnabled;
  104792. }
  104793. else {
  104794. this._log = this._logDisabled;
  104795. }
  104796. },
  104797. enumerable: true,
  104798. configurable: true
  104799. });
  104800. Object.defineProperty(GLTFFileLoader.prototype, "capturePerformanceCounters", {
  104801. /**
  104802. * Defines if the loader should capture performance counters.
  104803. */
  104804. get: function () {
  104805. return this._capturePerformanceCounters;
  104806. },
  104807. set: function (value) {
  104808. if (this._capturePerformanceCounters === value) {
  104809. return;
  104810. }
  104811. this._capturePerformanceCounters = value;
  104812. if (this._capturePerformanceCounters) {
  104813. this._startPerformanceCounter = this._startPerformanceCounterEnabled;
  104814. this._endPerformanceCounter = this._endPerformanceCounterEnabled;
  104815. }
  104816. else {
  104817. this._startPerformanceCounter = this._startPerformanceCounterDisabled;
  104818. this._endPerformanceCounter = this._endPerformanceCounterDisabled;
  104819. }
  104820. },
  104821. enumerable: true,
  104822. configurable: true
  104823. });
  104824. /**
  104825. * Disposes the loader, releases resources during load, and cancels any outstanding requests.
  104826. */
  104827. GLTFFileLoader.prototype.dispose = function () {
  104828. if (this._loader) {
  104829. this._loader.dispose();
  104830. this._loader = null;
  104831. }
  104832. this._clear();
  104833. this.onDisposeObservable.notifyObservers(undefined);
  104834. this.onDisposeObservable.clear();
  104835. };
  104836. /** @hidden */
  104837. GLTFFileLoader.prototype._clear = function () {
  104838. this.preprocessUrlAsync = function (url) { return Promise.resolve(url); };
  104839. this.onMeshLoadedObservable.clear();
  104840. this.onTextureLoadedObservable.clear();
  104841. this.onMaterialLoadedObservable.clear();
  104842. this.onCameraLoadedObservable.clear();
  104843. this.onCompleteObservable.clear();
  104844. this.onExtensionLoadedObservable.clear();
  104845. };
  104846. /**
  104847. * Imports one or more meshes from the loaded glTF data and adds them to the scene
  104848. * @param meshesNames a string or array of strings of the mesh names that should be loaded from the file
  104849. * @param scene the scene the meshes should be added to
  104850. * @param data the glTF data to load
  104851. * @param rootUrl root url to load from
  104852. * @param onProgress event that fires when loading progress has occured
  104853. * @returns a promise containg the loaded meshes, particles, skeletons and animations
  104854. */
  104855. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  104856. var _this = this;
  104857. return Promise.resolve().then(function () {
  104858. var loaderData = _this._parse(data);
  104859. _this._loader = _this._getLoader(loaderData);
  104860. return _this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onProgress);
  104861. });
  104862. };
  104863. /**
  104864. * Imports all objects from the loaded glTF data and adds them to the scene
  104865. * @param scene the scene the objects should be added to
  104866. * @param data the glTF data to load
  104867. * @param rootUrl root url to load from
  104868. * @param onProgress event that fires when loading progress has occured
  104869. * @returns a promise which completes when objects have been loaded to the scene
  104870. */
  104871. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  104872. var _this = this;
  104873. return Promise.resolve().then(function () {
  104874. var loaderData = _this._parse(data);
  104875. _this._loader = _this._getLoader(loaderData);
  104876. return _this._loader.loadAsync(scene, loaderData, rootUrl, onProgress);
  104877. });
  104878. };
  104879. /**
  104880. * Load into an asset container.
  104881. * @param scene The scene to load into
  104882. * @param data The data to import
  104883. * @param rootUrl The root url for scene and resources
  104884. * @param onProgress The callback when the load progresses
  104885. * @returns The loaded asset container
  104886. */
  104887. GLTFFileLoader.prototype.loadAssetContainerAsync = function (scene, data, rootUrl, onProgress) {
  104888. var _this = this;
  104889. return Promise.resolve().then(function () {
  104890. var loaderData = _this._parse(data);
  104891. _this._loader = _this._getLoader(loaderData);
  104892. return _this._loader.importMeshAsync(null, scene, loaderData, rootUrl, onProgress).then(function (result) {
  104893. var container = new BABYLON.AssetContainer(scene);
  104894. Array.prototype.push.apply(container.meshes, result.meshes);
  104895. Array.prototype.push.apply(container.particleSystems, result.particleSystems);
  104896. Array.prototype.push.apply(container.skeletons, result.skeletons);
  104897. Array.prototype.push.apply(container.animationGroups, result.animationGroups);
  104898. container.removeAllFromScene();
  104899. return container;
  104900. });
  104901. });
  104902. };
  104903. /**
  104904. * If the data string can be loaded directly.
  104905. * @param data string contianing the file data
  104906. * @returns if the data can be loaded directly
  104907. */
  104908. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  104909. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  104910. };
  104911. /**
  104912. * Instantiates a glTF file loader plugin.
  104913. * @returns the created plugin
  104914. */
  104915. GLTFFileLoader.prototype.createPlugin = function () {
  104916. return new GLTFFileLoader();
  104917. };
  104918. GLTFFileLoader.prototype._parse = function (data) {
  104919. this._startPerformanceCounter("Parse");
  104920. var parsedData;
  104921. if (data instanceof ArrayBuffer) {
  104922. this._log("Parsing binary");
  104923. parsedData = this._parseBinary(data);
  104924. }
  104925. else {
  104926. this._log("Parsing JSON");
  104927. this._log("JSON length: " + data.length);
  104928. parsedData = {
  104929. json: JSON.parse(data),
  104930. bin: null
  104931. };
  104932. }
  104933. this.onParsedObservable.notifyObservers(parsedData);
  104934. this.onParsedObservable.clear();
  104935. this._endPerformanceCounter("Parse");
  104936. return parsedData;
  104937. };
  104938. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  104939. var asset = loaderData.json.asset || {};
  104940. this._log("Asset version: " + asset.version);
  104941. asset.minVersion && this._log("Asset minimum version: " + asset.minVersion);
  104942. asset.generator && this._log("Asset generator: " + asset.generator);
  104943. var version = GLTFFileLoader._parseVersion(asset.version);
  104944. if (!version) {
  104945. throw new Error("Invalid version: " + asset.version);
  104946. }
  104947. if (asset.minVersion !== undefined) {
  104948. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  104949. if (!minVersion) {
  104950. throw new Error("Invalid minimum version: " + asset.minVersion);
  104951. }
  104952. if (GLTFFileLoader._compareVersion(minVersion, { major: 2, minor: 0 }) > 0) {
  104953. throw new Error("Incompatible minimum version: " + asset.minVersion);
  104954. }
  104955. }
  104956. var createLoaders = {
  104957. 1: GLTFFileLoader._CreateGLTFLoaderV1,
  104958. 2: GLTFFileLoader._CreateGLTFLoaderV2
  104959. };
  104960. var createLoader = createLoaders[version.major];
  104961. if (!createLoader) {
  104962. throw new Error("Unsupported version: " + asset.version);
  104963. }
  104964. return createLoader(this);
  104965. };
  104966. GLTFFileLoader.prototype._parseBinary = function (data) {
  104967. var Binary = {
  104968. Magic: 0x46546C67
  104969. };
  104970. this._log("Binary length: " + data.byteLength);
  104971. var binaryReader = new BinaryReader(data);
  104972. var magic = binaryReader.readUint32();
  104973. if (magic !== Binary.Magic) {
  104974. throw new Error("Unexpected magic: " + magic);
  104975. }
  104976. var version = binaryReader.readUint32();
  104977. if (this.loggingEnabled) {
  104978. this._log("Binary version: " + version);
  104979. }
  104980. switch (version) {
  104981. case 1: return this._parseV1(binaryReader);
  104982. case 2: return this._parseV2(binaryReader);
  104983. }
  104984. throw new Error("Unsupported version: " + version);
  104985. };
  104986. GLTFFileLoader.prototype._parseV1 = function (binaryReader) {
  104987. var ContentFormat = {
  104988. JSON: 0
  104989. };
  104990. var length = binaryReader.readUint32();
  104991. if (length != binaryReader.getLength()) {
  104992. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  104993. }
  104994. var contentLength = binaryReader.readUint32();
  104995. var contentFormat = binaryReader.readUint32();
  104996. var content;
  104997. switch (contentFormat) {
  104998. case ContentFormat.JSON: {
  104999. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  105000. break;
  105001. }
  105002. default: {
  105003. throw new Error("Unexpected content format: " + contentFormat);
  105004. }
  105005. }
  105006. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  105007. var body = binaryReader.readUint8Array(bytesRemaining);
  105008. return {
  105009. json: content,
  105010. bin: body
  105011. };
  105012. };
  105013. GLTFFileLoader.prototype._parseV2 = function (binaryReader) {
  105014. var ChunkFormat = {
  105015. JSON: 0x4E4F534A,
  105016. BIN: 0x004E4942
  105017. };
  105018. var length = binaryReader.readUint32();
  105019. if (length !== binaryReader.getLength()) {
  105020. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  105021. }
  105022. // JSON chunk
  105023. var chunkLength = binaryReader.readUint32();
  105024. var chunkFormat = binaryReader.readUint32();
  105025. if (chunkFormat !== ChunkFormat.JSON) {
  105026. throw new Error("First chunk format is not JSON");
  105027. }
  105028. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  105029. // Look for BIN chunk
  105030. var bin = null;
  105031. while (binaryReader.getPosition() < binaryReader.getLength()) {
  105032. var chunkLength_1 = binaryReader.readUint32();
  105033. var chunkFormat_1 = binaryReader.readUint32();
  105034. switch (chunkFormat_1) {
  105035. case ChunkFormat.JSON: {
  105036. throw new Error("Unexpected JSON chunk");
  105037. }
  105038. case ChunkFormat.BIN: {
  105039. bin = binaryReader.readUint8Array(chunkLength_1);
  105040. break;
  105041. }
  105042. default: {
  105043. // ignore unrecognized chunkFormat
  105044. binaryReader.skipBytes(chunkLength_1);
  105045. break;
  105046. }
  105047. }
  105048. }
  105049. return {
  105050. json: json,
  105051. bin: bin
  105052. };
  105053. };
  105054. GLTFFileLoader._parseVersion = function (version) {
  105055. if (version === "1.0" || version === "1.0.1") {
  105056. return {
  105057. major: 1,
  105058. minor: 0
  105059. };
  105060. }
  105061. var match = (version + "").match(/^(\d+)\.(\d+)/);
  105062. if (!match) {
  105063. return null;
  105064. }
  105065. return {
  105066. major: parseInt(match[1]),
  105067. minor: parseInt(match[2])
  105068. };
  105069. };
  105070. GLTFFileLoader._compareVersion = function (a, b) {
  105071. if (a.major > b.major)
  105072. return 1;
  105073. if (a.major < b.major)
  105074. return -1;
  105075. if (a.minor > b.minor)
  105076. return 1;
  105077. if (a.minor < b.minor)
  105078. return -1;
  105079. return 0;
  105080. };
  105081. GLTFFileLoader._decodeBufferToText = function (buffer) {
  105082. var result = "";
  105083. var length = buffer.byteLength;
  105084. for (var i = 0; i < length; i++) {
  105085. result += String.fromCharCode(buffer[i]);
  105086. }
  105087. return result;
  105088. };
  105089. /** @hidden */
  105090. GLTFFileLoader.prototype._logOpen = function (message) {
  105091. this._log(message);
  105092. this._logIndentLevel++;
  105093. };
  105094. /** @hidden */
  105095. GLTFFileLoader.prototype._logClose = function () {
  105096. --this._logIndentLevel;
  105097. };
  105098. GLTFFileLoader.prototype._logEnabled = function (message) {
  105099. var spaces = GLTFFileLoader._logSpaces.substr(0, this._logIndentLevel * 2);
  105100. BABYLON.Tools.Log("" + spaces + message);
  105101. };
  105102. GLTFFileLoader.prototype._logDisabled = function (message) {
  105103. };
  105104. GLTFFileLoader.prototype._startPerformanceCounterEnabled = function (counterName) {
  105105. BABYLON.Tools.StartPerformanceCounter(counterName);
  105106. };
  105107. GLTFFileLoader.prototype._startPerformanceCounterDisabled = function (counterName) {
  105108. };
  105109. GLTFFileLoader.prototype._endPerformanceCounterEnabled = function (counterName) {
  105110. BABYLON.Tools.EndPerformanceCounter(counterName);
  105111. };
  105112. GLTFFileLoader.prototype._endPerformanceCounterDisabled = function (counterName) {
  105113. };
  105114. // #endregion
  105115. // #region V1 options
  105116. /**
  105117. * 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.
  105118. * Textures always loads asynchronously. For example, the success callback can compute the bounding information of the loaded meshes when incremental loading is disabled.
  105119. * Defaults to true.
  105120. * @hidden
  105121. */
  105122. GLTFFileLoader.IncrementalLoading = true;
  105123. /**
  105124. * Set this property to true in order to work with homogeneous coordinates, available with some converters and exporters.
  105125. * Defaults to false. See https://en.wikipedia.org/wiki/Homogeneous_coordinates.
  105126. * @hidden
  105127. */
  105128. GLTFFileLoader.HomogeneousCoordinates = false;
  105129. GLTFFileLoader._logSpaces = " ";
  105130. return GLTFFileLoader;
  105131. }());
  105132. BABYLON.GLTFFileLoader = GLTFFileLoader;
  105133. var BinaryReader = /** @class */ (function () {
  105134. function BinaryReader(arrayBuffer) {
  105135. this._arrayBuffer = arrayBuffer;
  105136. this._dataView = new DataView(arrayBuffer);
  105137. this._byteOffset = 0;
  105138. }
  105139. BinaryReader.prototype.getPosition = function () {
  105140. return this._byteOffset;
  105141. };
  105142. BinaryReader.prototype.getLength = function () {
  105143. return this._arrayBuffer.byteLength;
  105144. };
  105145. BinaryReader.prototype.readUint32 = function () {
  105146. var value = this._dataView.getUint32(this._byteOffset, true);
  105147. this._byteOffset += 4;
  105148. return value;
  105149. };
  105150. BinaryReader.prototype.readUint8Array = function (length) {
  105151. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  105152. this._byteOffset += length;
  105153. return value;
  105154. };
  105155. BinaryReader.prototype.skipBytes = function (length) {
  105156. this._byteOffset += length;
  105157. };
  105158. return BinaryReader;
  105159. }());
  105160. if (BABYLON.SceneLoader) {
  105161. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  105162. }
  105163. })(BABYLON || (BABYLON = {}));
  105164. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  105165. var BABYLON;
  105166. (function (BABYLON) {
  105167. var GLTF1;
  105168. (function (GLTF1) {
  105169. /**
  105170. * Enums
  105171. */
  105172. var EComponentType;
  105173. (function (EComponentType) {
  105174. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  105175. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  105176. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  105177. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  105178. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  105179. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  105180. var EShaderType;
  105181. (function (EShaderType) {
  105182. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  105183. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  105184. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  105185. var EParameterType;
  105186. (function (EParameterType) {
  105187. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  105188. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  105189. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  105190. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  105191. EParameterType[EParameterType["INT"] = 5124] = "INT";
  105192. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  105193. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  105194. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  105195. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  105196. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  105197. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  105198. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  105199. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  105200. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  105201. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  105202. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  105203. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  105204. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  105205. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  105206. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  105207. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  105208. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  105209. var ETextureWrapMode;
  105210. (function (ETextureWrapMode) {
  105211. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  105212. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  105213. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  105214. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  105215. var ETextureFilterType;
  105216. (function (ETextureFilterType) {
  105217. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  105218. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  105219. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  105220. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  105221. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  105222. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  105223. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  105224. var ETextureFormat;
  105225. (function (ETextureFormat) {
  105226. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  105227. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  105228. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  105229. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  105230. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  105231. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  105232. var ECullingType;
  105233. (function (ECullingType) {
  105234. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  105235. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  105236. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  105237. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  105238. var EBlendingFunction;
  105239. (function (EBlendingFunction) {
  105240. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  105241. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  105242. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  105243. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  105244. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  105245. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  105246. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  105247. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  105248. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  105249. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  105250. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  105251. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  105252. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  105253. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  105254. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  105255. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  105256. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  105257. })(BABYLON || (BABYLON = {}));
  105258. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  105259. var BABYLON;
  105260. (function (BABYLON) {
  105261. var GLTF1;
  105262. (function (GLTF1) {
  105263. /**
  105264. * Tokenizer. Used for shaders compatibility
  105265. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  105266. */
  105267. var ETokenType;
  105268. (function (ETokenType) {
  105269. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  105270. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  105271. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  105272. })(ETokenType || (ETokenType = {}));
  105273. var Tokenizer = /** @class */ (function () {
  105274. function Tokenizer(toParse) {
  105275. this._pos = 0;
  105276. this.currentToken = ETokenType.UNKNOWN;
  105277. this.currentIdentifier = "";
  105278. this.currentString = "";
  105279. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  105280. this._toParse = toParse;
  105281. this._maxPos = toParse.length;
  105282. }
  105283. Tokenizer.prototype.getNextToken = function () {
  105284. if (this.isEnd())
  105285. return ETokenType.END_OF_INPUT;
  105286. this.currentString = this.read();
  105287. this.currentToken = ETokenType.UNKNOWN;
  105288. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  105289. this.currentToken = ETokenType.IDENTIFIER;
  105290. this.currentIdentifier = this.currentString;
  105291. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  105292. this.currentIdentifier += this.currentString;
  105293. this.forward();
  105294. }
  105295. }
  105296. return this.currentToken;
  105297. };
  105298. Tokenizer.prototype.peek = function () {
  105299. return this._toParse[this._pos];
  105300. };
  105301. Tokenizer.prototype.read = function () {
  105302. return this._toParse[this._pos++];
  105303. };
  105304. Tokenizer.prototype.forward = function () {
  105305. this._pos++;
  105306. };
  105307. Tokenizer.prototype.isEnd = function () {
  105308. return this._pos >= this._maxPos;
  105309. };
  105310. return Tokenizer;
  105311. }());
  105312. /**
  105313. * Values
  105314. */
  105315. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  105316. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  105317. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  105318. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  105319. /**
  105320. * Parse
  105321. */
  105322. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  105323. for (var buf in parsedBuffers) {
  105324. var parsedBuffer = parsedBuffers[buf];
  105325. gltfRuntime.buffers[buf] = parsedBuffer;
  105326. gltfRuntime.buffersCount++;
  105327. }
  105328. };
  105329. var parseShaders = function (parsedShaders, gltfRuntime) {
  105330. for (var sha in parsedShaders) {
  105331. var parsedShader = parsedShaders[sha];
  105332. gltfRuntime.shaders[sha] = parsedShader;
  105333. gltfRuntime.shaderscount++;
  105334. }
  105335. };
  105336. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  105337. for (var object in parsedObjects) {
  105338. var parsedObject = parsedObjects[object];
  105339. gltfRuntime[runtimeProperty][object] = parsedObject;
  105340. }
  105341. };
  105342. /**
  105343. * Utils
  105344. */
  105345. var normalizeUVs = function (buffer) {
  105346. if (!buffer) {
  105347. return;
  105348. }
  105349. for (var i = 0; i < buffer.length / 2; i++) {
  105350. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  105351. }
  105352. };
  105353. var getAttribute = function (attributeParameter) {
  105354. if (attributeParameter.semantic === "NORMAL") {
  105355. return "normal";
  105356. }
  105357. else if (attributeParameter.semantic === "POSITION") {
  105358. return "position";
  105359. }
  105360. else if (attributeParameter.semantic === "JOINT") {
  105361. return "matricesIndices";
  105362. }
  105363. else if (attributeParameter.semantic === "WEIGHT") {
  105364. return "matricesWeights";
  105365. }
  105366. else if (attributeParameter.semantic === "COLOR") {
  105367. return "color";
  105368. }
  105369. else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  105370. var channel = Number(attributeParameter.semantic.split("_")[1]);
  105371. return "uv" + (channel === 0 ? "" : channel + 1);
  105372. }
  105373. return null;
  105374. };
  105375. /**
  105376. * Loads and creates animations
  105377. */
  105378. var loadAnimations = function (gltfRuntime) {
  105379. for (var anim in gltfRuntime.animations) {
  105380. var animation = gltfRuntime.animations[anim];
  105381. if (!animation.channels || !animation.samplers) {
  105382. continue;
  105383. }
  105384. var lastAnimation = null;
  105385. for (var i = 0; i < animation.channels.length; i++) {
  105386. // Get parameters and load buffers
  105387. var channel = animation.channels[i];
  105388. var sampler = animation.samplers[channel.sampler];
  105389. if (!sampler) {
  105390. continue;
  105391. }
  105392. var inputData = null;
  105393. var outputData = null;
  105394. if (animation.parameters) {
  105395. inputData = animation.parameters[sampler.input];
  105396. outputData = animation.parameters[sampler.output];
  105397. }
  105398. else {
  105399. inputData = sampler.input;
  105400. outputData = sampler.output;
  105401. }
  105402. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  105403. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  105404. var targetID = channel.target.id;
  105405. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  105406. if (targetNode === null) {
  105407. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  105408. }
  105409. if (targetNode === null) {
  105410. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  105411. continue;
  105412. }
  105413. var isBone = targetNode instanceof BABYLON.Bone;
  105414. // Get target path (position, rotation or scaling)
  105415. var targetPath = channel.target.path;
  105416. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  105417. if (targetPathIndex !== -1) {
  105418. targetPath = babylonAnimationPaths[targetPathIndex];
  105419. }
  105420. // Determine animation type
  105421. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  105422. if (!isBone) {
  105423. if (targetPath === "rotationQuaternion") {
  105424. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  105425. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  105426. }
  105427. else {
  105428. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  105429. }
  105430. }
  105431. // Create animation and key frames
  105432. var babylonAnimation = null;
  105433. var keys = [];
  105434. var arrayOffset = 0;
  105435. var modifyKey = false;
  105436. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  105437. babylonAnimation = lastAnimation;
  105438. modifyKey = true;
  105439. }
  105440. if (!modifyKey) {
  105441. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  105442. }
  105443. // For each frame
  105444. for (var j = 0; j < bufferInput.length; j++) {
  105445. var value = null;
  105446. if (targetPath === "rotationQuaternion") { // VEC4
  105447. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  105448. arrayOffset += 4;
  105449. }
  105450. else { // Position and scaling are VEC3
  105451. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  105452. arrayOffset += 3;
  105453. }
  105454. if (isBone) {
  105455. var bone = targetNode;
  105456. var translation = BABYLON.Vector3.Zero();
  105457. var rotationQuaternion = new BABYLON.Quaternion();
  105458. var scaling = BABYLON.Vector3.Zero();
  105459. // Warning on decompose
  105460. var mat = bone.getBaseMatrix();
  105461. if (modifyKey && lastAnimation) {
  105462. mat = lastAnimation.getKeys()[j].value;
  105463. }
  105464. mat.decompose(scaling, rotationQuaternion, translation);
  105465. if (targetPath === "position") {
  105466. translation = value;
  105467. }
  105468. else if (targetPath === "rotationQuaternion") {
  105469. rotationQuaternion = value;
  105470. }
  105471. else {
  105472. scaling = value;
  105473. }
  105474. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  105475. }
  105476. if (!modifyKey) {
  105477. keys.push({
  105478. frame: bufferInput[j],
  105479. value: value
  105480. });
  105481. }
  105482. else if (lastAnimation) {
  105483. lastAnimation.getKeys()[j].value = value;
  105484. }
  105485. }
  105486. // Finish
  105487. if (!modifyKey && babylonAnimation) {
  105488. babylonAnimation.setKeys(keys);
  105489. targetNode.animations.push(babylonAnimation);
  105490. }
  105491. lastAnimation = babylonAnimation;
  105492. gltfRuntime.scene.stopAnimation(targetNode);
  105493. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  105494. }
  105495. }
  105496. };
  105497. /**
  105498. * Returns the bones transformation matrix
  105499. */
  105500. var configureBoneTransformation = function (node) {
  105501. var mat = null;
  105502. if (node.translation || node.rotation || node.scale) {
  105503. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  105504. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  105505. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  105506. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  105507. }
  105508. else {
  105509. mat = BABYLON.Matrix.FromArray(node.matrix);
  105510. }
  105511. return mat;
  105512. };
  105513. /**
  105514. * Returns the parent bone
  105515. */
  105516. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  105517. // Try to find
  105518. for (var i = 0; i < newSkeleton.bones.length; i++) {
  105519. if (newSkeleton.bones[i].name === jointName) {
  105520. return newSkeleton.bones[i];
  105521. }
  105522. }
  105523. // Not found, search in gltf nodes
  105524. var nodes = gltfRuntime.nodes;
  105525. for (var nde in nodes) {
  105526. var node = nodes[nde];
  105527. if (!node.jointName) {
  105528. continue;
  105529. }
  105530. var children = node.children;
  105531. for (var i = 0; i < children.length; i++) {
  105532. var child = gltfRuntime.nodes[children[i]];
  105533. if (!child.jointName) {
  105534. continue;
  105535. }
  105536. if (child.jointName === jointName) {
  105537. var mat = configureBoneTransformation(node);
  105538. var bone = new BABYLON.Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  105539. bone.id = nde;
  105540. return bone;
  105541. }
  105542. }
  105543. }
  105544. return null;
  105545. };
  105546. /**
  105547. * Returns the appropriate root node
  105548. */
  105549. var getNodeToRoot = function (nodesToRoot, id) {
  105550. for (var i = 0; i < nodesToRoot.length; i++) {
  105551. var nodeToRoot = nodesToRoot[i];
  105552. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  105553. var child = nodeToRoot.node.children[j];
  105554. if (child === id) {
  105555. return nodeToRoot.bone;
  105556. }
  105557. }
  105558. }
  105559. return null;
  105560. };
  105561. /**
  105562. * Returns the node with the joint name
  105563. */
  105564. var getJointNode = function (gltfRuntime, jointName) {
  105565. var nodes = gltfRuntime.nodes;
  105566. var node = nodes[jointName];
  105567. if (node) {
  105568. return {
  105569. node: node,
  105570. id: jointName
  105571. };
  105572. }
  105573. for (var nde in nodes) {
  105574. node = nodes[nde];
  105575. if (node.jointName === jointName) {
  105576. return {
  105577. node: node,
  105578. id: nde
  105579. };
  105580. }
  105581. }
  105582. return null;
  105583. };
  105584. /**
  105585. * Checks if a nodes is in joints
  105586. */
  105587. var nodeIsInJoints = function (skins, id) {
  105588. for (var i = 0; i < skins.jointNames.length; i++) {
  105589. if (skins.jointNames[i] === id) {
  105590. return true;
  105591. }
  105592. }
  105593. return false;
  105594. };
  105595. /**
  105596. * Fills the nodes to root for bones and builds hierarchy
  105597. */
  105598. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  105599. // Creates nodes for root
  105600. for (var nde in gltfRuntime.nodes) {
  105601. var node = gltfRuntime.nodes[nde];
  105602. var id = nde;
  105603. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  105604. continue;
  105605. }
  105606. // Create node to root bone
  105607. var mat = configureBoneTransformation(node);
  105608. var bone = new BABYLON.Bone(node.name || "", newSkeleton, null, mat);
  105609. bone.id = id;
  105610. nodesToRoot.push({ bone: bone, node: node, id: id });
  105611. }
  105612. // Parenting
  105613. for (var i = 0; i < nodesToRoot.length; i++) {
  105614. var nodeToRoot = nodesToRoot[i];
  105615. var children = nodeToRoot.node.children;
  105616. for (var j = 0; j < children.length; j++) {
  105617. var child = null;
  105618. for (var k = 0; k < nodesToRoot.length; k++) {
  105619. if (nodesToRoot[k].id === children[j]) {
  105620. child = nodesToRoot[k];
  105621. break;
  105622. }
  105623. }
  105624. if (child) {
  105625. child.bone._parent = nodeToRoot.bone;
  105626. nodeToRoot.bone.children.push(child.bone);
  105627. }
  105628. }
  105629. }
  105630. };
  105631. /**
  105632. * Imports a skeleton
  105633. */
  105634. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  105635. if (!newSkeleton) {
  105636. newSkeleton = new BABYLON.Skeleton(skins.name || "", "", gltfRuntime.scene);
  105637. }
  105638. if (!skins.babylonSkeleton) {
  105639. return newSkeleton;
  105640. }
  105641. // Find the root bones
  105642. var nodesToRoot = [];
  105643. var nodesToRootToAdd = [];
  105644. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  105645. newSkeleton.bones = [];
  105646. // Joints
  105647. for (var i = 0; i < skins.jointNames.length; i++) {
  105648. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  105649. if (!jointNode) {
  105650. continue;
  105651. }
  105652. var node = jointNode.node;
  105653. if (!node) {
  105654. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  105655. continue;
  105656. }
  105657. var id = jointNode.id;
  105658. // Optimize, if the bone already exists...
  105659. var existingBone = gltfRuntime.scene.getBoneByID(id);
  105660. if (existingBone) {
  105661. newSkeleton.bones.push(existingBone);
  105662. continue;
  105663. }
  105664. // Search for parent bone
  105665. var foundBone = false;
  105666. var parentBone = null;
  105667. for (var j = 0; j < i; j++) {
  105668. var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
  105669. if (!jointNode_1) {
  105670. continue;
  105671. }
  105672. var joint = jointNode_1.node;
  105673. if (!joint) {
  105674. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  105675. continue;
  105676. }
  105677. var children = joint.children;
  105678. if (!children) {
  105679. continue;
  105680. }
  105681. foundBone = false;
  105682. for (var k = 0; k < children.length; k++) {
  105683. if (children[k] === id) {
  105684. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  105685. foundBone = true;
  105686. break;
  105687. }
  105688. }
  105689. if (foundBone) {
  105690. break;
  105691. }
  105692. }
  105693. // Create bone
  105694. var mat = configureBoneTransformation(node);
  105695. if (!parentBone && nodesToRoot.length > 0) {
  105696. parentBone = getNodeToRoot(nodesToRoot, id);
  105697. if (parentBone) {
  105698. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  105699. nodesToRootToAdd.push(parentBone);
  105700. }
  105701. }
  105702. }
  105703. var bone = new BABYLON.Bone(node.jointName || "", newSkeleton, parentBone, mat);
  105704. bone.id = id;
  105705. }
  105706. // Polish
  105707. var bones = newSkeleton.bones;
  105708. newSkeleton.bones = [];
  105709. for (var i = 0; i < skins.jointNames.length; i++) {
  105710. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  105711. if (!jointNode) {
  105712. continue;
  105713. }
  105714. for (var j = 0; j < bones.length; j++) {
  105715. if (bones[j].id === jointNode.id) {
  105716. newSkeleton.bones.push(bones[j]);
  105717. break;
  105718. }
  105719. }
  105720. }
  105721. newSkeleton.prepare();
  105722. // Finish
  105723. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  105724. newSkeleton.bones.push(nodesToRootToAdd[i]);
  105725. }
  105726. return newSkeleton;
  105727. };
  105728. /**
  105729. * Imports a mesh and its geometries
  105730. */
  105731. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  105732. if (!newMesh) {
  105733. newMesh = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  105734. newMesh.id = id;
  105735. }
  105736. if (!node.babylonNode) {
  105737. return newMesh;
  105738. }
  105739. var subMaterials = [];
  105740. var vertexData = null;
  105741. var verticesStarts = new Array();
  105742. var verticesCounts = new Array();
  105743. var indexStarts = new Array();
  105744. var indexCounts = new Array();
  105745. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  105746. var meshID = meshes[meshIndex];
  105747. var mesh = gltfRuntime.meshes[meshID];
  105748. if (!mesh) {
  105749. continue;
  105750. }
  105751. // Positions, normals and UVs
  105752. for (var i = 0; i < mesh.primitives.length; i++) {
  105753. // Temporary vertex data
  105754. var tempVertexData = new BABYLON.VertexData();
  105755. var primitive = mesh.primitives[i];
  105756. if (primitive.mode !== 4) {
  105757. // continue;
  105758. }
  105759. var attributes = primitive.attributes;
  105760. var accessor = null;
  105761. var buffer = null;
  105762. // Set positions, normal and uvs
  105763. for (var semantic in attributes) {
  105764. // Link accessor and buffer view
  105765. accessor = gltfRuntime.accessors[attributes[semantic]];
  105766. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  105767. if (semantic === "NORMAL") {
  105768. tempVertexData.normals = new Float32Array(buffer.length);
  105769. tempVertexData.normals.set(buffer);
  105770. }
  105771. else if (semantic === "POSITION") {
  105772. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  105773. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  105774. for (var j = 0; j < buffer.length; j += 4) {
  105775. tempVertexData.positions[j] = buffer[j];
  105776. tempVertexData.positions[j + 1] = buffer[j + 1];
  105777. tempVertexData.positions[j + 2] = buffer[j + 2];
  105778. }
  105779. }
  105780. else {
  105781. tempVertexData.positions = new Float32Array(buffer.length);
  105782. tempVertexData.positions.set(buffer);
  105783. }
  105784. verticesCounts.push(tempVertexData.positions.length);
  105785. }
  105786. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  105787. var channel = Number(semantic.split("_")[1]);
  105788. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  105789. var uvs = new Float32Array(buffer.length);
  105790. uvs.set(buffer);
  105791. normalizeUVs(uvs);
  105792. tempVertexData.set(uvs, uvKind);
  105793. }
  105794. else if (semantic === "JOINT") {
  105795. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  105796. tempVertexData.matricesIndices.set(buffer);
  105797. }
  105798. else if (semantic === "WEIGHT") {
  105799. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  105800. tempVertexData.matricesWeights.set(buffer);
  105801. }
  105802. else if (semantic === "COLOR") {
  105803. tempVertexData.colors = new Float32Array(buffer.length);
  105804. tempVertexData.colors.set(buffer);
  105805. }
  105806. }
  105807. // Indices
  105808. accessor = gltfRuntime.accessors[primitive.indices];
  105809. if (accessor) {
  105810. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  105811. tempVertexData.indices = new Int32Array(buffer.length);
  105812. tempVertexData.indices.set(buffer);
  105813. indexCounts.push(tempVertexData.indices.length);
  105814. }
  105815. else {
  105816. // Set indices on the fly
  105817. var indices = [];
  105818. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  105819. indices.push(j);
  105820. }
  105821. tempVertexData.indices = new Int32Array(indices);
  105822. indexCounts.push(tempVertexData.indices.length);
  105823. }
  105824. if (!vertexData) {
  105825. vertexData = tempVertexData;
  105826. }
  105827. else {
  105828. vertexData.merge(tempVertexData);
  105829. }
  105830. // Sub material
  105831. var material_1 = gltfRuntime.scene.getMaterialByID(primitive.material);
  105832. subMaterials.push(material_1 === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material_1);
  105833. // Update vertices start and index start
  105834. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  105835. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  105836. }
  105837. }
  105838. var material;
  105839. if (subMaterials.length > 1) {
  105840. material = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  105841. material.subMaterials = subMaterials;
  105842. }
  105843. else {
  105844. material = new BABYLON.StandardMaterial("multimat" + id, gltfRuntime.scene);
  105845. }
  105846. if (subMaterials.length === 1) {
  105847. material = subMaterials[0];
  105848. }
  105849. if (!newMesh.material) {
  105850. newMesh.material = material;
  105851. }
  105852. // Apply geometry
  105853. new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  105854. newMesh.computeWorldMatrix(true);
  105855. // Apply submeshes
  105856. newMesh.subMeshes = [];
  105857. var index = 0;
  105858. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  105859. var meshID = meshes[meshIndex];
  105860. var mesh = gltfRuntime.meshes[meshID];
  105861. if (!mesh) {
  105862. continue;
  105863. }
  105864. for (var i = 0; i < mesh.primitives.length; i++) {
  105865. if (mesh.primitives[i].mode !== 4) {
  105866. //continue;
  105867. }
  105868. BABYLON.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  105869. index++;
  105870. }
  105871. }
  105872. // Finish
  105873. return newMesh;
  105874. };
  105875. /**
  105876. * Configure node transformation from position, rotation and scaling
  105877. */
  105878. var configureNode = function (newNode, position, rotation, scaling) {
  105879. if (newNode.position) {
  105880. newNode.position = position;
  105881. }
  105882. if (newNode.rotationQuaternion || newNode.rotation) {
  105883. newNode.rotationQuaternion = rotation;
  105884. }
  105885. if (newNode.scaling) {
  105886. newNode.scaling = scaling;
  105887. }
  105888. };
  105889. /**
  105890. * Configures node from transformation matrix
  105891. */
  105892. var configureNodeFromMatrix = function (newNode, node, parent) {
  105893. if (node.matrix) {
  105894. var position = new BABYLON.Vector3(0, 0, 0);
  105895. var rotation = new BABYLON.Quaternion();
  105896. var scaling = new BABYLON.Vector3(0, 0, 0);
  105897. var mat = BABYLON.Matrix.FromArray(node.matrix);
  105898. mat.decompose(scaling, rotation, position);
  105899. configureNode(newNode, position, rotation, scaling);
  105900. }
  105901. else if (node.translation && node.rotation && node.scale) {
  105902. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  105903. }
  105904. newNode.computeWorldMatrix(true);
  105905. };
  105906. /**
  105907. * Imports a node
  105908. */
  105909. var importNode = function (gltfRuntime, node, id, parent) {
  105910. var lastNode = null;
  105911. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  105912. if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
  105913. return null;
  105914. }
  105915. }
  105916. // Meshes
  105917. if (node.skin) {
  105918. if (node.meshes) {
  105919. var skin = gltfRuntime.skins[node.skin];
  105920. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  105921. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  105922. if (newMesh.skeleton === null) {
  105923. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  105924. if (!skin.babylonSkeleton) {
  105925. skin.babylonSkeleton = newMesh.skeleton;
  105926. }
  105927. }
  105928. lastNode = newMesh;
  105929. }
  105930. }
  105931. else if (node.meshes) {
  105932. /**
  105933. * Improve meshes property
  105934. */
  105935. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  105936. lastNode = newMesh;
  105937. }
  105938. // Lights
  105939. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  105940. var light = gltfRuntime.lights[node.light];
  105941. if (light) {
  105942. if (light.type === "ambient") {
  105943. var ambienLight = light[light.type];
  105944. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  105945. hemiLight.name = node.name || "";
  105946. if (ambienLight.color) {
  105947. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  105948. }
  105949. lastNode = hemiLight;
  105950. }
  105951. else if (light.type === "directional") {
  105952. var directionalLight = light[light.type];
  105953. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  105954. dirLight.name = node.name || "";
  105955. if (directionalLight.color) {
  105956. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  105957. }
  105958. lastNode = dirLight;
  105959. }
  105960. else if (light.type === "point") {
  105961. var pointLight = light[light.type];
  105962. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  105963. ptLight.name = node.name || "";
  105964. if (pointLight.color) {
  105965. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  105966. }
  105967. lastNode = ptLight;
  105968. }
  105969. else if (light.type === "spot") {
  105970. var spotLight = light[light.type];
  105971. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  105972. spLight.name = node.name || "";
  105973. if (spotLight.color) {
  105974. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  105975. }
  105976. if (spotLight.fallOfAngle) {
  105977. spLight.angle = spotLight.fallOfAngle;
  105978. }
  105979. if (spotLight.fallOffExponent) {
  105980. spLight.exponent = spotLight.fallOffExponent;
  105981. }
  105982. lastNode = spLight;
  105983. }
  105984. }
  105985. }
  105986. // Cameras
  105987. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  105988. var camera = gltfRuntime.cameras[node.camera];
  105989. if (camera) {
  105990. if (camera.type === "orthographic") {
  105991. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene, false);
  105992. orthoCamera.name = node.name || "";
  105993. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  105994. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  105995. lastNode = orthoCamera;
  105996. }
  105997. else if (camera.type === "perspective") {
  105998. var perspectiveCamera = camera[camera.type];
  105999. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene, false);
  106000. persCamera.name = node.name || "";
  106001. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  106002. if (!perspectiveCamera.aspectRatio) {
  106003. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  106004. }
  106005. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  106006. persCamera.maxZ = perspectiveCamera.zfar;
  106007. persCamera.minZ = perspectiveCamera.znear;
  106008. }
  106009. lastNode = persCamera;
  106010. }
  106011. }
  106012. }
  106013. // Empty node
  106014. if (!node.jointName) {
  106015. if (node.babylonNode) {
  106016. return node.babylonNode;
  106017. }
  106018. else if (lastNode === null) {
  106019. var dummy = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  106020. node.babylonNode = dummy;
  106021. lastNode = dummy;
  106022. }
  106023. }
  106024. if (lastNode !== null) {
  106025. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  106026. configureNodeFromMatrix(lastNode, node, parent);
  106027. }
  106028. else {
  106029. var translation = node.translation || [0, 0, 0];
  106030. var rotation = node.rotation || [0, 0, 0, 1];
  106031. var scale = node.scale || [1, 1, 1];
  106032. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  106033. }
  106034. lastNode.updateCache(true);
  106035. node.babylonNode = lastNode;
  106036. }
  106037. return lastNode;
  106038. };
  106039. /**
  106040. * Traverses nodes and creates them
  106041. */
  106042. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  106043. if (meshIncluded === void 0) { meshIncluded = false; }
  106044. var node = gltfRuntime.nodes[id];
  106045. var newNode = null;
  106046. if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
  106047. if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  106048. meshIncluded = true;
  106049. }
  106050. else {
  106051. meshIncluded = false;
  106052. }
  106053. }
  106054. else {
  106055. meshIncluded = true;
  106056. }
  106057. if (!node.jointName && meshIncluded) {
  106058. newNode = importNode(gltfRuntime, node, id, parent);
  106059. if (newNode !== null) {
  106060. newNode.id = id;
  106061. newNode.parent = parent;
  106062. }
  106063. }
  106064. if (node.children) {
  106065. for (var i = 0; i < node.children.length; i++) {
  106066. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  106067. }
  106068. }
  106069. };
  106070. /**
  106071. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  106072. */
  106073. var postLoad = function (gltfRuntime) {
  106074. // Nodes
  106075. var currentScene = gltfRuntime.currentScene;
  106076. if (currentScene) {
  106077. for (var i = 0; i < currentScene.nodes.length; i++) {
  106078. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  106079. }
  106080. }
  106081. else {
  106082. for (var thing in gltfRuntime.scenes) {
  106083. currentScene = gltfRuntime.scenes[thing];
  106084. for (var i = 0; i < currentScene.nodes.length; i++) {
  106085. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  106086. }
  106087. }
  106088. }
  106089. // Set animations
  106090. loadAnimations(gltfRuntime);
  106091. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  106092. var skeleton = gltfRuntime.scene.skeletons[i];
  106093. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  106094. }
  106095. };
  106096. /**
  106097. * onBind shaderrs callback to set uniforms and matrices
  106098. */
  106099. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  106100. var materialValues = material.values || technique.parameters;
  106101. for (var unif in unTreatedUniforms) {
  106102. var uniform = unTreatedUniforms[unif];
  106103. var type = uniform.type;
  106104. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  106105. if (uniform.semantic && !uniform.source && !uniform.node) {
  106106. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  106107. }
  106108. else if (uniform.semantic && (uniform.source || uniform.node)) {
  106109. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
  106110. if (source === null) {
  106111. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || "");
  106112. }
  106113. if (source === null) {
  106114. continue;
  106115. }
  106116. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  106117. }
  106118. }
  106119. else {
  106120. var value = materialValues[technique.uniforms[unif]];
  106121. if (!value) {
  106122. continue;
  106123. }
  106124. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  106125. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  106126. if (texture === null || texture === undefined) {
  106127. continue;
  106128. }
  106129. shaderMaterial.getEffect().setTexture(unif, texture);
  106130. }
  106131. else {
  106132. GLTF1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type);
  106133. }
  106134. }
  106135. }
  106136. onSuccess(shaderMaterial);
  106137. };
  106138. /**
  106139. * Prepare uniforms to send the only one time
  106140. * Loads the appropriate textures
  106141. */
  106142. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  106143. var materialValues = material.values || technique.parameters;
  106144. var techniqueUniforms = technique.uniforms;
  106145. /**
  106146. * Prepare values here (not matrices)
  106147. */
  106148. for (var unif in unTreatedUniforms) {
  106149. var uniform = unTreatedUniforms[unif];
  106150. var type = uniform.type;
  106151. var value = materialValues[techniqueUniforms[unif]];
  106152. if (value === undefined) {
  106153. // In case the value is the same for all materials
  106154. value = uniform.value;
  106155. }
  106156. if (!value) {
  106157. continue;
  106158. }
  106159. var onLoadTexture = function (uniformName) {
  106160. return function (texture) {
  106161. if (uniform.value && uniformName) {
  106162. // Static uniform
  106163. shaderMaterial.setTexture(uniformName, texture);
  106164. delete unTreatedUniforms[uniformName];
  106165. }
  106166. };
  106167. };
  106168. // Texture (sampler2D)
  106169. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  106170. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  106171. }
  106172. // Others
  106173. else {
  106174. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  106175. // Static uniform
  106176. delete unTreatedUniforms[unif];
  106177. }
  106178. }
  106179. }
  106180. };
  106181. /**
  106182. * Shader compilation failed
  106183. */
  106184. var onShaderCompileError = function (program, shaderMaterial, onError) {
  106185. return function (effect, error) {
  106186. shaderMaterial.dispose(true);
  106187. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  106188. };
  106189. };
  106190. /**
  106191. * Shader compilation success
  106192. */
  106193. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  106194. return function (_) {
  106195. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  106196. shaderMaterial.onBind = function (mesh) {
  106197. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  106198. };
  106199. };
  106200. };
  106201. /**
  106202. * Returns the appropriate uniform if already handled by babylon
  106203. */
  106204. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  106205. for (var unif in technique.uniforms) {
  106206. var uniform = technique.uniforms[unif];
  106207. var uniformParameter = technique.parameters[uniform];
  106208. if (tokenizer.currentIdentifier === unif) {
  106209. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  106210. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  106211. if (transformIndex !== -1) {
  106212. delete unTreatedUniforms[unif];
  106213. return babylonTransforms[transformIndex];
  106214. }
  106215. }
  106216. }
  106217. }
  106218. return tokenizer.currentIdentifier;
  106219. };
  106220. /**
  106221. * All shaders loaded. Create materials one by one
  106222. */
  106223. var importMaterials = function (gltfRuntime) {
  106224. // Create materials
  106225. for (var mat in gltfRuntime.materials) {
  106226. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  106227. }
  106228. };
  106229. /**
  106230. * Implementation of the base glTF spec
  106231. */
  106232. var GLTFLoaderBase = /** @class */ (function () {
  106233. function GLTFLoaderBase() {
  106234. }
  106235. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  106236. var gltfRuntime = {
  106237. extensions: {},
  106238. accessors: {},
  106239. buffers: {},
  106240. bufferViews: {},
  106241. meshes: {},
  106242. lights: {},
  106243. cameras: {},
  106244. nodes: {},
  106245. images: {},
  106246. textures: {},
  106247. shaders: {},
  106248. programs: {},
  106249. samplers: {},
  106250. techniques: {},
  106251. materials: {},
  106252. animations: {},
  106253. skins: {},
  106254. extensionsUsed: [],
  106255. scenes: {},
  106256. buffersCount: 0,
  106257. shaderscount: 0,
  106258. scene: scene,
  106259. rootUrl: rootUrl,
  106260. loadedBufferCount: 0,
  106261. loadedBufferViews: {},
  106262. loadedShaderCount: 0,
  106263. importOnlyMeshes: false,
  106264. dummyNodes: []
  106265. };
  106266. // Parse
  106267. if (parsedData.extensions) {
  106268. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  106269. }
  106270. if (parsedData.extensionsUsed) {
  106271. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  106272. }
  106273. if (parsedData.buffers) {
  106274. parseBuffers(parsedData.buffers, gltfRuntime);
  106275. }
  106276. if (parsedData.bufferViews) {
  106277. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  106278. }
  106279. if (parsedData.accessors) {
  106280. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  106281. }
  106282. if (parsedData.meshes) {
  106283. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  106284. }
  106285. if (parsedData.lights) {
  106286. parseObject(parsedData.lights, "lights", gltfRuntime);
  106287. }
  106288. if (parsedData.cameras) {
  106289. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  106290. }
  106291. if (parsedData.nodes) {
  106292. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  106293. }
  106294. if (parsedData.images) {
  106295. parseObject(parsedData.images, "images", gltfRuntime);
  106296. }
  106297. if (parsedData.textures) {
  106298. parseObject(parsedData.textures, "textures", gltfRuntime);
  106299. }
  106300. if (parsedData.shaders) {
  106301. parseShaders(parsedData.shaders, gltfRuntime);
  106302. }
  106303. if (parsedData.programs) {
  106304. parseObject(parsedData.programs, "programs", gltfRuntime);
  106305. }
  106306. if (parsedData.samplers) {
  106307. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  106308. }
  106309. if (parsedData.techniques) {
  106310. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  106311. }
  106312. if (parsedData.materials) {
  106313. parseObject(parsedData.materials, "materials", gltfRuntime);
  106314. }
  106315. if (parsedData.animations) {
  106316. parseObject(parsedData.animations, "animations", gltfRuntime);
  106317. }
  106318. if (parsedData.skins) {
  106319. parseObject(parsedData.skins, "skins", gltfRuntime);
  106320. }
  106321. if (parsedData.scenes) {
  106322. gltfRuntime.scenes = parsedData.scenes;
  106323. }
  106324. if (parsedData.scene && parsedData.scenes) {
  106325. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  106326. }
  106327. return gltfRuntime;
  106328. };
  106329. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  106330. var buffer = gltfRuntime.buffers[id];
  106331. if (BABYLON.Tools.IsBase64(buffer.uri)) {
  106332. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(buffer.uri))); });
  106333. }
  106334. else {
  106335. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
  106336. if (request) {
  106337. onError(request.status + " " + request.statusText);
  106338. }
  106339. });
  106340. }
  106341. };
  106342. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  106343. var texture = gltfRuntime.textures[id];
  106344. if (!texture || !texture.source) {
  106345. onError("");
  106346. return;
  106347. }
  106348. if (texture.babylonTexture) {
  106349. onSuccess(null);
  106350. return;
  106351. }
  106352. var source = gltfRuntime.images[texture.source];
  106353. if (BABYLON.Tools.IsBase64(source.uri)) {
  106354. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(source.uri))); });
  106355. }
  106356. else {
  106357. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
  106358. if (request) {
  106359. onError(request.status + " " + request.statusText);
  106360. }
  106361. });
  106362. }
  106363. };
  106364. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  106365. var texture = gltfRuntime.textures[id];
  106366. if (texture.babylonTexture) {
  106367. onSuccess(texture.babylonTexture);
  106368. return;
  106369. }
  106370. var sampler = gltfRuntime.samplers[texture.sampler];
  106371. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  106372. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  106373. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  106374. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  106375. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  106376. var blob = new Blob([buffer]);
  106377. var blobURL = URL.createObjectURL(blob);
  106378. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  106379. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  106380. if (sampler.wrapS !== undefined) {
  106381. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  106382. }
  106383. if (sampler.wrapT !== undefined) {
  106384. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  106385. }
  106386. newTexture.name = id;
  106387. texture.babylonTexture = newTexture;
  106388. onSuccess(newTexture);
  106389. };
  106390. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  106391. var shader = gltfRuntime.shaders[id];
  106392. if (BABYLON.Tools.IsBase64(shader.uri)) {
  106393. var shaderString = atob(shader.uri.split(",")[1]);
  106394. if (onSuccess) {
  106395. onSuccess(shaderString);
  106396. }
  106397. }
  106398. else {
  106399. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
  106400. if (request && onError) {
  106401. onError(request.status + " " + request.statusText);
  106402. }
  106403. });
  106404. }
  106405. };
  106406. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  106407. var material = gltfRuntime.materials[id];
  106408. if (!material.technique) {
  106409. if (onError) {
  106410. onError("No technique found.");
  106411. }
  106412. return;
  106413. }
  106414. var technique = gltfRuntime.techniques[material.technique];
  106415. if (!technique) {
  106416. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  106417. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  106418. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  106419. onSuccess(defaultMaterial);
  106420. return;
  106421. }
  106422. var program = gltfRuntime.programs[technique.program];
  106423. var states = technique.states;
  106424. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  106425. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  106426. var newVertexShader = "";
  106427. var newPixelShader = "";
  106428. var vertexTokenizer = new Tokenizer(vertexShader);
  106429. var pixelTokenizer = new Tokenizer(pixelShader);
  106430. var unTreatedUniforms = {};
  106431. var uniforms = [];
  106432. var attributes = [];
  106433. var samplers = [];
  106434. // Fill uniform, sampler2D and attributes
  106435. for (var unif in technique.uniforms) {
  106436. var uniform = technique.uniforms[unif];
  106437. var uniformParameter = technique.parameters[uniform];
  106438. unTreatedUniforms[unif] = uniformParameter;
  106439. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  106440. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  106441. if (transformIndex !== -1) {
  106442. uniforms.push(babylonTransforms[transformIndex]);
  106443. delete unTreatedUniforms[unif];
  106444. }
  106445. else {
  106446. uniforms.push(unif);
  106447. }
  106448. }
  106449. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  106450. samplers.push(unif);
  106451. }
  106452. else {
  106453. uniforms.push(unif);
  106454. }
  106455. }
  106456. for (var attr in technique.attributes) {
  106457. var attribute = technique.attributes[attr];
  106458. var attributeParameter = technique.parameters[attribute];
  106459. if (attributeParameter.semantic) {
  106460. attributes.push(getAttribute(attributeParameter));
  106461. }
  106462. }
  106463. // Configure vertex shader
  106464. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  106465. var tokenType = vertexTokenizer.currentToken;
  106466. if (tokenType !== ETokenType.IDENTIFIER) {
  106467. newVertexShader += vertexTokenizer.currentString;
  106468. continue;
  106469. }
  106470. var foundAttribute = false;
  106471. for (var attr in technique.attributes) {
  106472. var attribute = technique.attributes[attr];
  106473. var attributeParameter = technique.parameters[attribute];
  106474. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  106475. newVertexShader += getAttribute(attributeParameter);
  106476. foundAttribute = true;
  106477. break;
  106478. }
  106479. }
  106480. if (foundAttribute) {
  106481. continue;
  106482. }
  106483. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  106484. }
  106485. // Configure pixel shader
  106486. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  106487. var tokenType = pixelTokenizer.currentToken;
  106488. if (tokenType !== ETokenType.IDENTIFIER) {
  106489. newPixelShader += pixelTokenizer.currentString;
  106490. continue;
  106491. }
  106492. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  106493. }
  106494. // Create shader material
  106495. var shaderPath = {
  106496. vertex: program.vertexShader + id,
  106497. fragment: program.fragmentShader + id
  106498. };
  106499. var options = {
  106500. attributes: attributes,
  106501. uniforms: uniforms,
  106502. samplers: samplers,
  106503. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  106504. };
  106505. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  106506. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  106507. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  106508. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  106509. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  106510. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  106511. if (states && states.functions) {
  106512. var functions = states.functions;
  106513. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  106514. shaderMaterial.backFaceCulling = false;
  106515. }
  106516. var blendFunc = functions.blendFuncSeparate;
  106517. if (blendFunc) {
  106518. 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) {
  106519. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  106520. }
  106521. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  106522. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  106523. }
  106524. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  106525. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  106526. }
  106527. 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) {
  106528. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  106529. }
  106530. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  106531. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  106532. }
  106533. 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) {
  106534. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  106535. }
  106536. }
  106537. }
  106538. };
  106539. return GLTFLoaderBase;
  106540. }());
  106541. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  106542. /**
  106543. * glTF V1 Loader
  106544. */
  106545. var GLTFLoader = /** @class */ (function () {
  106546. function GLTFLoader() {
  106547. this.state = null;
  106548. }
  106549. GLTFLoader.RegisterExtension = function (extension) {
  106550. if (GLTFLoader.Extensions[extension.name]) {
  106551. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  106552. return;
  106553. }
  106554. GLTFLoader.Extensions[extension.name] = extension;
  106555. };
  106556. GLTFLoader.prototype.dispose = function () {
  106557. // do nothing
  106558. };
  106559. GLTFLoader.prototype._importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  106560. var _this = this;
  106561. scene.useRightHandedSystem = true;
  106562. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  106563. gltfRuntime.importOnlyMeshes = true;
  106564. if (meshesNames === "") {
  106565. gltfRuntime.importMeshesNames = [];
  106566. }
  106567. else if (typeof meshesNames === "string") {
  106568. gltfRuntime.importMeshesNames = [meshesNames];
  106569. }
  106570. else if (meshesNames && !(meshesNames instanceof Array)) {
  106571. gltfRuntime.importMeshesNames = [meshesNames];
  106572. }
  106573. else {
  106574. gltfRuntime.importMeshesNames = [];
  106575. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  106576. }
  106577. // Create nodes
  106578. _this._createNodes(gltfRuntime);
  106579. var meshes = new Array();
  106580. var skeletons = new Array();
  106581. // Fill arrays of meshes and skeletons
  106582. for (var nde in gltfRuntime.nodes) {
  106583. var node = gltfRuntime.nodes[nde];
  106584. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  106585. meshes.push(node.babylonNode);
  106586. }
  106587. }
  106588. for (var skl in gltfRuntime.skins) {
  106589. var skin = gltfRuntime.skins[skl];
  106590. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  106591. skeletons.push(skin.babylonSkeleton);
  106592. }
  106593. }
  106594. // Load buffers, shaders, materials, etc.
  106595. _this._loadBuffersAsync(gltfRuntime, function () {
  106596. _this._loadShadersAsync(gltfRuntime, function () {
  106597. importMaterials(gltfRuntime);
  106598. postLoad(gltfRuntime);
  106599. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  106600. onSuccess(meshes, skeletons);
  106601. }
  106602. });
  106603. }, onProgress);
  106604. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  106605. onSuccess(meshes, skeletons);
  106606. }
  106607. }, onError);
  106608. return true;
  106609. };
  106610. /**
  106611. * Imports one or more meshes from a loaded gltf file and adds them to the scene
  106612. * @param meshesNames a string or array of strings of the mesh names that should be loaded from the file
  106613. * @param scene the scene the meshes should be added to
  106614. * @param data gltf data containing information of the meshes in a loaded file
  106615. * @param rootUrl root url to load from
  106616. * @param onProgress event that fires when loading progress has occured
  106617. * @returns a promise containg the loaded meshes, particles, skeletons and animations
  106618. */
  106619. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  106620. var _this = this;
  106621. return new Promise(function (resolve, reject) {
  106622. _this._importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, skeletons) {
  106623. resolve({
  106624. meshes: meshes,
  106625. particleSystems: [],
  106626. skeletons: skeletons,
  106627. animationGroups: []
  106628. });
  106629. }, onProgress, function (message) {
  106630. reject(new Error(message));
  106631. });
  106632. });
  106633. };
  106634. GLTFLoader.prototype._loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  106635. var _this = this;
  106636. scene.useRightHandedSystem = true;
  106637. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  106638. // Load runtime extensios
  106639. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  106640. // Create nodes
  106641. _this._createNodes(gltfRuntime);
  106642. // Load buffers, shaders, materials, etc.
  106643. _this._loadBuffersAsync(gltfRuntime, function () {
  106644. _this._loadShadersAsync(gltfRuntime, function () {
  106645. importMaterials(gltfRuntime);
  106646. postLoad(gltfRuntime);
  106647. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  106648. onSuccess();
  106649. }
  106650. });
  106651. });
  106652. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  106653. onSuccess();
  106654. }
  106655. }, onError);
  106656. }, onError);
  106657. };
  106658. /**
  106659. * Imports all objects from a loaded gltf file and adds them to the scene
  106660. * @param scene the scene the objects should be added to
  106661. * @param data gltf data containing information of the meshes in a loaded file
  106662. * @param rootUrl root url to load from
  106663. * @param onProgress event that fires when loading progress has occured
  106664. * @returns a promise which completes when objects have been loaded to the scene
  106665. */
  106666. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  106667. var _this = this;
  106668. return new Promise(function (resolve, reject) {
  106669. _this._loadAsync(scene, data, rootUrl, function () {
  106670. resolve();
  106671. }, onProgress, function (message) {
  106672. reject(new Error(message));
  106673. });
  106674. });
  106675. };
  106676. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  106677. var hasShaders = false;
  106678. var processShader = function (sha, shader) {
  106679. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  106680. if (shaderString instanceof ArrayBuffer) {
  106681. return;
  106682. }
  106683. gltfRuntime.loadedShaderCount++;
  106684. if (shaderString) {
  106685. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  106686. }
  106687. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  106688. onload();
  106689. }
  106690. }, function () {
  106691. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  106692. });
  106693. };
  106694. for (var sha in gltfRuntime.shaders) {
  106695. hasShaders = true;
  106696. var shader = gltfRuntime.shaders[sha];
  106697. if (shader) {
  106698. processShader.bind(this, sha, shader)();
  106699. }
  106700. else {
  106701. BABYLON.Tools.Error("No shader named: " + sha);
  106702. }
  106703. }
  106704. if (!hasShaders) {
  106705. onload();
  106706. }
  106707. };
  106708. ;
  106709. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  106710. var hasBuffers = false;
  106711. var processBuffer = function (buf, buffer) {
  106712. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  106713. gltfRuntime.loadedBufferCount++;
  106714. if (bufferView) {
  106715. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  106716. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  106717. }
  106718. gltfRuntime.loadedBufferViews[buf] = bufferView;
  106719. }
  106720. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  106721. onLoad();
  106722. }
  106723. }, function () {
  106724. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  106725. });
  106726. };
  106727. for (var buf in gltfRuntime.buffers) {
  106728. hasBuffers = true;
  106729. var buffer = gltfRuntime.buffers[buf];
  106730. if (buffer) {
  106731. processBuffer.bind(this, buf, buffer)();
  106732. }
  106733. else {
  106734. BABYLON.Tools.Error("No buffer named: " + buf);
  106735. }
  106736. }
  106737. if (!hasBuffers) {
  106738. onLoad();
  106739. }
  106740. };
  106741. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  106742. var currentScene = gltfRuntime.currentScene;
  106743. if (currentScene) {
  106744. // Only one scene even if multiple scenes are defined
  106745. for (var i = 0; i < currentScene.nodes.length; i++) {
  106746. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  106747. }
  106748. }
  106749. else {
  106750. // Load all scenes
  106751. for (var thing in gltfRuntime.scenes) {
  106752. currentScene = gltfRuntime.scenes[thing];
  106753. for (var i = 0; i < currentScene.nodes.length; i++) {
  106754. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  106755. }
  106756. }
  106757. }
  106758. };
  106759. GLTFLoader.Extensions = {};
  106760. return GLTFLoader;
  106761. }());
  106762. GLTF1.GLTFLoader = GLTFLoader;
  106763. ;
  106764. BABYLON.GLTFFileLoader._CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  106765. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  106766. })(BABYLON || (BABYLON = {}));
  106767. //# sourceMappingURL=babylon.glTFLoader.js.map
  106768. var BABYLON;
  106769. (function (BABYLON) {
  106770. var GLTF1;
  106771. (function (GLTF1) {
  106772. /**
  106773. * Utils functions for GLTF
  106774. */
  106775. var GLTFUtils = /** @class */ (function () {
  106776. function GLTFUtils() {
  106777. }
  106778. /**
  106779. * Sets the given "parameter" matrix
  106780. * @param scene: the {BABYLON.Scene} object
  106781. * @param source: the source node where to pick the matrix
  106782. * @param parameter: the GLTF technique parameter
  106783. * @param uniformName: the name of the shader's uniform
  106784. * @param shaderMaterial: the shader material
  106785. */
  106786. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  106787. var mat = null;
  106788. if (parameter.semantic === "MODEL") {
  106789. mat = source.getWorldMatrix();
  106790. }
  106791. else if (parameter.semantic === "PROJECTION") {
  106792. mat = scene.getProjectionMatrix();
  106793. }
  106794. else if (parameter.semantic === "VIEW") {
  106795. mat = scene.getViewMatrix();
  106796. }
  106797. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  106798. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  106799. }
  106800. else if (parameter.semantic === "MODELVIEW") {
  106801. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  106802. }
  106803. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  106804. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  106805. }
  106806. else if (parameter.semantic === "MODELINVERSE") {
  106807. mat = source.getWorldMatrix().invert();
  106808. }
  106809. else if (parameter.semantic === "VIEWINVERSE") {
  106810. mat = scene.getViewMatrix().invert();
  106811. }
  106812. else if (parameter.semantic === "PROJECTIONINVERSE") {
  106813. mat = scene.getProjectionMatrix().invert();
  106814. }
  106815. else if (parameter.semantic === "MODELVIEWINVERSE") {
  106816. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  106817. }
  106818. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  106819. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  106820. }
  106821. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  106822. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  106823. }
  106824. else {
  106825. debugger;
  106826. }
  106827. if (mat) {
  106828. switch (parameter.type) {
  106829. case GLTF1.EParameterType.FLOAT_MAT2:
  106830. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  106831. break;
  106832. case GLTF1.EParameterType.FLOAT_MAT3:
  106833. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  106834. break;
  106835. case GLTF1.EParameterType.FLOAT_MAT4:
  106836. shaderMaterial.setMatrix(uniformName, mat);
  106837. break;
  106838. default: break;
  106839. }
  106840. }
  106841. };
  106842. /**
  106843. * Sets the given "parameter" matrix
  106844. * @param shaderMaterial: the shader material
  106845. * @param uniform: the name of the shader's uniform
  106846. * @param value: the value of the uniform
  106847. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  106848. */
  106849. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  106850. switch (type) {
  106851. case GLTF1.EParameterType.FLOAT:
  106852. shaderMaterial.setFloat(uniform, value);
  106853. return true;
  106854. case GLTF1.EParameterType.FLOAT_VEC2:
  106855. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  106856. return true;
  106857. case GLTF1.EParameterType.FLOAT_VEC3:
  106858. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  106859. return true;
  106860. case GLTF1.EParameterType.FLOAT_VEC4:
  106861. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  106862. return true;
  106863. default: return false;
  106864. }
  106865. };
  106866. /**
  106867. * Returns the wrap mode of the texture
  106868. * @param mode: the mode value
  106869. */
  106870. GLTFUtils.GetWrapMode = function (mode) {
  106871. switch (mode) {
  106872. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  106873. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  106874. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  106875. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  106876. }
  106877. };
  106878. /**
  106879. * Returns the byte stride giving an accessor
  106880. * @param accessor: the GLTF accessor objet
  106881. */
  106882. GLTFUtils.GetByteStrideFromType = function (accessor) {
  106883. // Needs this function since "byteStride" isn't requiered in glTF format
  106884. var type = accessor.type;
  106885. switch (type) {
  106886. case "VEC2": return 2;
  106887. case "VEC3": return 3;
  106888. case "VEC4": return 4;
  106889. case "MAT2": return 4;
  106890. case "MAT3": return 9;
  106891. case "MAT4": return 16;
  106892. default: return 1;
  106893. }
  106894. };
  106895. /**
  106896. * Returns the texture filter mode giving a mode value
  106897. * @param mode: the filter mode value
  106898. */
  106899. GLTFUtils.GetTextureFilterMode = function (mode) {
  106900. switch (mode) {
  106901. case GLTF1.ETextureFilterType.LINEAR:
  106902. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  106903. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  106904. case GLTF1.ETextureFilterType.NEAREST:
  106905. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  106906. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  106907. }
  106908. };
  106909. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  106910. var byteOffset = bufferView.byteOffset + byteOffset;
  106911. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  106912. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  106913. throw new Error("Buffer access is out of range");
  106914. }
  106915. var buffer = loadedBufferView.buffer;
  106916. byteOffset += loadedBufferView.byteOffset;
  106917. switch (componentType) {
  106918. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  106919. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  106920. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  106921. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  106922. default: return new Float32Array(buffer, byteOffset, byteLength);
  106923. }
  106924. };
  106925. /**
  106926. * Returns a buffer from its accessor
  106927. * @param gltfRuntime: the GLTF runtime
  106928. * @param accessor: the GLTF accessor
  106929. */
  106930. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  106931. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  106932. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  106933. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  106934. };
  106935. /**
  106936. * Decodes a buffer view into a string
  106937. * @param view: the buffer view
  106938. */
  106939. GLTFUtils.DecodeBufferToText = function (view) {
  106940. var result = "";
  106941. var length = view.byteLength;
  106942. for (var i = 0; i < length; ++i) {
  106943. result += String.fromCharCode(view[i]);
  106944. }
  106945. return result;
  106946. };
  106947. /**
  106948. * Returns the default material of gltf. Related to
  106949. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  106950. * @param scene: the Babylon.js scene
  106951. */
  106952. GLTFUtils.GetDefaultMaterial = function (scene) {
  106953. if (!GLTFUtils._DefaultMaterial) {
  106954. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  106955. "precision highp float;",
  106956. "",
  106957. "uniform mat4 worldView;",
  106958. "uniform mat4 projection;",
  106959. "",
  106960. "attribute vec3 position;",
  106961. "",
  106962. "void main(void)",
  106963. "{",
  106964. " gl_Position = projection * worldView * vec4(position, 1.0);",
  106965. "}"
  106966. ].join("\n");
  106967. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  106968. "precision highp float;",
  106969. "",
  106970. "uniform vec4 u_emission;",
  106971. "",
  106972. "void main(void)",
  106973. "{",
  106974. " gl_FragColor = u_emission;",
  106975. "}"
  106976. ].join("\n");
  106977. var shaderPath = {
  106978. vertex: "GLTFDefaultMaterial",
  106979. fragment: "GLTFDefaultMaterial"
  106980. };
  106981. var options = {
  106982. attributes: ["position"],
  106983. uniforms: ["worldView", "projection", "u_emission"],
  106984. samplers: new Array(),
  106985. needAlphaBlending: false
  106986. };
  106987. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  106988. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  106989. }
  106990. return GLTFUtils._DefaultMaterial;
  106991. };
  106992. // The GLTF default material
  106993. GLTFUtils._DefaultMaterial = null;
  106994. return GLTFUtils;
  106995. }());
  106996. GLTF1.GLTFUtils = GLTFUtils;
  106997. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  106998. })(BABYLON || (BABYLON = {}));
  106999. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  107000. var BABYLON;
  107001. (function (BABYLON) {
  107002. var GLTF1;
  107003. (function (GLTF1) {
  107004. var GLTFLoaderExtension = /** @class */ (function () {
  107005. function GLTFLoaderExtension(name) {
  107006. this._name = name;
  107007. }
  107008. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  107009. get: function () {
  107010. return this._name;
  107011. },
  107012. enumerable: true,
  107013. configurable: true
  107014. });
  107015. /**
  107016. * Defines an override for loading the runtime
  107017. * Return true to stop further extensions from loading the runtime
  107018. */
  107019. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  107020. return false;
  107021. };
  107022. /**
  107023. * Defines an onverride for creating gltf runtime
  107024. * Return true to stop further extensions from creating the runtime
  107025. */
  107026. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  107027. return false;
  107028. };
  107029. /**
  107030. * Defines an override for loading buffers
  107031. * Return true to stop further extensions from loading this buffer
  107032. */
  107033. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  107034. return false;
  107035. };
  107036. /**
  107037. * Defines an override for loading texture buffers
  107038. * Return true to stop further extensions from loading this texture data
  107039. */
  107040. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  107041. return false;
  107042. };
  107043. /**
  107044. * Defines an override for creating textures
  107045. * Return true to stop further extensions from loading this texture
  107046. */
  107047. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  107048. return false;
  107049. };
  107050. /**
  107051. * Defines an override for loading shader strings
  107052. * Return true to stop further extensions from loading this shader data
  107053. */
  107054. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  107055. return false;
  107056. };
  107057. /**
  107058. * Defines an override for loading materials
  107059. * Return true to stop further extensions from loading this material
  107060. */
  107061. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  107062. return false;
  107063. };
  107064. // ---------
  107065. // Utilities
  107066. // ---------
  107067. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  107068. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  107069. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  107070. }, function () {
  107071. setTimeout(function () {
  107072. if (!onSuccess) {
  107073. return;
  107074. }
  107075. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  107076. });
  107077. });
  107078. };
  107079. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  107080. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  107081. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  107082. }, function () {
  107083. setTimeout(function () {
  107084. onSuccess();
  107085. });
  107086. });
  107087. };
  107088. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  107089. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  107090. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  107091. }, function () {
  107092. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  107093. });
  107094. };
  107095. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  107096. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  107097. if (buffer) {
  107098. GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  107099. }
  107100. }, onError);
  107101. };
  107102. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  107103. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  107104. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  107105. }, function () {
  107106. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  107107. });
  107108. };
  107109. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  107110. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  107111. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  107112. }, function () {
  107113. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  107114. });
  107115. };
  107116. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  107117. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  107118. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  107119. }, function () {
  107120. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  107121. });
  107122. };
  107123. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  107124. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  107125. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  107126. }, function () {
  107127. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  107128. });
  107129. };
  107130. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  107131. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  107132. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  107133. if (func(loaderExtension)) {
  107134. return;
  107135. }
  107136. }
  107137. defaultFunc();
  107138. };
  107139. return GLTFLoaderExtension;
  107140. }());
  107141. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  107142. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  107143. })(BABYLON || (BABYLON = {}));
  107144. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  107145. var BABYLON;
  107146. (function (BABYLON) {
  107147. var GLTF1;
  107148. (function (GLTF1) {
  107149. var BinaryExtensionBufferName = "binary_glTF";
  107150. ;
  107151. ;
  107152. var GLTFBinaryExtension = /** @class */ (function (_super) {
  107153. __extends(GLTFBinaryExtension, _super);
  107154. function GLTFBinaryExtension() {
  107155. return _super.call(this, "KHR_binary_glTF") || this;
  107156. }
  107157. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  107158. var extensionsUsed = data.json.extensionsUsed;
  107159. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {
  107160. return false;
  107161. }
  107162. this._bin = data.bin;
  107163. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  107164. return true;
  107165. };
  107166. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  107167. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  107168. return false;
  107169. }
  107170. if (id !== BinaryExtensionBufferName) {
  107171. return false;
  107172. }
  107173. onSuccess(this._bin);
  107174. return true;
  107175. };
  107176. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  107177. var texture = gltfRuntime.textures[id];
  107178. var source = gltfRuntime.images[texture.source];
  107179. if (!source.extensions || !(this.name in source.extensions)) {
  107180. return false;
  107181. }
  107182. var sourceExt = source.extensions[this.name];
  107183. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  107184. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  107185. onSuccess(buffer);
  107186. return true;
  107187. };
  107188. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  107189. var shader = gltfRuntime.shaders[id];
  107190. if (!shader.extensions || !(this.name in shader.extensions)) {
  107191. return false;
  107192. }
  107193. var binaryExtensionShader = shader.extensions[this.name];
  107194. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  107195. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  107196. setTimeout(function () {
  107197. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  107198. onSuccess(shaderString);
  107199. });
  107200. return true;
  107201. };
  107202. return GLTFBinaryExtension;
  107203. }(GLTF1.GLTFLoaderExtension));
  107204. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  107205. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  107206. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  107207. })(BABYLON || (BABYLON = {}));
  107208. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  107209. var BABYLON;
  107210. (function (BABYLON) {
  107211. var GLTF1;
  107212. (function (GLTF1) {
  107213. ;
  107214. ;
  107215. ;
  107216. var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {
  107217. __extends(GLTFMaterialsCommonExtension, _super);
  107218. function GLTFMaterialsCommonExtension() {
  107219. return _super.call(this, "KHR_materials_common") || this;
  107220. }
  107221. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  107222. if (!gltfRuntime.extensions)
  107223. return false;
  107224. var extension = gltfRuntime.extensions[this.name];
  107225. if (!extension)
  107226. return false;
  107227. // Create lights
  107228. var lights = extension.lights;
  107229. if (lights) {
  107230. for (var thing in lights) {
  107231. var light = lights[thing];
  107232. switch (light.type) {
  107233. case "ambient":
  107234. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  107235. var ambient = light.ambient;
  107236. if (ambient) {
  107237. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  107238. }
  107239. break;
  107240. case "point":
  107241. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  107242. var point = light.point;
  107243. if (point) {
  107244. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  107245. }
  107246. break;
  107247. case "directional":
  107248. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  107249. var directional = light.directional;
  107250. if (directional) {
  107251. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  107252. }
  107253. break;
  107254. case "spot":
  107255. var spot = light.spot;
  107256. if (spot) {
  107257. 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);
  107258. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  107259. }
  107260. break;
  107261. default:
  107262. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  107263. break;
  107264. }
  107265. }
  107266. }
  107267. return false;
  107268. };
  107269. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  107270. var material = gltfRuntime.materials[id];
  107271. if (!material || !material.extensions)
  107272. return false;
  107273. var extension = material.extensions[this.name];
  107274. if (!extension)
  107275. return false;
  107276. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  107277. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  107278. if (extension.technique === "CONSTANT") {
  107279. standardMaterial.disableLighting = true;
  107280. }
  107281. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  107282. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  107283. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  107284. // Ambient
  107285. if (typeof extension.values.ambient === "string") {
  107286. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  107287. }
  107288. else {
  107289. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  107290. }
  107291. // Diffuse
  107292. if (typeof extension.values.diffuse === "string") {
  107293. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  107294. }
  107295. else {
  107296. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  107297. }
  107298. // Emission
  107299. if (typeof extension.values.emission === "string") {
  107300. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  107301. }
  107302. else {
  107303. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  107304. }
  107305. // Specular
  107306. if (typeof extension.values.specular === "string") {
  107307. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  107308. }
  107309. else {
  107310. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  107311. }
  107312. return true;
  107313. };
  107314. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  107315. // Create buffer from texture url
  107316. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  107317. // Create texture from buffer
  107318. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  107319. }, onError);
  107320. };
  107321. return GLTFMaterialsCommonExtension;
  107322. }(GLTF1.GLTFLoaderExtension));
  107323. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  107324. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  107325. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  107326. })(BABYLON || (BABYLON = {}));
  107327. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  107328. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  107329. /**
  107330. * Defines the module used to import/export glTF 2.0 assets
  107331. */
  107332. var BABYLON;
  107333. (function (BABYLON) {
  107334. var GLTF2;
  107335. (function (GLTF2) {
  107336. var _ArrayItem = /** @class */ (function () {
  107337. function _ArrayItem() {
  107338. }
  107339. _ArrayItem.Assign = function (values) {
  107340. if (values) {
  107341. for (var index = 0; index < values.length; index++) {
  107342. values[index]._index = index;
  107343. }
  107344. }
  107345. };
  107346. return _ArrayItem;
  107347. }());
  107348. /** @hidden */
  107349. var GLTFLoader = /** @class */ (function () {
  107350. function GLTFLoader(parent) {
  107351. this._completePromises = new Array();
  107352. this._disposed = false;
  107353. this._state = null;
  107354. this._extensions = {};
  107355. this._defaultSampler = {};
  107356. this._defaultBabylonMaterials = {};
  107357. this._requests = new Array();
  107358. this._parent = parent;
  107359. }
  107360. GLTFLoader._Register = function (name, factory) {
  107361. if (GLTFLoader._ExtensionFactories[name]) {
  107362. BABYLON.Tools.Error("Extension with the name '" + name + "' already exists");
  107363. return;
  107364. }
  107365. GLTFLoader._ExtensionFactories[name] = factory;
  107366. // Keep the order of registration so that extensions registered first are called first.
  107367. GLTFLoader._ExtensionNames.push(name);
  107368. };
  107369. Object.defineProperty(GLTFLoader.prototype, "state", {
  107370. /**
  107371. * Loader state or null if the loader is not active.
  107372. */
  107373. get: function () {
  107374. return this._state;
  107375. },
  107376. enumerable: true,
  107377. configurable: true
  107378. });
  107379. GLTFLoader.prototype.dispose = function () {
  107380. if (this._disposed) {
  107381. return;
  107382. }
  107383. this._disposed = true;
  107384. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  107385. var request = _a[_i];
  107386. request.abort();
  107387. }
  107388. this._requests.length = 0;
  107389. delete this._gltf;
  107390. delete this._babylonScene;
  107391. delete this._readyPromise;
  107392. this._completePromises.length = 0;
  107393. for (var name_1 in this._extensions) {
  107394. this._extensions[name_1].dispose();
  107395. }
  107396. this._extensions = {};
  107397. delete this._rootBabylonMesh;
  107398. delete this._progressCallback;
  107399. this._parent._clear();
  107400. };
  107401. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  107402. var _this = this;
  107403. return Promise.resolve().then(function () {
  107404. _this._babylonScene = scene;
  107405. _this._rootUrl = rootUrl;
  107406. _this._progressCallback = onProgress;
  107407. _this._loadData(data);
  107408. var nodes = null;
  107409. if (meshesNames) {
  107410. var nodeMap_1 = {};
  107411. if (_this._gltf.nodes) {
  107412. for (var _i = 0, _a = _this._gltf.nodes; _i < _a.length; _i++) {
  107413. var node = _a[_i];
  107414. if (node.name) {
  107415. nodeMap_1[node.name] = node._index;
  107416. }
  107417. }
  107418. }
  107419. var names = (meshesNames instanceof Array) ? meshesNames : [meshesNames];
  107420. nodes = names.map(function (name) {
  107421. var node = nodeMap_1[name];
  107422. if (node === undefined) {
  107423. throw new Error("Failed to find node '" + name + "'");
  107424. }
  107425. return node;
  107426. });
  107427. }
  107428. return _this._loadAsync(nodes).then(function () {
  107429. return {
  107430. meshes: _this._getMeshes(),
  107431. particleSystems: [],
  107432. skeletons: _this._getSkeletons(),
  107433. animationGroups: _this._getAnimationGroups()
  107434. };
  107435. });
  107436. });
  107437. };
  107438. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  107439. var _this = this;
  107440. return Promise.resolve().then(function () {
  107441. _this._babylonScene = scene;
  107442. _this._rootUrl = rootUrl;
  107443. _this._progressCallback = onProgress;
  107444. _this._loadData(data);
  107445. return _this._loadAsync(null);
  107446. });
  107447. };
  107448. GLTFLoader.prototype._loadAsync = function (nodes) {
  107449. var _this = this;
  107450. return Promise.resolve().then(function () {
  107451. _this._parent._startPerformanceCounter("Loading => Ready");
  107452. _this._parent._startPerformanceCounter("Loading => Complete");
  107453. _this._state = BABYLON.GLTFLoaderState.LOADING;
  107454. _this._parent._log("Loading");
  107455. var readyDeferred = new BABYLON.Deferred();
  107456. _this._readyPromise = readyDeferred.promise;
  107457. _this._loadExtensions();
  107458. _this._checkExtensions();
  107459. var promises = new Array();
  107460. if (nodes) {
  107461. promises.push(_this._loadSceneAsync("#/nodes", { nodes: nodes, _index: -1 }));
  107462. }
  107463. else {
  107464. var scene = GLTFLoader._GetProperty("#/scene", _this._gltf.scenes, _this._gltf.scene || 0);
  107465. promises.push(_this._loadSceneAsync("#/scenes/" + scene._index, scene));
  107466. }
  107467. if (_this._parent.compileMaterials) {
  107468. promises.push(_this._compileMaterialsAsync());
  107469. }
  107470. if (_this._parent.compileShadowGenerators) {
  107471. promises.push(_this._compileShadowGeneratorsAsync());
  107472. }
  107473. var resultPromise = Promise.all(promises).then(function () {
  107474. _this._state = BABYLON.GLTFLoaderState.READY;
  107475. _this._parent._log("Ready");
  107476. readyDeferred.resolve();
  107477. _this._startAnimations();
  107478. });
  107479. resultPromise.then(function () {
  107480. _this._parent._endPerformanceCounter("Loading => Ready");
  107481. if (_this._rootBabylonMesh) {
  107482. _this._rootBabylonMesh.setEnabled(true);
  107483. }
  107484. BABYLON.Tools.SetImmediate(function () {
  107485. if (!_this._disposed) {
  107486. Promise.all(_this._completePromises).then(function () {
  107487. _this._parent._endPerformanceCounter("Loading => Complete");
  107488. _this._state = BABYLON.GLTFLoaderState.COMPLETE;
  107489. _this._parent._log("Complete");
  107490. _this._parent.onCompleteObservable.notifyObservers(undefined);
  107491. _this._parent.onCompleteObservable.clear();
  107492. _this.dispose();
  107493. }).catch(function (error) {
  107494. BABYLON.Tools.Error("glTF Loader: " + error.message);
  107495. _this.dispose();
  107496. });
  107497. }
  107498. });
  107499. });
  107500. return resultPromise;
  107501. }).catch(function (error) {
  107502. if (!_this._disposed) {
  107503. BABYLON.Tools.Error("glTF Loader: " + error.message);
  107504. _this.dispose();
  107505. throw error;
  107506. }
  107507. });
  107508. };
  107509. GLTFLoader.prototype._loadData = function (data) {
  107510. this._gltf = data.json;
  107511. this._setupData();
  107512. if (data.bin) {
  107513. var buffers = this._gltf.buffers;
  107514. if (buffers && buffers[0] && !buffers[0].uri) {
  107515. var binaryBuffer = buffers[0];
  107516. if (binaryBuffer.byteLength < data.bin.byteLength - 3 || binaryBuffer.byteLength > data.bin.byteLength) {
  107517. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  107518. }
  107519. binaryBuffer._data = Promise.resolve(data.bin);
  107520. }
  107521. else {
  107522. BABYLON.Tools.Warn("Unexpected BIN chunk");
  107523. }
  107524. }
  107525. };
  107526. GLTFLoader.prototype._setupData = function () {
  107527. _ArrayItem.Assign(this._gltf.accessors);
  107528. _ArrayItem.Assign(this._gltf.animations);
  107529. _ArrayItem.Assign(this._gltf.buffers);
  107530. _ArrayItem.Assign(this._gltf.bufferViews);
  107531. _ArrayItem.Assign(this._gltf.cameras);
  107532. _ArrayItem.Assign(this._gltf.images);
  107533. _ArrayItem.Assign(this._gltf.materials);
  107534. _ArrayItem.Assign(this._gltf.meshes);
  107535. _ArrayItem.Assign(this._gltf.nodes);
  107536. _ArrayItem.Assign(this._gltf.samplers);
  107537. _ArrayItem.Assign(this._gltf.scenes);
  107538. _ArrayItem.Assign(this._gltf.skins);
  107539. _ArrayItem.Assign(this._gltf.textures);
  107540. if (this._gltf.nodes) {
  107541. var nodeParents = {};
  107542. for (var _i = 0, _a = this._gltf.nodes; _i < _a.length; _i++) {
  107543. var node = _a[_i];
  107544. if (node.children) {
  107545. for (var _b = 0, _c = node.children; _b < _c.length; _b++) {
  107546. var index = _c[_b];
  107547. nodeParents[index] = node._index;
  107548. }
  107549. }
  107550. }
  107551. var rootNode = this._createRootNode();
  107552. for (var _d = 0, _e = this._gltf.nodes; _d < _e.length; _d++) {
  107553. var node = _e[_d];
  107554. var parentIndex = nodeParents[node._index];
  107555. node._parent = parentIndex === undefined ? rootNode : this._gltf.nodes[parentIndex];
  107556. }
  107557. }
  107558. };
  107559. GLTFLoader.prototype._loadExtensions = function () {
  107560. for (var _i = 0, _a = GLTFLoader._ExtensionNames; _i < _a.length; _i++) {
  107561. var name_2 = _a[_i];
  107562. var extension = GLTFLoader._ExtensionFactories[name_2](this);
  107563. this._extensions[name_2] = extension;
  107564. this._parent.onExtensionLoadedObservable.notifyObservers(extension);
  107565. }
  107566. this._parent.onExtensionLoadedObservable.clear();
  107567. };
  107568. GLTFLoader.prototype._checkExtensions = function () {
  107569. if (this._gltf.extensionsRequired) {
  107570. for (var _i = 0, _a = this._gltf.extensionsRequired; _i < _a.length; _i++) {
  107571. var name_3 = _a[_i];
  107572. var extension = this._extensions[name_3];
  107573. if (!extension || !extension.enabled) {
  107574. throw new Error("Require extension " + name_3 + " is not available");
  107575. }
  107576. }
  107577. }
  107578. };
  107579. GLTFLoader.prototype._createRootNode = function () {
  107580. this._rootBabylonMesh = new BABYLON.Mesh("__root__", this._babylonScene);
  107581. this._rootBabylonMesh.setEnabled(false);
  107582. var rootNode = { _babylonMesh: this._rootBabylonMesh };
  107583. switch (this._parent.coordinateSystemMode) {
  107584. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO: {
  107585. if (!this._babylonScene.useRightHandedSystem) {
  107586. rootNode.rotation = [0, 1, 0, 0];
  107587. rootNode.scale = [1, 1, -1];
  107588. GLTFLoader._LoadTransform(rootNode, this._rootBabylonMesh);
  107589. }
  107590. break;
  107591. }
  107592. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  107593. this._babylonScene.useRightHandedSystem = true;
  107594. break;
  107595. }
  107596. default: {
  107597. throw new Error("Invalid coordinate system mode (" + this._parent.coordinateSystemMode + ")");
  107598. }
  107599. }
  107600. this._parent.onMeshLoadedObservable.notifyObservers(this._rootBabylonMesh);
  107601. return rootNode;
  107602. };
  107603. GLTFLoader.prototype._loadSceneAsync = function (context, scene) {
  107604. var promise = GLTF2.GLTFLoaderExtension._LoadSceneAsync(this, context, scene);
  107605. if (promise) {
  107606. return promise;
  107607. }
  107608. var promises = new Array();
  107609. this._parent._logOpen(context + " " + (scene.name || ""));
  107610. if (scene.nodes) {
  107611. for (var _i = 0, _a = scene.nodes; _i < _a.length; _i++) {
  107612. var index = _a[_i];
  107613. var node = GLTFLoader._GetProperty(context + "/nodes/" + index, this._gltf.nodes, index);
  107614. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  107615. }
  107616. }
  107617. promises.push(this._loadAnimationsAsync());
  107618. this._parent._logClose();
  107619. return Promise.all(promises).then(function () { });
  107620. };
  107621. GLTFLoader.prototype._forEachPrimitive = function (node, callback) {
  107622. if (node._primitiveBabylonMeshes) {
  107623. for (var _i = 0, _a = node._primitiveBabylonMeshes; _i < _a.length; _i++) {
  107624. var babylonMesh = _a[_i];
  107625. callback(babylonMesh);
  107626. }
  107627. }
  107628. else {
  107629. callback(node._babylonMesh);
  107630. }
  107631. };
  107632. GLTFLoader.prototype._getMeshes = function () {
  107633. var meshes = new Array();
  107634. // Root mesh is always first.
  107635. meshes.push(this._rootBabylonMesh);
  107636. var nodes = this._gltf.nodes;
  107637. if (nodes) {
  107638. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  107639. var node = nodes_1[_i];
  107640. if (node._babylonMesh) {
  107641. meshes.push(node._babylonMesh);
  107642. }
  107643. if (node._primitiveBabylonMeshes) {
  107644. for (var _a = 0, _b = node._primitiveBabylonMeshes; _a < _b.length; _a++) {
  107645. var babylonMesh = _b[_a];
  107646. meshes.push(babylonMesh);
  107647. }
  107648. }
  107649. }
  107650. }
  107651. return meshes;
  107652. };
  107653. GLTFLoader.prototype._getSkeletons = function () {
  107654. var skeletons = new Array();
  107655. var skins = this._gltf.skins;
  107656. if (skins) {
  107657. for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {
  107658. var skin = skins_1[_i];
  107659. if (skin._babylonSkeleton) {
  107660. skeletons.push(skin._babylonSkeleton);
  107661. }
  107662. }
  107663. }
  107664. return skeletons;
  107665. };
  107666. GLTFLoader.prototype._getAnimationGroups = function () {
  107667. var animationGroups = new Array();
  107668. var animations = this._gltf.animations;
  107669. if (animations) {
  107670. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  107671. var animation = animations_1[_i];
  107672. if (animation._babylonAnimationGroup) {
  107673. animationGroups.push(animation._babylonAnimationGroup);
  107674. }
  107675. }
  107676. }
  107677. return animationGroups;
  107678. };
  107679. GLTFLoader.prototype._startAnimations = function () {
  107680. switch (this._parent.animationStartMode) {
  107681. case BABYLON.GLTFLoaderAnimationStartMode.NONE: {
  107682. // do nothing
  107683. break;
  107684. }
  107685. case BABYLON.GLTFLoaderAnimationStartMode.FIRST: {
  107686. var babylonAnimationGroups = this._getAnimationGroups();
  107687. if (babylonAnimationGroups.length !== 0) {
  107688. babylonAnimationGroups[0].start(true);
  107689. }
  107690. break;
  107691. }
  107692. case BABYLON.GLTFLoaderAnimationStartMode.ALL: {
  107693. var babylonAnimationGroups = this._getAnimationGroups();
  107694. for (var _i = 0, babylonAnimationGroups_1 = babylonAnimationGroups; _i < babylonAnimationGroups_1.length; _i++) {
  107695. var babylonAnimationGroup = babylonAnimationGroups_1[_i];
  107696. babylonAnimationGroup.start(true);
  107697. }
  107698. break;
  107699. }
  107700. default: {
  107701. BABYLON.Tools.Error("Invalid animation start mode (" + this._parent.animationStartMode + ")");
  107702. return;
  107703. }
  107704. }
  107705. };
  107706. GLTFLoader.prototype._loadNodeAsync = function (context, node) {
  107707. var promise = GLTF2.GLTFLoaderExtension._LoadNodeAsync(this, context, node);
  107708. if (promise) {
  107709. return promise;
  107710. }
  107711. if (node._babylonMesh) {
  107712. throw new Error(context + ": Invalid recursive node hierarchy");
  107713. }
  107714. var promises = new Array();
  107715. this._parent._logOpen(context + " " + (node.name || ""));
  107716. var babylonMesh = new BABYLON.Mesh(node.name || "node" + node._index, this._babylonScene, node._parent ? node._parent._babylonMesh : null);
  107717. node._babylonMesh = babylonMesh;
  107718. GLTFLoader._LoadTransform(node, babylonMesh);
  107719. if (node.mesh != undefined) {
  107720. var mesh = GLTFLoader._GetProperty(context + "/mesh", this._gltf.meshes, node.mesh);
  107721. promises.push(this._loadMeshAsync("#/meshes/" + mesh._index, node, mesh, babylonMesh));
  107722. }
  107723. if (node.camera != undefined) {
  107724. var camera = GLTFLoader._GetProperty(context + "/camera", this._gltf.cameras, node.camera);
  107725. this._loadCamera("#/cameras/" + camera._index, camera, babylonMesh);
  107726. }
  107727. if (node.children) {
  107728. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  107729. var index = _a[_i];
  107730. var childNode = GLTFLoader._GetProperty(context + "/children/" + index, this._gltf.nodes, index);
  107731. promises.push(this._loadNodeAsync("#/nodes/" + index, childNode));
  107732. }
  107733. }
  107734. this._parent.onMeshLoadedObservable.notifyObservers(babylonMesh);
  107735. this._parent._logClose();
  107736. return Promise.all(promises).then(function () { });
  107737. };
  107738. GLTFLoader.prototype._loadMeshAsync = function (context, node, mesh, babylonMesh) {
  107739. var _this = this;
  107740. var promises = new Array();
  107741. this._parent._logOpen(context + " " + (mesh.name || ""));
  107742. var primitives = mesh.primitives;
  107743. if (!primitives || primitives.length === 0) {
  107744. throw new Error(context + ": Primitives are missing");
  107745. }
  107746. _ArrayItem.Assign(primitives);
  107747. if (primitives.length === 1) {
  107748. var primitive = primitives[0];
  107749. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive, babylonMesh));
  107750. }
  107751. else {
  107752. node._primitiveBabylonMeshes = [];
  107753. for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
  107754. var primitive = primitives_1[_i];
  107755. var primitiveBabylonMesh = new BABYLON.Mesh((mesh.name || babylonMesh.name) + "_" + primitive._index, this._babylonScene, babylonMesh);
  107756. node._primitiveBabylonMeshes.push(primitiveBabylonMesh);
  107757. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive, primitiveBabylonMesh));
  107758. this._parent.onMeshLoadedObservable.notifyObservers(babylonMesh);
  107759. }
  107760. }
  107761. if (node.skin != undefined) {
  107762. var skin = GLTFLoader._GetProperty(context + "/skin", this._gltf.skins, node.skin);
  107763. promises.push(this._loadSkinAsync("#/skins/" + skin._index, node, mesh, skin));
  107764. }
  107765. this._parent._logClose();
  107766. return Promise.all(promises).then(function () {
  107767. _this._forEachPrimitive(node, function (babylonMesh) {
  107768. babylonMesh._refreshBoundingInfo(true);
  107769. });
  107770. });
  107771. };
  107772. GLTFLoader.prototype._loadPrimitiveAsync = function (context, node, mesh, primitive, babylonMesh) {
  107773. var _this = this;
  107774. var promises = new Array();
  107775. this._parent._logOpen("" + context);
  107776. this._createMorphTargets(context, node, mesh, primitive, babylonMesh);
  107777. promises.push(this._loadVertexDataAsync(context, primitive, babylonMesh).then(function (babylonGeometry) {
  107778. return _this._loadMorphTargetsAsync(context, primitive, babylonMesh, babylonGeometry).then(function () {
  107779. babylonGeometry.applyToMesh(babylonMesh);
  107780. });
  107781. }));
  107782. var babylonDrawMode = GLTFLoader._GetDrawMode(context, primitive.mode);
  107783. if (primitive.material == undefined) {
  107784. babylonMesh.material = this._getDefaultMaterial(babylonDrawMode);
  107785. }
  107786. else {
  107787. var material = GLTFLoader._GetProperty(context + "/material}", this._gltf.materials, primitive.material);
  107788. promises.push(this._loadMaterialAsync("#/materials/" + material._index, material, mesh, babylonMesh, babylonDrawMode, function (babylonMaterial) {
  107789. babylonMesh.material = babylonMaterial;
  107790. }));
  107791. }
  107792. this._parent._logClose();
  107793. return Promise.all(promises).then(function () { });
  107794. };
  107795. GLTFLoader.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  107796. var _this = this;
  107797. var promise = GLTF2.GLTFLoaderExtension._LoadVertexDataAsync(this, context, primitive, babylonMesh);
  107798. if (promise) {
  107799. return promise;
  107800. }
  107801. var attributes = primitive.attributes;
  107802. if (!attributes) {
  107803. throw new Error(context + ": Attributes are missing");
  107804. }
  107805. var promises = new Array();
  107806. var babylonGeometry = new BABYLON.Geometry(babylonMesh.name, this._babylonScene);
  107807. if (primitive.indices == undefined) {
  107808. babylonMesh.isUnIndexed = true;
  107809. }
  107810. else {
  107811. var accessor = GLTFLoader._GetProperty(context + "/indices", this._gltf.accessors, primitive.indices);
  107812. promises.push(this._loadIndicesAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  107813. babylonGeometry.setIndices(data);
  107814. }));
  107815. }
  107816. var loadAttribute = function (attribute, kind, callback) {
  107817. if (attributes[attribute] == undefined) {
  107818. return;
  107819. }
  107820. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  107821. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  107822. babylonMesh._delayInfo.push(kind);
  107823. }
  107824. var accessor = GLTFLoader._GetProperty(context + "/attributes/" + attribute, _this._gltf.accessors, attributes[attribute]);
  107825. promises.push(_this._loadVertexAccessorAsync("#/accessors/" + accessor._index, accessor, kind).then(function (babylonVertexBuffer) {
  107826. babylonGeometry.setVerticesBuffer(babylonVertexBuffer, accessor.count);
  107827. }));
  107828. if (callback) {
  107829. callback(accessor);
  107830. }
  107831. };
  107832. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  107833. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  107834. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  107835. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  107836. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  107837. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  107838. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  107839. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind, function (accessor) {
  107840. if (accessor.type === "VEC4" /* VEC4 */) {
  107841. babylonMesh.hasVertexAlpha = true;
  107842. }
  107843. });
  107844. return Promise.all(promises).then(function () {
  107845. return babylonGeometry;
  107846. });
  107847. };
  107848. GLTFLoader.prototype._createMorphTargets = function (context, node, mesh, primitive, babylonMesh) {
  107849. if (!primitive.targets) {
  107850. return;
  107851. }
  107852. if (node._numMorphTargets == undefined) {
  107853. node._numMorphTargets = primitive.targets.length;
  107854. }
  107855. else if (primitive.targets.length !== node._numMorphTargets) {
  107856. throw new Error(context + ": Primitives do not have the same number of targets");
  107857. }
  107858. babylonMesh.morphTargetManager = new BABYLON.MorphTargetManager();
  107859. for (var index = 0; index < primitive.targets.length; index++) {
  107860. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  107861. babylonMesh.morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  107862. // TODO: tell the target whether it has positions, normals, tangents
  107863. }
  107864. };
  107865. GLTFLoader.prototype._loadMorphTargetsAsync = function (context, primitive, babylonMesh, babylonGeometry) {
  107866. if (!primitive.targets) {
  107867. return Promise.resolve();
  107868. }
  107869. var promises = new Array();
  107870. var morphTargetManager = babylonMesh.morphTargetManager;
  107871. for (var index = 0; index < morphTargetManager.numTargets; index++) {
  107872. var babylonMorphTarget = morphTargetManager.getTarget(index);
  107873. promises.push(this._loadMorphTargetVertexDataAsync(context + "/targets/" + index, babylonGeometry, primitive.targets[index], babylonMorphTarget));
  107874. }
  107875. return Promise.all(promises).then(function () { });
  107876. };
  107877. GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, babylonGeometry, attributes, babylonMorphTarget) {
  107878. var _this = this;
  107879. var promises = new Array();
  107880. var loadAttribute = function (attribute, kind, setData) {
  107881. if (attributes[attribute] == undefined) {
  107882. return;
  107883. }
  107884. var babylonVertexBuffer = babylonGeometry.getVertexBuffer(kind);
  107885. if (!babylonVertexBuffer) {
  107886. return;
  107887. }
  107888. var accessor = GLTFLoader._GetProperty(context + "/" + attribute, _this._gltf.accessors, attributes[attribute]);
  107889. promises.push(_this._loadFloatAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  107890. setData(babylonVertexBuffer, data);
  107891. }));
  107892. };
  107893. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind, function (babylonVertexBuffer, data) {
  107894. babylonVertexBuffer.forEach(data.length, function (value, index) {
  107895. data[index] += value;
  107896. });
  107897. babylonMorphTarget.setPositions(data);
  107898. });
  107899. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind, function (babylonVertexBuffer, data) {
  107900. babylonVertexBuffer.forEach(data.length, function (value, index) {
  107901. data[index] += value;
  107902. });
  107903. babylonMorphTarget.setNormals(data);
  107904. });
  107905. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind, function (babylonVertexBuffer, data) {
  107906. var dataIndex = 0;
  107907. babylonVertexBuffer.forEach(data.length / 3 * 4, function (value, index) {
  107908. // Tangent data for morph targets is stored as xyz delta.
  107909. // The vertexData.tangent is stored as xyzw.
  107910. // So we need to skip every fourth vertexData.tangent.
  107911. if (((index + 1) % 4) !== 0) {
  107912. data[dataIndex++] += value;
  107913. }
  107914. });
  107915. babylonMorphTarget.setTangents(data);
  107916. });
  107917. return Promise.all(promises).then(function () { });
  107918. };
  107919. GLTFLoader._LoadTransform = function (node, babylonNode) {
  107920. var position = BABYLON.Vector3.Zero();
  107921. var rotation = BABYLON.Quaternion.Identity();
  107922. var scaling = BABYLON.Vector3.One();
  107923. if (node.matrix) {
  107924. var matrix = BABYLON.Matrix.FromArray(node.matrix);
  107925. matrix.decompose(scaling, rotation, position);
  107926. }
  107927. else {
  107928. if (node.translation)
  107929. position = BABYLON.Vector3.FromArray(node.translation);
  107930. if (node.rotation)
  107931. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  107932. if (node.scale)
  107933. scaling = BABYLON.Vector3.FromArray(node.scale);
  107934. }
  107935. babylonNode.position = position;
  107936. babylonNode.rotationQuaternion = rotation;
  107937. babylonNode.scaling = scaling;
  107938. };
  107939. GLTFLoader.prototype._loadSkinAsync = function (context, node, mesh, skin) {
  107940. var _this = this;
  107941. var assignSkeleton = function (skeleton) {
  107942. _this._forEachPrimitive(node, function (babylonMesh) {
  107943. babylonMesh.skeleton = skeleton;
  107944. });
  107945. // Ignore the TRS of skinned nodes.
  107946. // See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins (second implementation note)
  107947. node._babylonMesh.parent = _this._rootBabylonMesh;
  107948. node._babylonMesh.position = BABYLON.Vector3.Zero();
  107949. node._babylonMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  107950. node._babylonMesh.scaling = BABYLON.Vector3.One();
  107951. };
  107952. if (skin._loaded) {
  107953. return skin._loaded.then(function () {
  107954. assignSkeleton(skin._babylonSkeleton);
  107955. });
  107956. }
  107957. var skeletonId = "skeleton" + skin._index;
  107958. var babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, this._babylonScene);
  107959. skin._babylonSkeleton = babylonSkeleton;
  107960. this._loadBones(context, skin);
  107961. assignSkeleton(babylonSkeleton);
  107962. return (skin._loaded = this._loadSkinInverseBindMatricesDataAsync(context, skin).then(function (inverseBindMatricesData) {
  107963. _this._updateBoneMatrices(babylonSkeleton, inverseBindMatricesData);
  107964. }));
  107965. };
  107966. GLTFLoader.prototype._loadBones = function (context, skin) {
  107967. var babylonBones = {};
  107968. for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {
  107969. var index = _a[_i];
  107970. var node = GLTFLoader._GetProperty(context + "/joints/" + index, this._gltf.nodes, index);
  107971. this._loadBone(node, skin, babylonBones);
  107972. }
  107973. };
  107974. GLTFLoader.prototype._loadBone = function (node, skin, babylonBones) {
  107975. var babylonBone = babylonBones[node._index];
  107976. if (babylonBone) {
  107977. return babylonBone;
  107978. }
  107979. var babylonParentBone = null;
  107980. if (node._parent && node._parent._babylonMesh !== this._rootBabylonMesh) {
  107981. babylonParentBone = this._loadBone(node._parent, skin, babylonBones);
  107982. }
  107983. var boneIndex = skin.joints.indexOf(node._index);
  107984. babylonBone = new BABYLON.Bone(node.name || "joint" + node._index, skin._babylonSkeleton, babylonParentBone, this._getNodeMatrix(node), null, null, boneIndex);
  107985. babylonBones[node._index] = babylonBone;
  107986. node._babylonBones = node._babylonBones || [];
  107987. node._babylonBones.push(babylonBone);
  107988. return babylonBone;
  107989. };
  107990. GLTFLoader.prototype._loadSkinInverseBindMatricesDataAsync = function (context, skin) {
  107991. if (skin.inverseBindMatrices == undefined) {
  107992. return Promise.resolve(null);
  107993. }
  107994. var accessor = GLTFLoader._GetProperty(context + "/inverseBindMatrices", this._gltf.accessors, skin.inverseBindMatrices);
  107995. return this._loadFloatAccessorAsync("#/accessors/" + accessor._index, accessor);
  107996. };
  107997. GLTFLoader.prototype._updateBoneMatrices = function (babylonSkeleton, inverseBindMatricesData) {
  107998. for (var _i = 0, _a = babylonSkeleton.bones; _i < _a.length; _i++) {
  107999. var babylonBone = _a[_i];
  108000. var baseMatrix = BABYLON.Matrix.Identity();
  108001. var boneIndex = babylonBone._index;
  108002. if (inverseBindMatricesData && boneIndex !== -1) {
  108003. BABYLON.Matrix.FromArrayToRef(inverseBindMatricesData, boneIndex * 16, baseMatrix);
  108004. baseMatrix.invertToRef(baseMatrix);
  108005. }
  108006. var babylonParentBone = babylonBone.getParent();
  108007. if (babylonParentBone) {
  108008. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  108009. }
  108010. babylonBone.updateMatrix(baseMatrix, false, false);
  108011. babylonBone._updateDifferenceMatrix(undefined, false);
  108012. }
  108013. };
  108014. GLTFLoader.prototype._getNodeMatrix = function (node) {
  108015. return node.matrix ?
  108016. BABYLON.Matrix.FromArray(node.matrix) :
  108017. 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());
  108018. };
  108019. GLTFLoader.prototype._loadCamera = function (context, camera, babylonMesh) {
  108020. var babylonCamera = new BABYLON.FreeCamera(camera.name || "camera" + camera._index, BABYLON.Vector3.Zero(), this._babylonScene, false);
  108021. babylonCamera.parent = babylonMesh;
  108022. babylonCamera.rotation = new BABYLON.Vector3(0, Math.PI, 0);
  108023. switch (camera.type) {
  108024. case "perspective" /* PERSPECTIVE */: {
  108025. var perspective = camera.perspective;
  108026. if (!perspective) {
  108027. throw new Error(context + ": Camera perspective properties are missing");
  108028. }
  108029. babylonCamera.fov = perspective.yfov;
  108030. babylonCamera.minZ = perspective.znear;
  108031. babylonCamera.maxZ = perspective.zfar || Number.MAX_VALUE;
  108032. break;
  108033. }
  108034. case "orthographic" /* ORTHOGRAPHIC */: {
  108035. if (!camera.orthographic) {
  108036. throw new Error(context + ": Camera orthographic properties are missing");
  108037. }
  108038. babylonCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  108039. babylonCamera.orthoLeft = -camera.orthographic.xmag;
  108040. babylonCamera.orthoRight = camera.orthographic.xmag;
  108041. babylonCamera.orthoBottom = -camera.orthographic.ymag;
  108042. babylonCamera.orthoTop = camera.orthographic.ymag;
  108043. babylonCamera.minZ = camera.orthographic.znear;
  108044. babylonCamera.maxZ = camera.orthographic.zfar;
  108045. break;
  108046. }
  108047. default: {
  108048. throw new Error(context + ": Invalid camera type (" + camera.type + ")");
  108049. }
  108050. }
  108051. this._parent.onCameraLoadedObservable.notifyObservers(babylonCamera);
  108052. };
  108053. GLTFLoader.prototype._loadAnimationsAsync = function () {
  108054. var animations = this._gltf.animations;
  108055. if (!animations) {
  108056. return Promise.resolve();
  108057. }
  108058. var promises = new Array();
  108059. for (var index = 0; index < animations.length; index++) {
  108060. var animation = animations[index];
  108061. promises.push(this._loadAnimationAsync("#/animations/" + index, animation));
  108062. }
  108063. return Promise.all(promises).then(function () { });
  108064. };
  108065. GLTFLoader.prototype._loadAnimationAsync = function (context, animation) {
  108066. var _this = this;
  108067. var babylonAnimationGroup = new BABYLON.AnimationGroup(animation.name || "animation" + animation._index, this._babylonScene);
  108068. animation._babylonAnimationGroup = babylonAnimationGroup;
  108069. var promises = new Array();
  108070. _ArrayItem.Assign(animation.channels);
  108071. _ArrayItem.Assign(animation.samplers);
  108072. for (var _i = 0, _a = animation.channels; _i < _a.length; _i++) {
  108073. var channel = _a[_i];
  108074. promises.push(this._loadAnimationChannelAsync(context + "/channels/" + channel._index, context, animation, channel, babylonAnimationGroup));
  108075. }
  108076. return Promise.all(promises).then(function () {
  108077. babylonAnimationGroup.normalize(_this._parent._normalizeAnimationGroupsToBeginAtZero ? 0 : null);
  108078. });
  108079. };
  108080. GLTFLoader.prototype._loadAnimationChannelAsync = function (context, animationContext, animation, channel, babylonAnimationGroup) {
  108081. var _this = this;
  108082. var targetNode = GLTFLoader._GetProperty(context + "/target/node", this._gltf.nodes, channel.target.node);
  108083. // Ignore animations that have no animation targets.
  108084. if ((channel.target.path === "weights" /* WEIGHTS */ && !targetNode._numMorphTargets) ||
  108085. (channel.target.path !== "weights" /* WEIGHTS */ && !targetNode._babylonMesh)) {
  108086. return Promise.resolve();
  108087. }
  108088. // Ignore animations targeting TRS of skinned nodes.
  108089. // See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins (second implementation note)
  108090. if (targetNode.skin != undefined && channel.target.path !== "weights" /* WEIGHTS */) {
  108091. return Promise.resolve();
  108092. }
  108093. var sampler = GLTFLoader._GetProperty(context + "/sampler", animation.samplers, channel.sampler);
  108094. return this._loadAnimationSamplerAsync(animationContext + "/samplers/" + channel.sampler, sampler).then(function (data) {
  108095. var targetPath;
  108096. var animationType;
  108097. switch (channel.target.path) {
  108098. case "translation" /* TRANSLATION */: {
  108099. targetPath = "position";
  108100. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  108101. break;
  108102. }
  108103. case "rotation" /* ROTATION */: {
  108104. targetPath = "rotationQuaternion";
  108105. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  108106. break;
  108107. }
  108108. case "scale" /* SCALE */: {
  108109. targetPath = "scaling";
  108110. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  108111. break;
  108112. }
  108113. case "weights" /* WEIGHTS */: {
  108114. targetPath = "influence";
  108115. animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  108116. break;
  108117. }
  108118. default: {
  108119. throw new Error(context + ": Invalid target path (" + channel.target.path + ")");
  108120. }
  108121. }
  108122. var outputBufferOffset = 0;
  108123. var getNextOutputValue;
  108124. switch (targetPath) {
  108125. case "position": {
  108126. getNextOutputValue = function () {
  108127. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  108128. outputBufferOffset += 3;
  108129. return value;
  108130. };
  108131. break;
  108132. }
  108133. case "rotationQuaternion": {
  108134. getNextOutputValue = function () {
  108135. var value = BABYLON.Quaternion.FromArray(data.output, outputBufferOffset);
  108136. outputBufferOffset += 4;
  108137. return value;
  108138. };
  108139. break;
  108140. }
  108141. case "scaling": {
  108142. getNextOutputValue = function () {
  108143. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  108144. outputBufferOffset += 3;
  108145. return value;
  108146. };
  108147. break;
  108148. }
  108149. case "influence": {
  108150. getNextOutputValue = function () {
  108151. var value = new Array(targetNode._numMorphTargets);
  108152. for (var i = 0; i < targetNode._numMorphTargets; i++) {
  108153. value[i] = data.output[outputBufferOffset++];
  108154. }
  108155. return value;
  108156. };
  108157. break;
  108158. }
  108159. }
  108160. var getNextKey;
  108161. switch (data.interpolation) {
  108162. case "STEP" /* STEP */: {
  108163. getNextKey = function (frameIndex) { return ({
  108164. frame: data.input[frameIndex],
  108165. value: getNextOutputValue(),
  108166. interpolation: BABYLON.AnimationKeyInterpolation.STEP
  108167. }); };
  108168. break;
  108169. }
  108170. case "LINEAR" /* LINEAR */: {
  108171. getNextKey = function (frameIndex) { return ({
  108172. frame: data.input[frameIndex],
  108173. value: getNextOutputValue()
  108174. }); };
  108175. break;
  108176. }
  108177. case "CUBICSPLINE" /* CUBICSPLINE */: {
  108178. getNextKey = function (frameIndex) { return ({
  108179. frame: data.input[frameIndex],
  108180. inTangent: getNextOutputValue(),
  108181. value: getNextOutputValue(),
  108182. outTangent: getNextOutputValue()
  108183. }); };
  108184. break;
  108185. }
  108186. }
  108187. var keys = new Array(data.input.length);
  108188. for (var frameIndex = 0; frameIndex < data.input.length; frameIndex++) {
  108189. keys[frameIndex] = getNextKey(frameIndex);
  108190. }
  108191. if (targetPath === "influence") {
  108192. var _loop_1 = function (targetIndex) {
  108193. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  108194. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  108195. babylonAnimation.setKeys(keys.map(function (key) { return ({
  108196. frame: key.frame,
  108197. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  108198. value: key.value[targetIndex],
  108199. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  108200. }); }));
  108201. _this._forEachPrimitive(targetNode, function (babylonMesh) {
  108202. var morphTarget = babylonMesh.morphTargetManager.getTarget(targetIndex);
  108203. var babylonAnimationClone = babylonAnimation.clone();
  108204. morphTarget.animations.push(babylonAnimationClone);
  108205. babylonAnimationGroup.addTargetedAnimation(babylonAnimationClone, morphTarget);
  108206. });
  108207. };
  108208. for (var targetIndex = 0; targetIndex < targetNode._numMorphTargets; targetIndex++) {
  108209. _loop_1(targetIndex);
  108210. }
  108211. }
  108212. else {
  108213. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  108214. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  108215. babylonAnimation.setKeys(keys);
  108216. if (targetNode._babylonBones) {
  108217. var babylonAnimationTargets = [targetNode._babylonMesh].concat(targetNode._babylonBones);
  108218. for (var _i = 0, babylonAnimationTargets_1 = babylonAnimationTargets; _i < babylonAnimationTargets_1.length; _i++) {
  108219. var babylonAnimationTarget = babylonAnimationTargets_1[_i];
  108220. babylonAnimationTarget.animations.push(babylonAnimation);
  108221. }
  108222. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, babylonAnimationTargets);
  108223. }
  108224. else {
  108225. targetNode._babylonMesh.animations.push(babylonAnimation);
  108226. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, targetNode._babylonMesh);
  108227. }
  108228. }
  108229. });
  108230. };
  108231. GLTFLoader.prototype._loadAnimationSamplerAsync = function (context, sampler) {
  108232. if (sampler._data) {
  108233. return sampler._data;
  108234. }
  108235. var interpolation = sampler.interpolation || "LINEAR" /* LINEAR */;
  108236. switch (interpolation) {
  108237. case "STEP" /* STEP */:
  108238. case "LINEAR" /* LINEAR */:
  108239. case "CUBICSPLINE" /* CUBICSPLINE */: {
  108240. break;
  108241. }
  108242. default: {
  108243. throw new Error(context + ": Invalid interpolation (" + sampler.interpolation + ")");
  108244. }
  108245. }
  108246. var inputAccessor = GLTFLoader._GetProperty(context + "/input", this._gltf.accessors, sampler.input);
  108247. var outputAccessor = GLTFLoader._GetProperty(context + "/output", this._gltf.accessors, sampler.output);
  108248. sampler._data = Promise.all([
  108249. this._loadFloatAccessorAsync("#/accessors/" + inputAccessor._index, inputAccessor),
  108250. this._loadFloatAccessorAsync("#/accessors/" + outputAccessor._index, outputAccessor)
  108251. ]).then(function (_a) {
  108252. var inputData = _a[0], outputData = _a[1];
  108253. return {
  108254. input: inputData,
  108255. interpolation: interpolation,
  108256. output: outputData,
  108257. };
  108258. });
  108259. return sampler._data;
  108260. };
  108261. GLTFLoader.prototype._loadBufferAsync = function (context, buffer) {
  108262. if (buffer._data) {
  108263. return buffer._data;
  108264. }
  108265. if (!buffer.uri) {
  108266. throw new Error(context + ": Uri is missing");
  108267. }
  108268. buffer._data = this._loadUriAsync(context, buffer.uri);
  108269. return buffer._data;
  108270. };
  108271. GLTFLoader.prototype._loadBufferViewAsync = function (context, bufferView) {
  108272. if (bufferView._data) {
  108273. return bufferView._data;
  108274. }
  108275. var buffer = GLTFLoader._GetProperty(context + "/buffer", this._gltf.buffers, bufferView.buffer);
  108276. bufferView._data = this._loadBufferAsync("#/buffers/" + buffer._index, buffer).then(function (data) {
  108277. try {
  108278. return new Uint8Array(data.buffer, data.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  108279. }
  108280. catch (e) {
  108281. throw new Error(context + ": " + e.message);
  108282. }
  108283. });
  108284. return bufferView._data;
  108285. };
  108286. GLTFLoader.prototype._loadIndicesAccessorAsync = function (context, accessor) {
  108287. if (accessor.type !== "SCALAR" /* SCALAR */) {
  108288. throw new Error(context + ": Invalid type " + accessor.type);
  108289. }
  108290. if (accessor.componentType !== 5121 /* UNSIGNED_BYTE */ &&
  108291. accessor.componentType !== 5123 /* UNSIGNED_SHORT */ &&
  108292. accessor.componentType !== 5125 /* UNSIGNED_INT */) {
  108293. throw new Error(context + ": Invalid component type " + accessor.componentType);
  108294. }
  108295. if (accessor._data) {
  108296. return accessor._data;
  108297. }
  108298. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  108299. accessor._data = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (data) {
  108300. return GLTFLoader._GetTypedArray(context, accessor.componentType, data, accessor.byteOffset, accessor.count);
  108301. });
  108302. return accessor._data;
  108303. };
  108304. GLTFLoader.prototype._loadFloatAccessorAsync = function (context, accessor) {
  108305. // TODO: support normalized and stride
  108306. var _this = this;
  108307. if (accessor.componentType !== 5126 /* FLOAT */) {
  108308. throw new Error("Invalid component type " + accessor.componentType);
  108309. }
  108310. if (accessor._data) {
  108311. return accessor._data;
  108312. }
  108313. var numComponents = GLTFLoader._GetNumComponents(context, accessor.type);
  108314. var length = numComponents * accessor.count;
  108315. if (accessor.bufferView == undefined) {
  108316. accessor._data = Promise.resolve(new Float32Array(length));
  108317. }
  108318. else {
  108319. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  108320. accessor._data = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (data) {
  108321. return GLTFLoader._GetTypedArray(context, accessor.componentType, data, accessor.byteOffset, length);
  108322. });
  108323. }
  108324. if (accessor.sparse) {
  108325. var sparse_1 = accessor.sparse;
  108326. accessor._data = accessor._data.then(function (data) {
  108327. var indicesBufferView = GLTFLoader._GetProperty(context + "/sparse/indices/bufferView", _this._gltf.bufferViews, sparse_1.indices.bufferView);
  108328. var valuesBufferView = GLTFLoader._GetProperty(context + "/sparse/values/bufferView", _this._gltf.bufferViews, sparse_1.values.bufferView);
  108329. return Promise.all([
  108330. _this._loadBufferViewAsync("#/bufferViews/" + indicesBufferView._index, indicesBufferView),
  108331. _this._loadBufferViewAsync("#/bufferViews/" + valuesBufferView._index, valuesBufferView)
  108332. ]).then(function (_a) {
  108333. var indicesData = _a[0], valuesData = _a[1];
  108334. var indices = GLTFLoader._GetTypedArray(context + "/sparse/indices", sparse_1.indices.componentType, indicesData, sparse_1.indices.byteOffset, sparse_1.count);
  108335. var values = GLTFLoader._GetTypedArray(context + "/sparse/values", accessor.componentType, valuesData, sparse_1.values.byteOffset, numComponents * sparse_1.count);
  108336. var valuesIndex = 0;
  108337. for (var indicesIndex = 0; indicesIndex < indices.length; indicesIndex++) {
  108338. var dataIndex = indices[indicesIndex] * numComponents;
  108339. for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  108340. data[dataIndex++] = values[valuesIndex++];
  108341. }
  108342. }
  108343. return data;
  108344. });
  108345. });
  108346. }
  108347. return accessor._data;
  108348. };
  108349. GLTFLoader.prototype._loadVertexBufferViewAsync = function (context, bufferView, kind) {
  108350. var _this = this;
  108351. if (bufferView._babylonBuffer) {
  108352. return bufferView._babylonBuffer;
  108353. }
  108354. bufferView._babylonBuffer = this._loadBufferViewAsync(context, bufferView).then(function (data) {
  108355. return new BABYLON.Buffer(_this._babylonScene.getEngine(), data, false);
  108356. });
  108357. return bufferView._babylonBuffer;
  108358. };
  108359. GLTFLoader.prototype._loadVertexAccessorAsync = function (context, accessor, kind) {
  108360. var _this = this;
  108361. if (accessor._babylonVertexBuffer) {
  108362. return accessor._babylonVertexBuffer;
  108363. }
  108364. if (accessor.sparse) {
  108365. accessor._babylonVertexBuffer = this._loadFloatAccessorAsync(context, accessor).then(function (data) {
  108366. return new BABYLON.VertexBuffer(_this._babylonScene.getEngine(), data, kind, false);
  108367. });
  108368. }
  108369. else {
  108370. var bufferView_1 = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  108371. accessor._babylonVertexBuffer = this._loadVertexBufferViewAsync("#/bufferViews/" + bufferView_1._index, bufferView_1, kind).then(function (buffer) {
  108372. var size = GLTFLoader._GetNumComponents(context, accessor.type);
  108373. return new BABYLON.VertexBuffer(_this._babylonScene.getEngine(), buffer, kind, false, false, bufferView_1.byteStride, false, accessor.byteOffset, size, accessor.componentType, accessor.normalized, true);
  108374. });
  108375. }
  108376. return accessor._babylonVertexBuffer;
  108377. };
  108378. GLTFLoader.prototype._getDefaultMaterial = function (drawMode) {
  108379. var babylonMaterial = this._defaultBabylonMaterials[drawMode];
  108380. if (!babylonMaterial) {
  108381. babylonMaterial = this._createMaterial("__gltf_default", drawMode);
  108382. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  108383. babylonMaterial.metallic = 1;
  108384. babylonMaterial.roughness = 1;
  108385. this._parent.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  108386. }
  108387. return babylonMaterial;
  108388. };
  108389. GLTFLoader.prototype._loadMaterialMetallicRoughnessPropertiesAsync = function (context, material, babylonMaterial) {
  108390. var promises = new Array();
  108391. // Ensure metallic workflow
  108392. babylonMaterial.metallic = 1;
  108393. babylonMaterial.roughness = 1;
  108394. var properties = material.pbrMetallicRoughness;
  108395. if (properties) {
  108396. if (properties.baseColorFactor) {
  108397. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.baseColorFactor);
  108398. babylonMaterial.alpha = properties.baseColorFactor[3];
  108399. }
  108400. else {
  108401. babylonMaterial.albedoColor = BABYLON.Color3.White();
  108402. }
  108403. babylonMaterial.metallic = properties.metallicFactor == undefined ? 1 : properties.metallicFactor;
  108404. babylonMaterial.roughness = properties.roughnessFactor == undefined ? 1 : properties.roughnessFactor;
  108405. if (properties.baseColorTexture) {
  108406. promises.push(this._loadTextureAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  108407. babylonMaterial.albedoTexture = texture;
  108408. }));
  108409. }
  108410. if (properties.metallicRoughnessTexture) {
  108411. promises.push(this._loadTextureAsync(context + "/metallicRoughnessTexture", properties.metallicRoughnessTexture, function (texture) {
  108412. babylonMaterial.metallicTexture = texture;
  108413. }));
  108414. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  108415. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  108416. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  108417. }
  108418. }
  108419. this._loadMaterialAlphaProperties(context, material, babylonMaterial);
  108420. return Promise.all(promises).then(function () { });
  108421. };
  108422. GLTFLoader.prototype._loadMaterialAsync = function (context, material, mesh, babylonMesh, babylonDrawMode, assign) {
  108423. var promise = GLTF2.GLTFLoaderExtension._LoadMaterialAsync(this, context, material, mesh, babylonMesh, babylonDrawMode, assign);
  108424. if (promise) {
  108425. return promise;
  108426. }
  108427. material._babylonData = material._babylonData || {};
  108428. var babylonData = material._babylonData[babylonDrawMode];
  108429. if (!babylonData) {
  108430. var promises = new Array();
  108431. this._parent._logOpen(context + " " + (material.name || ""));
  108432. var name_4 = material.name || "material_" + material._index;
  108433. var babylonMaterial = this._createMaterial(name_4, babylonDrawMode);
  108434. promises.push(this._loadMaterialBasePropertiesAsync(context, material, babylonMaterial));
  108435. promises.push(this._loadMaterialMetallicRoughnessPropertiesAsync(context, material, babylonMaterial));
  108436. this._parent.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  108437. babylonData = {
  108438. material: babylonMaterial,
  108439. meshes: [],
  108440. loaded: Promise.all(promises).then(function () { })
  108441. };
  108442. material._babylonData[babylonDrawMode] = babylonData;
  108443. this._parent._logClose();
  108444. }
  108445. babylonData.meshes.push(babylonMesh);
  108446. assign(babylonData.material);
  108447. return babylonData.loaded;
  108448. };
  108449. GLTFLoader.prototype._createMaterial = function (name, drawMode) {
  108450. var babylonMaterial = new BABYLON.PBRMaterial(name, this._babylonScene);
  108451. babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation;
  108452. babylonMaterial.fillMode = drawMode;
  108453. babylonMaterial.enableSpecularAntiAliasing = true;
  108454. babylonMaterial.useRadianceOverAlpha = !this._parent.transparencyAsCoverage;
  108455. babylonMaterial.useSpecularOverAlpha = !this._parent.transparencyAsCoverage;
  108456. return babylonMaterial;
  108457. };
  108458. GLTFLoader.prototype._loadMaterialBasePropertiesAsync = function (context, material, babylonMaterial) {
  108459. var promises = new Array();
  108460. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  108461. if (material.doubleSided) {
  108462. babylonMaterial.backFaceCulling = false;
  108463. babylonMaterial.twoSidedLighting = true;
  108464. }
  108465. if (material.normalTexture) {
  108466. promises.push(this._loadTextureAsync(context + "/normalTexture", material.normalTexture, function (texture) {
  108467. babylonMaterial.bumpTexture = texture;
  108468. }));
  108469. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  108470. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  108471. if (material.normalTexture.scale != undefined) {
  108472. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  108473. }
  108474. }
  108475. if (material.occlusionTexture) {
  108476. promises.push(this._loadTextureAsync(context + "/occlusionTexture", material.occlusionTexture, function (texture) {
  108477. babylonMaterial.ambientTexture = texture;
  108478. }));
  108479. babylonMaterial.useAmbientInGrayScale = true;
  108480. if (material.occlusionTexture.strength != undefined) {
  108481. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  108482. }
  108483. }
  108484. if (material.emissiveTexture) {
  108485. promises.push(this._loadTextureAsync(context + "/emissiveTexture", material.emissiveTexture, function (texture) {
  108486. babylonMaterial.emissiveTexture = texture;
  108487. }));
  108488. }
  108489. return Promise.all(promises).then(function () { });
  108490. };
  108491. GLTFLoader.prototype._loadMaterialAlphaProperties = function (context, material, babylonMaterial) {
  108492. var alphaMode = material.alphaMode || "OPAQUE" /* OPAQUE */;
  108493. switch (alphaMode) {
  108494. case "OPAQUE" /* OPAQUE */: {
  108495. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  108496. break;
  108497. }
  108498. case "MASK" /* MASK */: {
  108499. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  108500. babylonMaterial.alphaCutOff = (material.alphaCutoff == undefined ? 0.5 : material.alphaCutoff);
  108501. if (babylonMaterial.albedoTexture) {
  108502. babylonMaterial.albedoTexture.hasAlpha = true;
  108503. }
  108504. break;
  108505. }
  108506. case "BLEND" /* BLEND */: {
  108507. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND;
  108508. if (babylonMaterial.albedoTexture) {
  108509. babylonMaterial.albedoTexture.hasAlpha = true;
  108510. babylonMaterial.useAlphaFromAlbedoTexture = true;
  108511. }
  108512. break;
  108513. }
  108514. default: {
  108515. throw new Error(context + ": Invalid alpha mode (" + material.alphaMode + ")");
  108516. }
  108517. }
  108518. };
  108519. GLTFLoader.prototype._loadTextureAsync = function (context, textureInfo, assign) {
  108520. var _this = this;
  108521. var promise = GLTF2.GLTFLoaderExtension._LoadTextureAsync(this, context, textureInfo, assign);
  108522. if (promise) {
  108523. return promise;
  108524. }
  108525. this._parent._logOpen("" + context);
  108526. var texture = GLTFLoader._GetProperty(context + "/index", this._gltf.textures, textureInfo.index);
  108527. context = "#/textures/" + textureInfo.index;
  108528. var promises = new Array();
  108529. this._parent._logOpen(context + " " + (texture.name || ""));
  108530. var sampler = (texture.sampler == undefined ? this._defaultSampler : GLTFLoader._GetProperty(context + "/sampler", this._gltf.samplers, texture.sampler));
  108531. var samplerData = this._loadSampler("#/samplers/" + sampler._index, sampler);
  108532. var deferred = new BABYLON.Deferred();
  108533. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, samplerData.noMipMaps, false, samplerData.samplingMode, function () {
  108534. if (!_this._disposed) {
  108535. deferred.resolve();
  108536. }
  108537. }, function (message, exception) {
  108538. if (!_this._disposed) {
  108539. deferred.reject(new Error(context + ": " + ((exception && exception.message) ? exception.message : message || "Failed to load texture")));
  108540. }
  108541. });
  108542. promises.push(deferred.promise);
  108543. babylonTexture.name = texture.name || "texture" + texture._index;
  108544. babylonTexture.wrapU = samplerData.wrapU;
  108545. babylonTexture.wrapV = samplerData.wrapV;
  108546. babylonTexture.coordinatesIndex = textureInfo.texCoord || 0;
  108547. var image = GLTFLoader._GetProperty(context + "/source", this._gltf.images, texture.source);
  108548. promises.push(this._loadImageAsync("#/images/" + image._index, image).then(function (blob) {
  108549. var dataUrl = "data:" + _this._rootUrl + (image.uri || "image" + image._index);
  108550. babylonTexture.updateURL(dataUrl, blob);
  108551. }));
  108552. assign(babylonTexture);
  108553. this._parent.onTextureLoadedObservable.notifyObservers(babylonTexture);
  108554. this._parent._logClose();
  108555. this._parent._logClose();
  108556. return Promise.all(promises).then(function () { });
  108557. };
  108558. GLTFLoader.prototype._loadSampler = function (context, sampler) {
  108559. if (!sampler._data) {
  108560. sampler._data = {
  108561. noMipMaps: (sampler.minFilter === 9728 /* NEAREST */ || sampler.minFilter === 9729 /* LINEAR */),
  108562. samplingMode: GLTFLoader._GetTextureSamplingMode(context, sampler.magFilter, sampler.minFilter),
  108563. wrapU: GLTFLoader._GetTextureWrapMode(context, sampler.wrapS),
  108564. wrapV: GLTFLoader._GetTextureWrapMode(context, sampler.wrapT)
  108565. };
  108566. }
  108567. ;
  108568. return sampler._data;
  108569. };
  108570. GLTFLoader.prototype._loadImageAsync = function (context, image) {
  108571. if (!image._blob) {
  108572. this._parent._logOpen(context + " " + (image.name || ""));
  108573. var promise = void 0;
  108574. if (image.uri) {
  108575. promise = this._loadUriAsync(context, image.uri);
  108576. }
  108577. else {
  108578. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, image.bufferView);
  108579. promise = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView);
  108580. }
  108581. image._blob = promise.then(function (data) {
  108582. return new Blob([data], { type: image.mimeType });
  108583. });
  108584. this._parent._logClose();
  108585. }
  108586. return image._blob;
  108587. };
  108588. GLTFLoader.prototype._loadUriAsync = function (context, uri) {
  108589. var _this = this;
  108590. var promise = GLTF2.GLTFLoaderExtension._LoadUriAsync(this, context, uri);
  108591. if (promise) {
  108592. return promise;
  108593. }
  108594. if (!GLTFLoader._ValidateUri(uri)) {
  108595. throw new Error(context + ": Uri '" + uri + "' is invalid");
  108596. }
  108597. if (BABYLON.Tools.IsBase64(uri)) {
  108598. var data = new Uint8Array(BABYLON.Tools.DecodeBase64(uri));
  108599. this._parent._log("Decoded " + uri.substr(0, 64) + "... (" + data.length + " bytes)");
  108600. return Promise.resolve(data);
  108601. }
  108602. this._parent._log("Loading " + uri);
  108603. return this._parent.preprocessUrlAsync(this._rootUrl + uri).then(function (url) {
  108604. return new Promise(function (resolve, reject) {
  108605. if (!_this._disposed) {
  108606. var request_1 = BABYLON.Tools.LoadFile(url, function (fileData) {
  108607. if (!_this._disposed) {
  108608. var data = new Uint8Array(fileData);
  108609. _this._parent._log("Loaded " + uri + " (" + data.length + " bytes)");
  108610. resolve(data);
  108611. }
  108612. }, function (event) {
  108613. if (!_this._disposed) {
  108614. if (request_1) {
  108615. request_1._lengthComputable = event.lengthComputable;
  108616. request_1._loaded = event.loaded;
  108617. request_1._total = event.total;
  108618. }
  108619. if (_this._state === BABYLON.GLTFLoaderState.LOADING) {
  108620. try {
  108621. _this._onProgress();
  108622. }
  108623. catch (e) {
  108624. reject(e);
  108625. }
  108626. }
  108627. }
  108628. }, _this._babylonScene.database, true, function (request, exception) {
  108629. if (!_this._disposed) {
  108630. reject(new BABYLON.LoadFileError(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""), request));
  108631. }
  108632. });
  108633. _this._requests.push(request_1);
  108634. }
  108635. });
  108636. });
  108637. };
  108638. GLTFLoader.prototype._onProgress = function () {
  108639. if (!this._progressCallback) {
  108640. return;
  108641. }
  108642. var lengthComputable = true;
  108643. var loaded = 0;
  108644. var total = 0;
  108645. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  108646. var request = _a[_i];
  108647. if (request._lengthComputable === undefined || request._loaded === undefined || request._total === undefined) {
  108648. return;
  108649. }
  108650. lengthComputable = lengthComputable && request._lengthComputable;
  108651. loaded += request._loaded;
  108652. total += request._total;
  108653. }
  108654. this._progressCallback(new BABYLON.SceneLoaderProgressEvent(lengthComputable, loaded, lengthComputable ? total : 0));
  108655. };
  108656. GLTFLoader._GetProperty = function (context, array, index) {
  108657. if (!array || index == undefined || !array[index]) {
  108658. throw new Error(context + ": Failed to find index (" + index + ")");
  108659. }
  108660. return array[index];
  108661. };
  108662. GLTFLoader._GetTextureWrapMode = function (context, mode) {
  108663. // Set defaults if undefined
  108664. mode = mode == undefined ? 10497 /* REPEAT */ : mode;
  108665. switch (mode) {
  108666. case 33071 /* CLAMP_TO_EDGE */: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  108667. case 33648 /* MIRRORED_REPEAT */: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  108668. case 10497 /* REPEAT */: return BABYLON.Texture.WRAP_ADDRESSMODE;
  108669. default:
  108670. BABYLON.Tools.Warn(context + ": Invalid texture wrap mode (" + mode + ")");
  108671. return BABYLON.Texture.WRAP_ADDRESSMODE;
  108672. }
  108673. };
  108674. GLTFLoader._GetTextureSamplingMode = function (context, magFilter, minFilter) {
  108675. // Set defaults if undefined
  108676. magFilter = magFilter == undefined ? 9729 /* LINEAR */ : magFilter;
  108677. minFilter = minFilter == undefined ? 9987 /* LINEAR_MIPMAP_LINEAR */ : minFilter;
  108678. if (magFilter === 9729 /* LINEAR */) {
  108679. switch (minFilter) {
  108680. case 9728 /* NEAREST */: return BABYLON.Texture.LINEAR_NEAREST;
  108681. case 9729 /* LINEAR */: return BABYLON.Texture.LINEAR_LINEAR;
  108682. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  108683. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  108684. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  108685. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  108686. default:
  108687. BABYLON.Tools.Warn(context + ": Invalid texture minification filter (" + minFilter + ")");
  108688. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  108689. }
  108690. }
  108691. else {
  108692. if (magFilter !== 9728 /* NEAREST */) {
  108693. BABYLON.Tools.Warn(context + ": Invalid texture magnification filter (" + magFilter + ")");
  108694. }
  108695. switch (minFilter) {
  108696. case 9728 /* NEAREST */: return BABYLON.Texture.NEAREST_NEAREST;
  108697. case 9729 /* LINEAR */: return BABYLON.Texture.NEAREST_LINEAR;
  108698. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  108699. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  108700. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  108701. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  108702. default:
  108703. BABYLON.Tools.Warn(context + ": Invalid texture minification filter (" + minFilter + ")");
  108704. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  108705. }
  108706. }
  108707. };
  108708. GLTFLoader._GetTypedArray = function (context, componentType, bufferView, byteOffset, length) {
  108709. var buffer = bufferView.buffer;
  108710. byteOffset = bufferView.byteOffset + (byteOffset || 0);
  108711. try {
  108712. switch (componentType) {
  108713. case 5120 /* BYTE */: return new Int8Array(buffer, byteOffset, length);
  108714. case 5121 /* UNSIGNED_BYTE */: return new Uint8Array(buffer, byteOffset, length);
  108715. case 5122 /* SHORT */: return new Int16Array(buffer, byteOffset, length);
  108716. case 5123 /* UNSIGNED_SHORT */: return new Uint16Array(buffer, byteOffset, length);
  108717. case 5125 /* UNSIGNED_INT */: return new Uint32Array(buffer, byteOffset, length);
  108718. case 5126 /* FLOAT */: return new Float32Array(buffer, byteOffset, length);
  108719. default: throw new Error("Invalid component type " + componentType);
  108720. }
  108721. }
  108722. catch (e) {
  108723. throw new Error(context + ": " + e);
  108724. }
  108725. };
  108726. GLTFLoader._GetNumComponents = function (context, type) {
  108727. switch (type) {
  108728. case "SCALAR": return 1;
  108729. case "VEC2": return 2;
  108730. case "VEC3": return 3;
  108731. case "VEC4": return 4;
  108732. case "MAT2": return 4;
  108733. case "MAT3": return 9;
  108734. case "MAT4": return 16;
  108735. }
  108736. throw new Error(context + ": Invalid type (" + type + ")");
  108737. };
  108738. GLTFLoader._ValidateUri = function (uri) {
  108739. return (BABYLON.Tools.IsBase64(uri) || uri.indexOf("..") === -1);
  108740. };
  108741. GLTFLoader._GetDrawMode = function (context, mode) {
  108742. if (mode == undefined) {
  108743. mode = 4 /* TRIANGLES */;
  108744. }
  108745. switch (mode) {
  108746. case 0 /* POINTS */: return BABYLON.Material.PointListDrawMode;
  108747. case 1 /* LINES */: return BABYLON.Material.LineListDrawMode;
  108748. case 2 /* LINE_LOOP */: return BABYLON.Material.LineLoopDrawMode;
  108749. case 3 /* LINE_STRIP */: return BABYLON.Material.LineStripDrawMode;
  108750. case 4 /* TRIANGLES */: return BABYLON.Material.TriangleFillMode;
  108751. case 5 /* TRIANGLE_STRIP */: return BABYLON.Material.TriangleStripDrawMode;
  108752. case 6 /* TRIANGLE_FAN */: return BABYLON.Material.TriangleFanDrawMode;
  108753. }
  108754. throw new Error(context + ": Invalid mesh primitive mode (" + mode + ")");
  108755. };
  108756. GLTFLoader.prototype._compileMaterialsAsync = function () {
  108757. var _this = this;
  108758. this._parent._startPerformanceCounter("Compile materials");
  108759. var promises = new Array();
  108760. if (this._gltf.materials) {
  108761. for (var _i = 0, _a = this._gltf.materials; _i < _a.length; _i++) {
  108762. var material = _a[_i];
  108763. if (material._babylonData) {
  108764. for (var babylonDrawMode in material._babylonData) {
  108765. var babylonData = material._babylonData[babylonDrawMode];
  108766. for (var _b = 0, _c = babylonData.meshes; _b < _c.length; _b++) {
  108767. var babylonMesh = _c[_b];
  108768. // Ensure nonUniformScaling is set if necessary.
  108769. babylonMesh.computeWorldMatrix(true);
  108770. var babylonMaterial = babylonData.material;
  108771. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh));
  108772. if (this._parent.useClipPlane) {
  108773. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh, { clipPlane: true }));
  108774. }
  108775. }
  108776. }
  108777. }
  108778. }
  108779. }
  108780. return Promise.all(promises).then(function () {
  108781. _this._parent._endPerformanceCounter("Compile materials");
  108782. });
  108783. };
  108784. GLTFLoader.prototype._compileShadowGeneratorsAsync = function () {
  108785. var _this = this;
  108786. this._parent._startPerformanceCounter("Compile shadow generators");
  108787. var promises = new Array();
  108788. var lights = this._babylonScene.lights;
  108789. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  108790. var light = lights_1[_i];
  108791. var generator = light.getShadowGenerator();
  108792. if (generator) {
  108793. promises.push(generator.forceCompilationAsync());
  108794. }
  108795. }
  108796. return Promise.all(promises).then(function () {
  108797. _this._parent._endPerformanceCounter("Compile shadow generators");
  108798. });
  108799. };
  108800. GLTFLoader.prototype._applyExtensions = function (actionAsync) {
  108801. for (var _i = 0, _a = GLTFLoader._ExtensionNames; _i < _a.length; _i++) {
  108802. var name_5 = _a[_i];
  108803. var extension = this._extensions[name_5];
  108804. if (extension.enabled) {
  108805. var promise = actionAsync(extension);
  108806. if (promise) {
  108807. return promise;
  108808. }
  108809. }
  108810. }
  108811. return null;
  108812. };
  108813. GLTFLoader._ExtensionNames = new Array();
  108814. GLTFLoader._ExtensionFactories = {};
  108815. return GLTFLoader;
  108816. }());
  108817. GLTF2.GLTFLoader = GLTFLoader;
  108818. BABYLON.GLTFFileLoader._CreateGLTFLoaderV2 = function (parent) { return new GLTFLoader(parent); };
  108819. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  108820. })(BABYLON || (BABYLON = {}));
  108821. //# sourceMappingURL=babylon.glTFLoader.js.map
  108822. var BABYLON;
  108823. (function (BABYLON) {
  108824. var GLTF2;
  108825. (function (GLTF2) {
  108826. /**
  108827. * Abstract class that can be implemented to extend existing glTF loader behavior.
  108828. */
  108829. var GLTFLoaderExtension = /** @class */ (function () {
  108830. /**
  108831. * Creates new GLTFLoaderExtension
  108832. * @param loader defines the GLTFLoader to use
  108833. */
  108834. function GLTFLoaderExtension(loader) {
  108835. /**
  108836. * Gets or sets a boolean indicating if the extension is enabled
  108837. */
  108838. this.enabled = true;
  108839. this._loader = loader;
  108840. }
  108841. /**
  108842. * Release all resources
  108843. */
  108844. GLTFLoaderExtension.prototype.dispose = function () {
  108845. delete this._loader;
  108846. };
  108847. // #region Overridable Methods
  108848. /**
  108849. * Override this method to modify the default behavior for loading scenes.
  108850. * @hidden
  108851. */
  108852. GLTFLoaderExtension.prototype._loadSceneAsync = function (context, node) { return null; };
  108853. /**
  108854. * Override this method to modify the default behavior for loading nodes.
  108855. * @hidden
  108856. */
  108857. GLTFLoaderExtension.prototype._loadNodeAsync = function (context, node) { return null; };
  108858. /**
  108859. * Override this method to modify the default behavior for loading mesh primitive vertex data.
  108860. * @hidden
  108861. */
  108862. GLTFLoaderExtension.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) { return null; };
  108863. /**
  108864. * Override this method to modify the default behavior for loading materials.
  108865. * @hidden
  108866. */
  108867. GLTFLoaderExtension.prototype._loadMaterialAsync = function (context, material, mesh, babylonMesh, babylonDrawMode, assign) { return null; };
  108868. /**
  108869. * Override this method to modify the default behavior for loading textures.
  108870. * @hidden
  108871. */
  108872. GLTFLoaderExtension.prototype._loadTextureAsync = function (context, textureInfo, assign) { return null; };
  108873. /**
  108874. * Override this method to modify the default behavior for loading uris.
  108875. * @hidden
  108876. */
  108877. GLTFLoaderExtension.prototype._loadUriAsync = function (context, uri) { return null; };
  108878. // #endregion
  108879. /**
  108880. * Helper method called by a loader extension to load an glTF extension.
  108881. * @hidden
  108882. */
  108883. GLTFLoaderExtension.prototype._loadExtensionAsync = function (context, property, actionAsync) {
  108884. if (!property.extensions) {
  108885. return null;
  108886. }
  108887. var extensions = property.extensions;
  108888. var extension = extensions[this.name];
  108889. if (!extension) {
  108890. return null;
  108891. }
  108892. // Clear out the extension before executing the action to avoid infinite recursion.
  108893. delete extensions[this.name];
  108894. try {
  108895. return actionAsync(context + "/extensions/" + this.name, extension);
  108896. }
  108897. finally {
  108898. // Restore the extension after executing the action.
  108899. extensions[this.name] = extension;
  108900. }
  108901. };
  108902. /**
  108903. * Helper method called by the loader to allow extensions to override loading scenes.
  108904. * @hidden
  108905. */
  108906. GLTFLoaderExtension.prototype._loadExtrasValueAsync = function (context, property, actionAsync) {
  108907. if (!property.extras) {
  108908. return null;
  108909. }
  108910. var extras = property.extras;
  108911. var value = extras[this.name];
  108912. if (value === undefined) {
  108913. return null;
  108914. }
  108915. // Clear out the extras value before executing the action to avoid infinite recursion.
  108916. delete extras[this.name];
  108917. try {
  108918. return actionAsync(context + "/extras/" + this.name, value);
  108919. }
  108920. finally {
  108921. // Restore the extras value after executing the action.
  108922. extras[this.name] = value;
  108923. }
  108924. };
  108925. /**
  108926. * Helper method called by the loader to allow extensions to override loading scenes.
  108927. * @hidden
  108928. */
  108929. GLTFLoaderExtension._LoadSceneAsync = function (loader, context, scene) {
  108930. return loader._applyExtensions(function (extension) { return extension._loadSceneAsync(context, scene); });
  108931. };
  108932. /**
  108933. * Helper method called by the loader to allow extensions to override loading nodes.
  108934. * @hidden
  108935. */
  108936. GLTFLoaderExtension._LoadNodeAsync = function (loader, context, node) {
  108937. return loader._applyExtensions(function (extension) { return extension._loadNodeAsync(context, node); });
  108938. };
  108939. /**
  108940. * Helper method called by the loader to allow extensions to override loading mesh primitive vertex data.
  108941. * @hidden
  108942. */
  108943. GLTFLoaderExtension._LoadVertexDataAsync = function (loader, context, primitive, babylonMesh) {
  108944. return loader._applyExtensions(function (extension) { return extension._loadVertexDataAsync(context, primitive, babylonMesh); });
  108945. };
  108946. /**
  108947. * Helper method called by the loader to allow extensions to override loading materials.
  108948. * @hidden
  108949. */
  108950. GLTFLoaderExtension._LoadMaterialAsync = function (loader, context, material, mesh, babylonMesh, babylonDrawMode, assign) {
  108951. return loader._applyExtensions(function (extension) { return extension._loadMaterialAsync(context, material, mesh, babylonMesh, babylonDrawMode, assign); });
  108952. };
  108953. /**
  108954. * Helper method called by the loader to allow extensions to override loading textures.
  108955. * @hidden
  108956. */
  108957. GLTFLoaderExtension._LoadTextureAsync = function (loader, context, textureInfo, assign) {
  108958. return loader._applyExtensions(function (extension) { return extension._loadTextureAsync(context, textureInfo, assign); });
  108959. };
  108960. /**
  108961. * Helper method called by the loader to allow extensions to override loading uris.
  108962. * @hidden
  108963. */
  108964. GLTFLoaderExtension._LoadUriAsync = function (loader, context, uri) {
  108965. return loader._applyExtensions(function (extension) { return extension._loadUriAsync(context, uri); });
  108966. };
  108967. return GLTFLoaderExtension;
  108968. }());
  108969. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  108970. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  108971. })(BABYLON || (BABYLON = {}));
  108972. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  108973. var BABYLON;
  108974. (function (BABYLON) {
  108975. var GLTF2;
  108976. (function (GLTF2) {
  108977. var Extensions;
  108978. (function (Extensions) {
  108979. var NAME = "MSFT_lod";
  108980. /**
  108981. * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/MSFT_lod)
  108982. */
  108983. var MSFT_lod = /** @class */ (function (_super) {
  108984. __extends(MSFT_lod, _super);
  108985. function MSFT_lod(loader) {
  108986. var _this = _super.call(this, loader) || this;
  108987. _this.name = NAME;
  108988. /**
  108989. * Maximum number of LODs to load, starting from the lowest LOD.
  108990. */
  108991. _this.maxLODsToLoad = Number.MAX_VALUE;
  108992. /**
  108993. * Observable raised when all node LODs of one level are loaded.
  108994. * The event data is the index of the loaded LOD starting from zero.
  108995. * Dispose the loader to cancel the loading of the next level of LODs.
  108996. */
  108997. _this.onNodeLODsLoadedObservable = new BABYLON.Observable();
  108998. /**
  108999. * Observable raised when all material LODs of one level are loaded.
  109000. * The event data is the index of the loaded LOD starting from zero.
  109001. * Dispose the loader to cancel the loading of the next level of LODs.
  109002. */
  109003. _this.onMaterialLODsLoadedObservable = new BABYLON.Observable();
  109004. _this._nodeIndexLOD = null;
  109005. _this._nodeSignalLODs = new Array();
  109006. _this._nodePromiseLODs = new Array();
  109007. _this._materialIndexLOD = null;
  109008. _this._materialSignalLODs = new Array();
  109009. _this._materialPromiseLODs = new Array();
  109010. _this._loader._readyPromise.then(function () {
  109011. var _loop_1 = function (indexLOD) {
  109012. var promise = Promise.all(_this._nodePromiseLODs[indexLOD]).then(function () {
  109013. if (indexLOD !== 0) {
  109014. _this._loader._parent._endPerformanceCounter("Node LOD " + indexLOD);
  109015. }
  109016. _this._loader._parent._log("Loaded node LOD " + indexLOD);
  109017. _this.onNodeLODsLoadedObservable.notifyObservers(indexLOD);
  109018. if (indexLOD !== _this._nodePromiseLODs.length - 1) {
  109019. _this._loader._parent._startPerformanceCounter("Node LOD " + (indexLOD + 1));
  109020. _this._nodeSignalLODs[indexLOD].resolve();
  109021. }
  109022. });
  109023. _this._loader._completePromises.push(promise);
  109024. };
  109025. for (var indexLOD = 0; indexLOD < _this._nodePromiseLODs.length; indexLOD++) {
  109026. _loop_1(indexLOD);
  109027. }
  109028. var _loop_2 = function (indexLOD) {
  109029. var promise = Promise.all(_this._materialPromiseLODs[indexLOD]).then(function () {
  109030. if (indexLOD !== 0) {
  109031. _this._loader._parent._endPerformanceCounter("Material LOD " + indexLOD);
  109032. }
  109033. _this._loader._parent._log("Loaded material LOD " + indexLOD);
  109034. _this.onMaterialLODsLoadedObservable.notifyObservers(indexLOD);
  109035. if (indexLOD !== _this._materialPromiseLODs.length - 1) {
  109036. _this._loader._parent._startPerformanceCounter("Material LOD " + (indexLOD + 1));
  109037. _this._materialSignalLODs[indexLOD].resolve();
  109038. }
  109039. });
  109040. _this._loader._completePromises.push(promise);
  109041. };
  109042. for (var indexLOD = 0; indexLOD < _this._materialPromiseLODs.length; indexLOD++) {
  109043. _loop_2(indexLOD);
  109044. }
  109045. });
  109046. return _this;
  109047. }
  109048. MSFT_lod.prototype.dispose = function () {
  109049. _super.prototype.dispose.call(this);
  109050. this._nodeIndexLOD = null;
  109051. this._nodeSignalLODs.length = 0;
  109052. this._nodePromiseLODs.length = 0;
  109053. this._materialIndexLOD = null;
  109054. this._materialSignalLODs.length = 0;
  109055. this._materialPromiseLODs.length = 0;
  109056. this.onMaterialLODsLoadedObservable.clear();
  109057. this.onNodeLODsLoadedObservable.clear();
  109058. };
  109059. MSFT_lod.prototype._loadNodeAsync = function (context, node) {
  109060. var _this = this;
  109061. return this._loadExtensionAsync(context, node, function (extensionContext, extension) {
  109062. var firstPromise;
  109063. var nodeLODs = _this._getLODs(extensionContext, node, _this._loader._gltf.nodes, extension.ids);
  109064. _this._loader._parent._logOpen("" + extensionContext);
  109065. var _loop_3 = function (indexLOD) {
  109066. var nodeLOD = nodeLODs[indexLOD];
  109067. if (indexLOD !== 0) {
  109068. _this._nodeIndexLOD = indexLOD;
  109069. _this._nodeSignalLODs[indexLOD] = _this._nodeSignalLODs[indexLOD] || new BABYLON.Deferred();
  109070. }
  109071. var promise = _this._loader._loadNodeAsync("#/nodes/" + nodeLOD._index, nodeLOD).then(function () {
  109072. if (indexLOD !== 0) {
  109073. var previousNodeLOD = nodeLODs[indexLOD - 1];
  109074. if (previousNodeLOD._babylonMesh) {
  109075. previousNodeLOD._babylonMesh.dispose(false, true);
  109076. delete previousNodeLOD._babylonMesh;
  109077. }
  109078. }
  109079. });
  109080. if (indexLOD === 0) {
  109081. firstPromise = promise;
  109082. }
  109083. else {
  109084. _this._nodeIndexLOD = null;
  109085. }
  109086. _this._nodePromiseLODs[indexLOD] = _this._nodePromiseLODs[indexLOD] || [];
  109087. _this._nodePromiseLODs[indexLOD].push(promise);
  109088. };
  109089. for (var indexLOD = 0; indexLOD < nodeLODs.length; indexLOD++) {
  109090. _loop_3(indexLOD);
  109091. }
  109092. _this._loader._parent._logClose();
  109093. return firstPromise;
  109094. });
  109095. };
  109096. MSFT_lod.prototype._loadMaterialAsync = function (context, material, mesh, babylonMesh, babylonDrawMode, assign) {
  109097. var _this = this;
  109098. // Don't load material LODs if already loading a node LOD.
  109099. if (this._nodeIndexLOD) {
  109100. return null;
  109101. }
  109102. return this._loadExtensionAsync(context, material, function (extensionContext, extension) {
  109103. var firstPromise;
  109104. var materialLODs = _this._getLODs(extensionContext, material, _this._loader._gltf.materials, extension.ids);
  109105. _this._loader._parent._logOpen("" + extensionContext);
  109106. var _loop_4 = function (indexLOD) {
  109107. var materialLOD = materialLODs[indexLOD];
  109108. if (indexLOD !== 0) {
  109109. _this._materialIndexLOD = indexLOD;
  109110. }
  109111. var promise = _this._loader._loadMaterialAsync("#/materials/" + materialLOD._index, materialLOD, mesh, babylonMesh, babylonDrawMode, indexLOD === 0 ? assign : function () { }).then(function () {
  109112. if (indexLOD !== 0) {
  109113. var babylonDataLOD = materialLOD._babylonData;
  109114. assign(babylonDataLOD[babylonDrawMode].material);
  109115. var previousBabylonDataLOD = materialLODs[indexLOD - 1]._babylonData;
  109116. if (previousBabylonDataLOD[babylonDrawMode]) {
  109117. previousBabylonDataLOD[babylonDrawMode].material.dispose();
  109118. delete previousBabylonDataLOD[babylonDrawMode];
  109119. }
  109120. }
  109121. });
  109122. if (indexLOD === 0) {
  109123. firstPromise = promise;
  109124. }
  109125. else {
  109126. _this._materialIndexLOD = null;
  109127. }
  109128. _this._materialPromiseLODs[indexLOD] = _this._materialPromiseLODs[indexLOD] || [];
  109129. _this._materialPromiseLODs[indexLOD].push(promise);
  109130. };
  109131. for (var indexLOD = 0; indexLOD < materialLODs.length; indexLOD++) {
  109132. _loop_4(indexLOD);
  109133. }
  109134. _this._loader._parent._logClose();
  109135. return firstPromise;
  109136. });
  109137. };
  109138. MSFT_lod.prototype._loadUriAsync = function (context, uri) {
  109139. var _this = this;
  109140. // Defer the loading of uris if loading a material or node LOD.
  109141. if (this._materialIndexLOD !== null) {
  109142. this._loader._parent._log("deferred");
  109143. var previousIndexLOD = this._materialIndexLOD - 1;
  109144. this._materialSignalLODs[previousIndexLOD] = this._materialSignalLODs[previousIndexLOD] || new BABYLON.Deferred();
  109145. return this._materialSignalLODs[previousIndexLOD].promise.then(function () {
  109146. return _this._loader._loadUriAsync(context, uri);
  109147. });
  109148. }
  109149. else if (this._nodeIndexLOD !== null) {
  109150. this._loader._parent._log("deferred");
  109151. var previousIndexLOD = this._nodeIndexLOD - 1;
  109152. this._nodeSignalLODs[previousIndexLOD] = this._nodeSignalLODs[previousIndexLOD] || new BABYLON.Deferred();
  109153. return this._nodeSignalLODs[this._nodeIndexLOD - 1].promise.then(function () {
  109154. return _this._loader._loadUriAsync(context, uri);
  109155. });
  109156. }
  109157. return null;
  109158. };
  109159. /**
  109160. * Gets an array of LOD properties from lowest to highest.
  109161. */
  109162. MSFT_lod.prototype._getLODs = function (context, property, array, ids) {
  109163. if (this.maxLODsToLoad <= 0) {
  109164. throw new Error("maxLODsToLoad must be greater than zero");
  109165. }
  109166. var properties = new Array();
  109167. for (var i = ids.length - 1; i >= 0; i--) {
  109168. properties.push(GLTF2.GLTFLoader._GetProperty(context + "/ids/" + ids[i], array, ids[i]));
  109169. if (properties.length === this.maxLODsToLoad) {
  109170. return properties;
  109171. }
  109172. }
  109173. properties.push(property);
  109174. return properties;
  109175. };
  109176. return MSFT_lod;
  109177. }(GLTF2.GLTFLoaderExtension));
  109178. Extensions.MSFT_lod = MSFT_lod;
  109179. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_lod(loader); });
  109180. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  109181. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  109182. })(BABYLON || (BABYLON = {}));
  109183. //# sourceMappingURL=MSFT_lod.js.map
  109184. var BABYLON;
  109185. (function (BABYLON) {
  109186. var GLTF2;
  109187. (function (GLTF2) {
  109188. var Extensions;
  109189. (function (Extensions) {
  109190. var NAME = "MSFT_minecraftMesh";
  109191. /** @hidden */
  109192. var MSFT_minecraftMesh = /** @class */ (function (_super) {
  109193. __extends(MSFT_minecraftMesh, _super);
  109194. function MSFT_minecraftMesh() {
  109195. var _this = _super !== null && _super.apply(this, arguments) || this;
  109196. _this.name = NAME;
  109197. return _this;
  109198. }
  109199. MSFT_minecraftMesh.prototype._loadMaterialAsync = function (context, material, mesh, babylonMesh, babylonDrawMode, assign) {
  109200. var _this = this;
  109201. return this._loadExtrasValueAsync(context, mesh, function (extensionContext, value) {
  109202. if (value) {
  109203. return _this._loader._loadMaterialAsync(context, material, mesh, babylonMesh, babylonDrawMode, function (babylonMaterial) {
  109204. if (babylonMaterial.needAlphaBlending()) {
  109205. babylonMaterial.forceDepthWrite = true;
  109206. babylonMaterial.separateCullingPass = true;
  109207. }
  109208. babylonMaterial.backFaceCulling = babylonMaterial.forceDepthWrite;
  109209. babylonMaterial.twoSidedLighting = true;
  109210. assign(babylonMaterial);
  109211. });
  109212. }
  109213. return null;
  109214. });
  109215. };
  109216. return MSFT_minecraftMesh;
  109217. }(GLTF2.GLTFLoaderExtension));
  109218. Extensions.MSFT_minecraftMesh = MSFT_minecraftMesh;
  109219. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_minecraftMesh(loader); });
  109220. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  109221. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  109222. })(BABYLON || (BABYLON = {}));
  109223. //# sourceMappingURL=MSFT_minecraftMesh.js.map
  109224. var BABYLON;
  109225. (function (BABYLON) {
  109226. var GLTF2;
  109227. (function (GLTF2) {
  109228. var Extensions;
  109229. (function (Extensions) {
  109230. var NAME = "MSFT_sRGBFactors";
  109231. /** @hidden */
  109232. var MSFT_sRGBFactors = /** @class */ (function (_super) {
  109233. __extends(MSFT_sRGBFactors, _super);
  109234. function MSFT_sRGBFactors() {
  109235. var _this = _super !== null && _super.apply(this, arguments) || this;
  109236. _this.name = NAME;
  109237. return _this;
  109238. }
  109239. MSFT_sRGBFactors.prototype._loadMaterialAsync = function (context, material, mesh, babylonMesh, babylonDrawMode, assign) {
  109240. var _this = this;
  109241. return this._loadExtrasValueAsync(context, material, function (extensionContext, value) {
  109242. if (value) {
  109243. return _this._loader._loadMaterialAsync(context, material, mesh, babylonMesh, babylonDrawMode, function (babylonMaterial) {
  109244. if (!babylonMaterial.albedoTexture) {
  109245. babylonMaterial.albedoColor.toLinearSpaceToRef(babylonMaterial.albedoColor);
  109246. }
  109247. if (!babylonMaterial.reflectivityTexture) {
  109248. babylonMaterial.reflectivityColor.toLinearSpaceToRef(babylonMaterial.reflectivityColor);
  109249. }
  109250. assign(babylonMaterial);
  109251. });
  109252. }
  109253. return null;
  109254. });
  109255. };
  109256. return MSFT_sRGBFactors;
  109257. }(GLTF2.GLTFLoaderExtension));
  109258. Extensions.MSFT_sRGBFactors = MSFT_sRGBFactors;
  109259. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_sRGBFactors(loader); });
  109260. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  109261. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  109262. })(BABYLON || (BABYLON = {}));
  109263. //# sourceMappingURL=MSFT_sRGBFactors.js.map
  109264. var BABYLON;
  109265. (function (BABYLON) {
  109266. var GLTF2;
  109267. (function (GLTF2) {
  109268. var Extensions;
  109269. (function (Extensions) {
  109270. var NAME = "KHR_draco_mesh_compression";
  109271. /**
  109272. * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression)
  109273. */
  109274. var KHR_draco_mesh_compression = /** @class */ (function (_super) {
  109275. __extends(KHR_draco_mesh_compression, _super);
  109276. function KHR_draco_mesh_compression(loader) {
  109277. var _this = _super.call(this, loader) || this;
  109278. _this.name = NAME;
  109279. _this._dracoCompression = null;
  109280. // Disable extension if decoder is not available.
  109281. if (!BABYLON.DracoCompression.DecoderAvailable) {
  109282. _this.enabled = false;
  109283. }
  109284. return _this;
  109285. }
  109286. KHR_draco_mesh_compression.prototype.dispose = function () {
  109287. if (this._dracoCompression) {
  109288. this._dracoCompression.dispose();
  109289. }
  109290. _super.prototype.dispose.call(this);
  109291. };
  109292. KHR_draco_mesh_compression.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  109293. var _this = this;
  109294. return this._loadExtensionAsync(context, primitive, function (extensionContext, extension) {
  109295. if (primitive.mode != undefined) {
  109296. if (primitive.mode !== 5 /* TRIANGLE_STRIP */ &&
  109297. primitive.mode !== 4 /* TRIANGLES */) {
  109298. throw new Error(context + ": Unsupported mode " + primitive.mode);
  109299. }
  109300. // TODO: handle triangle strips
  109301. if (primitive.mode === 5 /* TRIANGLE_STRIP */) {
  109302. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  109303. }
  109304. }
  109305. var attributes = {};
  109306. var loadAttribute = function (name, kind) {
  109307. var uniqueId = extension.attributes[name];
  109308. if (uniqueId == undefined) {
  109309. return;
  109310. }
  109311. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  109312. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  109313. babylonMesh._delayInfo.push(kind);
  109314. }
  109315. attributes[kind] = uniqueId;
  109316. };
  109317. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  109318. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  109319. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  109320. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  109321. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  109322. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  109323. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  109324. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind);
  109325. var bufferView = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._loader._gltf.bufferViews, extension.bufferView);
  109326. if (!bufferView._dracoBabylonGeometry) {
  109327. bufferView._dracoBabylonGeometry = _this._loader._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (data) {
  109328. if (!_this._dracoCompression) {
  109329. _this._dracoCompression = new BABYLON.DracoCompression();
  109330. }
  109331. return _this._dracoCompression.decodeMeshAsync(data, attributes).then(function (babylonVertexData) {
  109332. var babylonGeometry = new BABYLON.Geometry(babylonMesh.name, _this._loader._babylonScene);
  109333. babylonVertexData.applyToGeometry(babylonGeometry);
  109334. return babylonGeometry;
  109335. }).catch(function (error) {
  109336. throw new Error(context + ": " + error.message);
  109337. });
  109338. });
  109339. }
  109340. return bufferView._dracoBabylonGeometry;
  109341. });
  109342. };
  109343. return KHR_draco_mesh_compression;
  109344. }(GLTF2.GLTFLoaderExtension));
  109345. Extensions.KHR_draco_mesh_compression = KHR_draco_mesh_compression;
  109346. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_draco_mesh_compression(loader); });
  109347. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  109348. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  109349. })(BABYLON || (BABYLON = {}));
  109350. //# sourceMappingURL=KHR_draco_mesh_compression.js.map
  109351. var BABYLON;
  109352. (function (BABYLON) {
  109353. var GLTF2;
  109354. (function (GLTF2) {
  109355. var Extensions;
  109356. (function (Extensions) {
  109357. var NAME = "KHR_materials_pbrSpecularGlossiness";
  109358. /**
  109359. * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness)
  109360. */
  109361. var KHR_materials_pbrSpecularGlossiness = /** @class */ (function (_super) {
  109362. __extends(KHR_materials_pbrSpecularGlossiness, _super);
  109363. function KHR_materials_pbrSpecularGlossiness() {
  109364. var _this = _super !== null && _super.apply(this, arguments) || this;
  109365. _this.name = NAME;
  109366. return _this;
  109367. }
  109368. KHR_materials_pbrSpecularGlossiness.prototype._loadMaterialAsync = function (context, material, mesh, babylonMesh, babylonDrawMode, assign) {
  109369. var _this = this;
  109370. return this._loadExtensionAsync(context, material, function (extensionContext, extension) {
  109371. material._babylonData = material._babylonData || {};
  109372. var babylonData = material._babylonData[babylonDrawMode];
  109373. if (!babylonData) {
  109374. var promises = new Array();
  109375. var name_1 = material.name || "materialSG_" + material._index;
  109376. var babylonMaterial = _this._loader._createMaterial(name_1, babylonDrawMode);
  109377. promises.push(_this._loader._loadMaterialBasePropertiesAsync(context, material, babylonMaterial));
  109378. promises.push(_this._loadSpecularGlossinessPropertiesAsync(extensionContext, material, extension, babylonMaterial));
  109379. _this._loader._parent.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  109380. babylonData = {
  109381. material: babylonMaterial,
  109382. meshes: [],
  109383. loaded: Promise.all(promises).then(function () { })
  109384. };
  109385. material._babylonData[babylonDrawMode] = babylonData;
  109386. }
  109387. babylonData.meshes.push(babylonMesh);
  109388. assign(babylonData.material);
  109389. return babylonData.loaded;
  109390. });
  109391. };
  109392. KHR_materials_pbrSpecularGlossiness.prototype._loadSpecularGlossinessPropertiesAsync = function (context, material, properties, babylonMaterial) {
  109393. var promises = new Array();
  109394. if (properties.diffuseFactor) {
  109395. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.diffuseFactor);
  109396. babylonMaterial.alpha = properties.diffuseFactor[3];
  109397. }
  109398. else {
  109399. babylonMaterial.albedoColor = BABYLON.Color3.White();
  109400. }
  109401. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : BABYLON.Color3.White();
  109402. babylonMaterial.microSurface = properties.glossinessFactor == undefined ? 1 : properties.glossinessFactor;
  109403. if (properties.diffuseTexture) {
  109404. promises.push(this._loader._loadTextureAsync(context + "/diffuseTexture", properties.diffuseTexture, function (texture) {
  109405. babylonMaterial.albedoTexture = texture;
  109406. }));
  109407. }
  109408. if (properties.specularGlossinessTexture) {
  109409. promises.push(this._loader._loadTextureAsync(context + "/specularGlossinessTexture", properties.specularGlossinessTexture, function (texture) {
  109410. babylonMaterial.reflectivityTexture = texture;
  109411. }));
  109412. babylonMaterial.reflectivityTexture.hasAlpha = true;
  109413. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  109414. }
  109415. this._loader._loadMaterialAlphaProperties(context, material, babylonMaterial);
  109416. return Promise.all(promises).then(function () { });
  109417. };
  109418. return KHR_materials_pbrSpecularGlossiness;
  109419. }(GLTF2.GLTFLoaderExtension));
  109420. Extensions.KHR_materials_pbrSpecularGlossiness = KHR_materials_pbrSpecularGlossiness;
  109421. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_materials_pbrSpecularGlossiness(loader); });
  109422. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  109423. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  109424. })(BABYLON || (BABYLON = {}));
  109425. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  109426. var BABYLON;
  109427. (function (BABYLON) {
  109428. var GLTF2;
  109429. (function (GLTF2) {
  109430. var Extensions;
  109431. (function (Extensions) {
  109432. var NAME = "KHR_materials_unlit";
  109433. /**
  109434. * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_unlit)
  109435. */
  109436. var KHR_materials_unlit = /** @class */ (function (_super) {
  109437. __extends(KHR_materials_unlit, _super);
  109438. function KHR_materials_unlit() {
  109439. var _this = _super !== null && _super.apply(this, arguments) || this;
  109440. _this.name = NAME;
  109441. return _this;
  109442. }
  109443. KHR_materials_unlit.prototype._loadMaterialAsync = function (context, material, mesh, babylonMesh, babylonDrawMode, assign) {
  109444. var _this = this;
  109445. return this._loadExtensionAsync(context, material, function () {
  109446. material._babylonData = material._babylonData || {};
  109447. var babylonData = material._babylonData[babylonDrawMode];
  109448. if (!babylonData) {
  109449. var name_1 = material.name || "materialUnlit_" + material._index;
  109450. var babylonMaterial = _this._loader._createMaterial(name_1, babylonDrawMode);
  109451. babylonMaterial.unlit = true;
  109452. var promise = _this._loadUnlitPropertiesAsync(context, material, babylonMaterial);
  109453. _this._loader._parent.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  109454. babylonData = {
  109455. material: babylonMaterial,
  109456. meshes: [],
  109457. loaded: promise
  109458. };
  109459. material._babylonData[babylonDrawMode] = babylonData;
  109460. }
  109461. babylonData.meshes.push(babylonMesh);
  109462. assign(babylonData.material);
  109463. return babylonData.loaded;
  109464. });
  109465. };
  109466. KHR_materials_unlit.prototype._loadUnlitPropertiesAsync = function (context, material, babylonMaterial) {
  109467. var promises = new Array();
  109468. // Ensure metallic workflow
  109469. babylonMaterial.metallic = 1;
  109470. babylonMaterial.roughness = 1;
  109471. var properties = material.pbrMetallicRoughness;
  109472. if (properties) {
  109473. if (properties.baseColorFactor) {
  109474. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.baseColorFactor);
  109475. babylonMaterial.alpha = properties.baseColorFactor[3];
  109476. }
  109477. else {
  109478. babylonMaterial.albedoColor = BABYLON.Color3.White();
  109479. }
  109480. if (properties.baseColorTexture) {
  109481. promises.push(this._loader._loadTextureAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  109482. babylonMaterial.albedoTexture = texture;
  109483. }));
  109484. }
  109485. }
  109486. if (material.doubleSided) {
  109487. babylonMaterial.backFaceCulling = false;
  109488. babylonMaterial.twoSidedLighting = true;
  109489. }
  109490. this._loader._loadMaterialAlphaProperties(context, material, babylonMaterial);
  109491. return Promise.all(promises).then(function () { });
  109492. };
  109493. return KHR_materials_unlit;
  109494. }(GLTF2.GLTFLoaderExtension));
  109495. Extensions.KHR_materials_unlit = KHR_materials_unlit;
  109496. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_materials_unlit(loader); });
  109497. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  109498. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  109499. })(BABYLON || (BABYLON = {}));
  109500. //# sourceMappingURL=KHR_materials_unlit.js.map
  109501. var BABYLON;
  109502. (function (BABYLON) {
  109503. var GLTF2;
  109504. (function (GLTF2) {
  109505. var Extensions;
  109506. (function (Extensions) {
  109507. var NAME = "KHR_lights";
  109508. var LightType;
  109509. (function (LightType) {
  109510. LightType["AMBIENT"] = "ambient";
  109511. LightType["DIRECTIONAL"] = "directional";
  109512. LightType["POINT"] = "point";
  109513. LightType["SPOT"] = "spot";
  109514. })(LightType || (LightType = {}));
  109515. /**
  109516. * [Specification](https://github.com/MiiBond/glTF/tree/khr_lights_v1/extensions/Khronos/KHR_lights) (Experimental)
  109517. */
  109518. var KHR_lights = /** @class */ (function (_super) {
  109519. __extends(KHR_lights, _super);
  109520. function KHR_lights() {
  109521. var _this = _super !== null && _super.apply(this, arguments) || this;
  109522. _this.name = NAME;
  109523. return _this;
  109524. }
  109525. KHR_lights.prototype._loadSceneAsync = function (context, scene) {
  109526. var _this = this;
  109527. return this._loadExtensionAsync(context, scene, function (extensionContext, extension) {
  109528. var promise = _this._loader._loadSceneAsync(extensionContext, scene);
  109529. var light = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._lights, extension.light);
  109530. if (light.type !== LightType.AMBIENT) {
  109531. throw new Error(extensionContext + ": Only ambient lights are allowed on a scene");
  109532. }
  109533. _this._loader._babylonScene.ambientColor = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.Black();
  109534. return promise;
  109535. });
  109536. };
  109537. KHR_lights.prototype._loadNodeAsync = function (context, node) {
  109538. var _this = this;
  109539. return this._loadExtensionAsync(context, node, function (extensionContext, extension) {
  109540. var promise = _this._loader._loadNodeAsync(extensionContext, node);
  109541. var babylonLight;
  109542. var light = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._lights, extension.light);
  109543. var name = node._babylonMesh.name;
  109544. switch (light.type) {
  109545. case LightType.AMBIENT: {
  109546. throw new Error(extensionContext + ": Ambient lights are not allowed on a node");
  109547. }
  109548. case LightType.DIRECTIONAL: {
  109549. babylonLight = new BABYLON.DirectionalLight(name, BABYLON.Vector3.Forward(), _this._loader._babylonScene);
  109550. break;
  109551. }
  109552. case LightType.POINT: {
  109553. babylonLight = new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), _this._loader._babylonScene);
  109554. break;
  109555. }
  109556. case LightType.SPOT: {
  109557. var spotLight = light;
  109558. // TODO: support inner and outer cone angles
  109559. //const innerConeAngle = spotLight.innerConeAngle || 0;
  109560. var outerConeAngle = spotLight.outerConeAngle || Math.PI / 4;
  109561. babylonLight = new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward(), outerConeAngle, 2, _this._loader._babylonScene);
  109562. break;
  109563. }
  109564. default: {
  109565. throw new Error(extensionContext + ": Invalid light type (" + light.type + ")");
  109566. }
  109567. }
  109568. babylonLight.diffuse = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.White();
  109569. babylonLight.intensity = light.intensity == undefined ? 1 : light.intensity;
  109570. babylonLight.parent = node._babylonMesh;
  109571. return promise;
  109572. });
  109573. };
  109574. Object.defineProperty(KHR_lights.prototype, "_lights", {
  109575. get: function () {
  109576. var extensions = this._loader._gltf.extensions;
  109577. if (!extensions || !extensions[this.name]) {
  109578. throw new Error("#/extensions: '" + this.name + "' not found");
  109579. }
  109580. var extension = extensions[this.name];
  109581. return extension.lights;
  109582. },
  109583. enumerable: true,
  109584. configurable: true
  109585. });
  109586. return KHR_lights;
  109587. }(GLTF2.GLTFLoaderExtension));
  109588. Extensions.KHR_lights = KHR_lights;
  109589. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_lights(loader); });
  109590. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  109591. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  109592. })(BABYLON || (BABYLON = {}));
  109593. var BABYLON;
  109594. (function (BABYLON) {
  109595. var GLTF2;
  109596. (function (GLTF2) {
  109597. var Extensions;
  109598. (function (Extensions) {
  109599. var NAME = "KHR_texture_transform";
  109600. /**
  109601. * [Specification](https://github.com/AltspaceVR/glTF/blob/avr-sampler-offset-tile/extensions/2.0/Khronos/KHR_texture_transform/README.md) (Experimental)
  109602. */
  109603. var KHR_texture_transform = /** @class */ (function (_super) {
  109604. __extends(KHR_texture_transform, _super);
  109605. function KHR_texture_transform() {
  109606. var _this = _super !== null && _super.apply(this, arguments) || this;
  109607. _this.name = NAME;
  109608. return _this;
  109609. }
  109610. KHR_texture_transform.prototype._loadTextureAsync = function (context, textureInfo, assign) {
  109611. var _this = this;
  109612. return this._loadExtensionAsync(context, textureInfo, function (extensionContext, extension) {
  109613. return _this._loader._loadTextureAsync(context, textureInfo, function (babylonTexture) {
  109614. if (extension.offset) {
  109615. babylonTexture.uOffset = extension.offset[0];
  109616. babylonTexture.vOffset = extension.offset[1];
  109617. }
  109618. // Always rotate around the origin.
  109619. babylonTexture.uRotationCenter = 0;
  109620. babylonTexture.vRotationCenter = 0;
  109621. if (extension.rotation) {
  109622. babylonTexture.wAng = -extension.rotation;
  109623. }
  109624. if (extension.scale) {
  109625. babylonTexture.uScale = extension.scale[0];
  109626. babylonTexture.vScale = extension.scale[1];
  109627. }
  109628. if (extension.texCoord != undefined) {
  109629. babylonTexture.coordinatesIndex = extension.texCoord;
  109630. }
  109631. assign(babylonTexture);
  109632. });
  109633. });
  109634. };
  109635. return KHR_texture_transform;
  109636. }(GLTF2.GLTFLoaderExtension));
  109637. Extensions.KHR_texture_transform = KHR_texture_transform;
  109638. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_texture_transform(loader); });
  109639. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  109640. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  109641. })(BABYLON || (BABYLON = {}));
  109642. return BABYLON;
  109643. });
  109644. /***/ }),
  109645. /* 15 */
  109646. /***/ (function(module, exports, __webpack_require__) {
  109647. module.exports = __webpack_require__(16);
  109648. /***/ }),
  109649. /* 16 */
  109650. /***/ (function(module, exports, __webpack_require__) {
  109651. "use strict";
  109652. function __export(m) {
  109653. for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
  109654. }
  109655. Object.defineProperty(exports, "__esModule", { value: true });
  109656. var mappers_1 = __webpack_require__(3);
  109657. exports.mapperManager = mappers_1.mapperManager;
  109658. var globals_1 = __webpack_require__(4);
  109659. exports.viewerGlobals = globals_1.viewerGlobals;
  109660. var viewerManager_1 = __webpack_require__(7);
  109661. exports.viewerManager = viewerManager_1.viewerManager;
  109662. var defaultViewer_1 = __webpack_require__(8);
  109663. exports.DefaultViewer = defaultViewer_1.DefaultViewer;
  109664. var viewer_1 = __webpack_require__(9);
  109665. exports.AbstractViewer = viewer_1.AbstractViewer;
  109666. var telemetryManager_1 = __webpack_require__(6);
  109667. exports.telemetryManager = telemetryManager_1.telemetryManager;
  109668. var modelLoader_1 = __webpack_require__(13);
  109669. exports.ModelLoader = modelLoader_1.ModelLoader;
  109670. var viewerModel_1 = __webpack_require__(5);
  109671. exports.ViewerModel = viewerModel_1.ViewerModel;
  109672. exports.ModelState = viewerModel_1.ModelState;
  109673. /**
  109674. * BabylonJS Viewer
  109675. *
  109676. * An HTML-Based viewer for 3D models, based on BabylonJS and its extensions.
  109677. */
  109678. var BABYLON = __webpack_require__(0);
  109679. exports.BABYLON = BABYLON;
  109680. // load needed modules.
  109681. __webpack_require__(14);
  109682. __webpack_require__(64);
  109683. var initializer_1 = __webpack_require__(65);
  109684. exports.InitTags = initializer_1.InitTags;
  109685. // promise polyfill, if needed!
  109686. BABYLON.PromisePolyfill.Apply();
  109687. initializer_1.initListeners();
  109688. //deprectaed, here for backwards compatibility
  109689. var disableInit = globals_1.viewerGlobals.disableInit;
  109690. exports.disableInit = disableInit;
  109691. /**
  109692. * Dispose all viewers currently registered
  109693. */
  109694. function disposeAll() {
  109695. viewerManager_1.viewerManager.dispose();
  109696. mappers_1.mapperManager.dispose();
  109697. telemetryManager_1.telemetryManager.dispose();
  109698. }
  109699. exports.disposeAll = disposeAll;
  109700. var Version = globals_1.viewerGlobals.version;
  109701. exports.Version = Version;
  109702. console.log("Babylon.js viewer (v" + Version + ")");
  109703. // export publicliy all configuration interfaces
  109704. __export(__webpack_require__(10));
  109705. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi9zcmMvaW5kZXgudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7Ozs7QUFBQSxtREFBd0Q7QUE4Q3lFLHdCQTlDeEgsdUJBQWEsQ0E4Q3dIO0FBN0M5SSxtREFBd0Q7QUE2Q1ksd0JBN0MzRCx1QkFBYSxDQTZDMkQ7QUE1Q2pGLHdEQUF1RDtBQTRDMkQsd0JBNUN6Ryw2QkFBYSxDQTRDeUc7QUEzQy9ILHdEQUF1RDtBQTJDbEIsd0JBM0M1Qiw2QkFBYSxDQTJDNEI7QUExQ2xELDBDQUFpRDtBQTBDRyx5QkExQzNDLHVCQUFjLENBMEMyQztBQXpDbEUsZ0VBQStEO0FBeUNvQiwyQkF6QzFFLG1DQUFnQixDQXlDMEU7QUF4Q25HLG9EQUFtRDtBQXdDeUcsc0JBeENuSix5QkFBVyxDQXdDbUo7QUF2Q3ZLLG1EQUE4RDtBQXVDMkcsc0JBdkNoSyx5QkFBVyxDQXVDZ0s7QUFBcUMscUJBdkNuTSx3QkFBVSxDQXVDbU07QUFuQ25POzs7O0dBSUc7QUFFSCxtQ0FBcUM7QUE2QjVCLDBCQUFPO0FBM0JoQix1QkFBdUI7QUFDdkIsNkJBQTJCO0FBQzNCLGlCQUFlO0FBRWYsNkNBQXdEO0FBdUI3QixtQkF2Qkgsc0JBQVEsQ0F1Qkc7QUFyQm5DLCtCQUErQjtBQUMvQixPQUFPLENBQUMsZUFBZSxDQUFDLEtBQUssRUFBRSxDQUFDO0FBQ2hDLDJCQUFhLEVBQUUsQ0FBQztBQUVoQiw4Q0FBOEM7QUFDOUMsSUFBSSxXQUFXLEdBQVksdUJBQWEsQ0FBQyxXQUFXLENBQUM7QUFnQmdELGtDQUFXO0FBZGhIOztHQUVHO0FBQ0g7SUFDSSw2QkFBYSxDQUFDLE9BQU8sRUFBRSxDQUFDO0lBQ3hCLHVCQUFhLENBQUMsT0FBTyxFQUFFLENBQUM7SUFDeEIsbUNBQWdCLENBQUMsT0FBTyxFQUFFLENBQUM7QUFDL0IsQ0FBQztBQU8rSSxnQ0FBVTtBQUwxSixJQUFNLE9BQU8sR0FBRyx1QkFBYSxDQUFDLE9BQU8sQ0FBQztBQUtwQiwwQkFBTztBQUh6QixPQUFPLENBQUMsR0FBRyxDQUFDLHNCQUFzQixHQUFHLE9BQU8sR0FBRyxHQUFHLENBQUMsQ0FBQztBQUlwRCxnREFBZ0Q7QUFDaEQscUNBQWdDIn0=
  109706. /***/ }),
  109707. /* 17 */
  109708. /***/ (function(module, exports) {
  109709. var g;
  109710. // This works in non-strict mode
  109711. g = (function() {
  109712. return this;
  109713. })();
  109714. try {
  109715. // This works if eval is allowed (see CSP)
  109716. g = g || Function("return this")() || (1,eval)("this");
  109717. } catch(e) {
  109718. // This works if the window reference is available
  109719. if(typeof window === "object")
  109720. g = window;
  109721. }
  109722. // g can still be undefined, but nothing to do about it...
  109723. // We return undefined, instead of nothing here, so it's
  109724. // easier to handle this case. if(!global) { ...}
  109725. module.exports = g;
  109726. /***/ }),
  109727. /* 18 */
  109728. /***/ (function(module, exports) {
  109729. if(typeof CANNON === 'undefined') {var e = new Error("Cannot find module \"CANNON\""); e.code = 'MODULE_NOT_FOUND'; throw e;}
  109730. module.exports = CANNON;
  109731. /***/ }),
  109732. /* 19 */
  109733. /***/ (function(module, exports) {
  109734. if(typeof OIMO === 'undefined') {var e = new Error("Cannot find module \"OIMO\""); e.code = 'MODULE_NOT_FOUND'; throw e;}
  109735. module.exports = OIMO;
  109736. /***/ }),
  109737. /* 20 */
  109738. /***/ (function(module, exports) {
  109739. if(typeof earcut === 'undefined') {var e = new Error("Cannot find module \"earcut\""); e.code = 'MODULE_NOT_FOUND'; throw e;}
  109740. module.exports = earcut;
  109741. /***/ }),
  109742. /* 21 */
  109743. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  109744. "use strict";
  109745. Object.defineProperty(__webpack_exports__, "__esModule", { value: true });
  109746. var isMergeableObject = function isMergeableObject(value) {
  109747. return isNonNullObject(value)
  109748. && !isSpecial(value)
  109749. };
  109750. function isNonNullObject(value) {
  109751. return !!value && typeof value === 'object'
  109752. }
  109753. function isSpecial(value) {
  109754. var stringValue = Object.prototype.toString.call(value);
  109755. return stringValue === '[object RegExp]'
  109756. || stringValue === '[object Date]'
  109757. || isReactElement(value)
  109758. }
  109759. // see https://github.com/facebook/react/blob/b5ac963fb791d1298e7f396236383bc955f916c1/src/isomorphic/classic/element/ReactElement.js#L21-L25
  109760. var canUseSymbol = typeof Symbol === 'function' && Symbol.for;
  109761. var REACT_ELEMENT_TYPE = canUseSymbol ? Symbol.for('react.element') : 0xeac7;
  109762. function isReactElement(value) {
  109763. return value.$$typeof === REACT_ELEMENT_TYPE
  109764. }
  109765. function emptyTarget(val) {
  109766. return Array.isArray(val) ? [] : {}
  109767. }
  109768. function cloneUnlessOtherwiseSpecified(value, options) {
  109769. return (options.clone !== false && options.isMergeableObject(value))
  109770. ? deepmerge(emptyTarget(value), value, options)
  109771. : value
  109772. }
  109773. function defaultArrayMerge(target, source, options) {
  109774. return target.concat(source).map(function(element) {
  109775. return cloneUnlessOtherwiseSpecified(element, options)
  109776. })
  109777. }
  109778. function mergeObject(target, source, options) {
  109779. var destination = {};
  109780. if (options.isMergeableObject(target)) {
  109781. Object.keys(target).forEach(function(key) {
  109782. destination[key] = cloneUnlessOtherwiseSpecified(target[key], options);
  109783. });
  109784. }
  109785. Object.keys(source).forEach(function(key) {
  109786. if (!options.isMergeableObject(source[key]) || !target[key]) {
  109787. destination[key] = cloneUnlessOtherwiseSpecified(source[key], options);
  109788. } else {
  109789. destination[key] = deepmerge(target[key], source[key], options);
  109790. }
  109791. });
  109792. return destination
  109793. }
  109794. function deepmerge(target, source, options) {
  109795. options = options || {};
  109796. options.arrayMerge = options.arrayMerge || defaultArrayMerge;
  109797. options.isMergeableObject = options.isMergeableObject || isMergeableObject;
  109798. var sourceIsArray = Array.isArray(source);
  109799. var targetIsArray = Array.isArray(target);
  109800. var sourceAndTargetTypesMatch = sourceIsArray === targetIsArray;
  109801. if (!sourceAndTargetTypesMatch) {
  109802. return cloneUnlessOtherwiseSpecified(source, options)
  109803. } else if (sourceIsArray) {
  109804. return options.arrayMerge(target, source, options)
  109805. } else {
  109806. return mergeObject(target, source, options)
  109807. }
  109808. }
  109809. deepmerge.all = function deepmergeAll(array, options) {
  109810. if (!Array.isArray(array)) {
  109811. throw new Error('first argument should be an array')
  109812. }
  109813. return array.reduce(function(prev, next) {
  109814. return deepmerge(prev, next, options)
  109815. }, {})
  109816. };
  109817. var deepmerge_1 = deepmerge;
  109818. /* harmony default export */ __webpack_exports__["default"] = (deepmerge_1);
  109819. /***/ }),
  109820. /* 22 */
  109821. /***/ (function(module, exports, __webpack_require__) {
  109822. "use strict";
  109823. Object.defineProperty(exports, "__esModule", { value: true });
  109824. var babylonjs_1 = __webpack_require__(0);
  109825. var configuration_1 = __webpack_require__(10);
  109826. var viewerModel_1 = __webpack_require__(5);
  109827. var helper_1 = __webpack_require__(1);
  109828. var viewerLabs_1 = __webpack_require__(24);
  109829. var _1 = __webpack_require__(26);
  109830. var SceneManager = /** @class */ (function () {
  109831. function SceneManager(_engine, _configurationContainer, _observablesManager) {
  109832. var _this = this;
  109833. this._engine = _engine;
  109834. this._configurationContainer = _configurationContainer;
  109835. this._observablesManager = _observablesManager;
  109836. this._animationBlendingEnabled = true;
  109837. this._white = babylonjs_1.Color3.White();
  109838. this._forceShadowUpdate = false;
  109839. this._processShadows = true;
  109840. this._groundEnabled = true;
  109841. this._groundMirrorEnabled = true;
  109842. this._defaultRenderingPipelineEnabled = false;
  109843. this._globalConfiguration = {};
  109844. this._defaultRenderingPipelineShouldBuild = true;
  109845. // default from rendering pipeline
  109846. this._bloomEnabled = false;
  109847. // default from rendering pipeline
  109848. this._fxaaEnabled = false;
  109849. this._focusOnModel = function (model) {
  109850. var boundingInfo = model.rootMesh.getHierarchyBoundingVectors(true);
  109851. var sizeVec = boundingInfo.max.subtract(boundingInfo.min);
  109852. var halfSizeVec = sizeVec.scale(0.5);
  109853. var center = boundingInfo.min.add(halfSizeVec);
  109854. _this.camera.setTarget(center);
  109855. _this.camera.alpha = (_this._globalConfiguration.camera && _this._globalConfiguration.camera.alpha) || _this.camera.alpha;
  109856. _this.camera.beta = (_this._globalConfiguration.camera && _this._globalConfiguration.camera.beta) || _this.camera.beta;
  109857. _this.camera.radius = (_this._globalConfiguration.camera && _this._globalConfiguration.camera.radius) || _this.camera.radius;
  109858. var sceneDiagonalLenght = sizeVec.length();
  109859. if (isFinite(sceneDiagonalLenght))
  109860. _this.camera.upperRadiusLimit = sceneDiagonalLenght * 4;
  109861. if (_this._configurationContainer.configuration)
  109862. _this._configureEnvironment(_this._configurationContainer.configuration.skybox, _this._configurationContainer.configuration.ground);
  109863. /*this.scene.lights.filter(light => light instanceof ShadowLight).forEach(light => {
  109864. // casting ais safe, due to the constraints tested before
  109865. (<ShadowLight>light).setDirectionToTarget(center);
  109866. });*/
  109867. };
  109868. this._cameraBehaviorMapping = {};
  109869. this.models = [];
  109870. this.onCameraConfiguredObservable = new babylonjs_1.Observable();
  109871. this.onLightsConfiguredObservable = new babylonjs_1.Observable();
  109872. this.onModelsConfiguredObservable = new babylonjs_1.Observable();
  109873. this.onSceneConfiguredObservable = new babylonjs_1.Observable();
  109874. this.onSceneInitObservable = new babylonjs_1.Observable();
  109875. this.onSceneOptimizerConfiguredObservable = new babylonjs_1.Observable();
  109876. this.onEnvironmentConfiguredObservable = new babylonjs_1.Observable();
  109877. //this._viewer.onEngineInitObservable.add(() => {
  109878. this._handleHardwareLimitations();
  109879. //});
  109880. this.onSceneInitObservable.add(function (scene) {
  109881. _this.scene.animationPropertiesOverride = _this.scene.animationPropertiesOverride || new babylonjs_1.AnimationPropertiesOverride();
  109882. _this.labs = new viewerLabs_1.ViewerLabs(scene);
  109883. var updateShadows = function () {
  109884. for (var _i = 0, _a = _this.scene.lights; _i < _a.length; _i++) {
  109885. var light = _a[_i];
  109886. var generator = light.getShadowGenerator();
  109887. if (generator) {
  109888. // Processing shadows if animates
  109889. var shadowMap = generator.getShadowMap();
  109890. if (shadowMap) {
  109891. shadowMap.refreshRate = babylonjs_1.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  109892. }
  109893. }
  109894. }
  109895. };
  109896. scene.registerBeforeRender(function () {
  109897. if (_this._forceShadowUpdate || (scene.animatables && scene.animatables.length > 0)) {
  109898. // make sure all models are loaded
  109899. updateShadows();
  109900. _this._forceShadowUpdate = false;
  109901. }
  109902. else if (!(_this.models.every(function (model) {
  109903. if (!model.shadowsRenderedAfterLoad) {
  109904. model.shadowsRenderedAfterLoad = true;
  109905. return false;
  109906. }
  109907. return model.state === viewerModel_1.ModelState.COMPLETE && !model.currentAnimation;
  109908. }))) {
  109909. updateShadows();
  109910. }
  109911. });
  109912. return _this._observablesManager && _this._observablesManager.onSceneInitObservable.notifyObserversWithPromise(_this.scene);
  109913. });
  109914. if (this._observablesManager) {
  109915. this._observablesManager.onModelLoadedObservable.add(function (model) {
  109916. for (var _i = 0, _a = _this.scene.lights; _i < _a.length; _i++) {
  109917. var light = _a[_i];
  109918. var generator = light.getShadowGenerator();
  109919. if (generator) {
  109920. // Processing shadows if animates
  109921. var shadowMap = generator.getShadowMap();
  109922. if (shadowMap) {
  109923. shadowMap.refreshRate = babylonjs_1.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  109924. }
  109925. }
  109926. }
  109927. _this._focusOnModel(model);
  109928. });
  109929. this._observablesManager.onModelAddedObservable.add(function (model) {
  109930. _this.models.push(model);
  109931. });
  109932. this._observablesManager.onModelRemovedObservable.add(function (model) {
  109933. _this.models.splice(_this.models.indexOf(model), 1);
  109934. });
  109935. }
  109936. }
  109937. Object.defineProperty(SceneManager.prototype, "defaultRenderingPipeline", {
  109938. get: function () {
  109939. return this._defaultRenderingPipeline;
  109940. },
  109941. enumerable: true,
  109942. configurable: true
  109943. });
  109944. Object.defineProperty(SceneManager.prototype, "isHdrSupported", {
  109945. /**
  109946. * Returns a boolean representing HDR support
  109947. */
  109948. get: function () {
  109949. return this._hdrSupport;
  109950. },
  109951. enumerable: true,
  109952. configurable: true
  109953. });
  109954. Object.defineProperty(SceneManager.prototype, "mainColor", {
  109955. /**
  109956. * Return the main color defined in the configuration.
  109957. */
  109958. get: function () {
  109959. return this._configurationContainer.mainColor;
  109960. },
  109961. enumerable: true,
  109962. configurable: true
  109963. });
  109964. Object.defineProperty(SceneManager.prototype, "reflectionColor", {
  109965. get: function () {
  109966. return this._configurationContainer.reflectionColor;
  109967. },
  109968. enumerable: true,
  109969. configurable: true
  109970. });
  109971. Object.defineProperty(SceneManager.prototype, "animationBlendingEnabled", {
  109972. get: function () {
  109973. return this.scene && this.scene.animationPropertiesOverride.enableBlending;
  109974. },
  109975. set: function (value) {
  109976. this.scene.animationPropertiesOverride.enableBlending = value;
  109977. },
  109978. enumerable: true,
  109979. configurable: true
  109980. });
  109981. Object.defineProperty(SceneManager.prototype, "observablesManager", {
  109982. get: function () {
  109983. return this._observablesManager;
  109984. },
  109985. enumerable: true,
  109986. configurable: true
  109987. });
  109988. Object.defineProperty(SceneManager.prototype, "processShadows", {
  109989. /**
  109990. * The flag defining whether shadows are rendered constantly or once.
  109991. */
  109992. get: function () {
  109993. return this._processShadows;
  109994. },
  109995. /**
  109996. * Should shadows be rendered every frame, or only once and stop.
  109997. * This can be used to optimize a scene.
  109998. *
  109999. * Not that the shadows will NOT disapear but will remain in place.
  110000. * @param process if true shadows will be updated once every frame. if false they will stop being updated.
  110001. */
  110002. set: function (process) {
  110003. var refreshType = process ? babylonjs_1.RenderTargetTexture.REFRESHRATE_RENDER_ONEVERYFRAME : babylonjs_1.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  110004. for (var _i = 0, _a = this.scene.lights; _i < _a.length; _i++) {
  110005. var light = _a[_i];
  110006. var generator = light.getShadowGenerator();
  110007. if (generator) {
  110008. var shadowMap = generator.getShadowMap();
  110009. if (shadowMap) {
  110010. shadowMap.refreshRate = refreshType;
  110011. }
  110012. }
  110013. }
  110014. this._processShadows = process;
  110015. },
  110016. enumerable: true,
  110017. configurable: true
  110018. });
  110019. Object.defineProperty(SceneManager.prototype, "groundEnabled", {
  110020. get: function () {
  110021. return this._groundEnabled;
  110022. },
  110023. set: function (newValue) {
  110024. if (newValue === this._groundEnabled)
  110025. return;
  110026. this._groundEnabled = newValue;
  110027. if (this.environmentHelper && this.environmentHelper.ground) {
  110028. this.environmentHelper.ground.setEnabled(this._groundEnabled);
  110029. }
  110030. },
  110031. enumerable: true,
  110032. configurable: true
  110033. });
  110034. Object.defineProperty(SceneManager.prototype, "groundMirrorEnabled", {
  110035. /**
  110036. * gets wether the reflection is disabled.
  110037. */
  110038. get: function () {
  110039. return this._groundMirrorEnabled;
  110040. },
  110041. /**
  110042. * sets wether the reflection is disabled.
  110043. */
  110044. set: function (value) {
  110045. if (this._groundMirrorEnabled === value) {
  110046. return;
  110047. }
  110048. this._groundMirrorEnabled = value;
  110049. if (this.environmentHelper && this.environmentHelper.groundMaterial && this.environmentHelper.groundMirror) {
  110050. if (!value) {
  110051. this.environmentHelper.groundMaterial.reflectionTexture = null;
  110052. }
  110053. else {
  110054. this.environmentHelper.groundMaterial.reflectionTexture = this.environmentHelper.groundMirror;
  110055. }
  110056. }
  110057. },
  110058. enumerable: true,
  110059. configurable: true
  110060. });
  110061. Object.defineProperty(SceneManager.prototype, "defaultRenderingPipelineEnabled", {
  110062. get: function () {
  110063. return this._defaultRenderingPipelineEnabled;
  110064. },
  110065. set: function (value) {
  110066. if (value === this._defaultRenderingPipelineEnabled) {
  110067. return;
  110068. }
  110069. this._defaultRenderingPipelineEnabled = value;
  110070. this._rebuildPostprocesses();
  110071. if (this._defaultRenderingPipeline) {
  110072. this._defaultRenderingPipelineShouldBuild = false;
  110073. this._defaultRenderingPipeline.prepare();
  110074. this.scene.imageProcessingConfiguration.applyByPostProcess = true;
  110075. }
  110076. },
  110077. enumerable: true,
  110078. configurable: true
  110079. });
  110080. /**
  110081. * Sets the engine flags to unlock all babylon features.
  110082. * Can also be configured using the scene.flags configuration object
  110083. */
  110084. SceneManager.prototype.unlockBabylonFeatures = function () {
  110085. this.scene.shadowsEnabled = true;
  110086. this.scene.particlesEnabled = true;
  110087. this.scene.postProcessesEnabled = true;
  110088. this.scene.collisionsEnabled = true;
  110089. this.scene.lightsEnabled = true;
  110090. this.scene.texturesEnabled = true;
  110091. this.scene.lensFlaresEnabled = true;
  110092. this.scene.proceduralTexturesEnabled = true;
  110093. this.scene.renderTargetsEnabled = true;
  110094. this.scene.spritesEnabled = true;
  110095. this.scene.skeletonsEnabled = true;
  110096. this.scene.audioEnabled = true;
  110097. };
  110098. /**
  110099. * initialize the scene. Calling this function again will dispose the old scene, if exists.
  110100. */
  110101. SceneManager.prototype.initScene = function (sceneConfiguration, optimizerConfiguration) {
  110102. if (sceneConfiguration === void 0) { sceneConfiguration = {}; }
  110103. // if the scen exists, dispose it.
  110104. if (this.scene) {
  110105. this.scene.dispose();
  110106. }
  110107. // create a new scene
  110108. this.scene = new babylonjs_1.Scene(this._engine);
  110109. // set a default PBR material
  110110. if (!sceneConfiguration.defaultMaterial) {
  110111. var defaultMaterial = new BABYLON.PBRMaterial('defaultMaterial', this.scene);
  110112. defaultMaterial.reflectivityColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  110113. defaultMaterial.microSurface = 0.6;
  110114. if (this.scene.defaultMaterial) {
  110115. this.scene.defaultMaterial.dispose();
  110116. }
  110117. this.scene.defaultMaterial = defaultMaterial;
  110118. }
  110119. this.scene.animationPropertiesOverride = new babylonjs_1.AnimationPropertiesOverride();
  110120. babylonjs_1.Animation.AllowMatricesInterpolation = true;
  110121. /*if (sceneConfiguration.glow) {
  110122. let options: Partial<IGlowLayerOptions> = {
  110123. mainTextureFixedSize: 512
  110124. };
  110125. if (typeof sceneConfiguration.glow === 'object') {
  110126. options = sceneConfiguration.glow
  110127. }
  110128. var gl = new BABYLON.GlowLayer("glow", this.scene, options);
  110129. }*/
  110130. return this.onSceneInitObservable.notifyObserversWithPromise(this.scene);
  110131. };
  110132. SceneManager.prototype.clearScene = function (clearModels, clearLights) {
  110133. if (clearModels === void 0) { clearModels = true; }
  110134. if (clearLights === void 0) { clearLights = false; }
  110135. if (clearModels) {
  110136. this.models.forEach(function (m) { return m.dispose(); });
  110137. this.models.length = 0;
  110138. }
  110139. if (clearLights) {
  110140. this.scene.lights.forEach(function (l) { return l.dispose(); });
  110141. }
  110142. };
  110143. /**
  110144. * This will update the scene's configuration, including camera, lights, environment.
  110145. * @param newConfiguration the delta that should be configured. This includes only the changes
  110146. * @param globalConfiguration The global configuration object, after the new configuration was merged into it
  110147. */
  110148. SceneManager.prototype.updateConfiguration = function (newConfiguration) {
  110149. var _this = this;
  110150. if (this._configurationContainer) {
  110151. this._globalConfiguration = this._configurationContainer.configuration;
  110152. }
  110153. else {
  110154. this._globalConfiguration = newConfiguration;
  110155. }
  110156. if (newConfiguration.lab) {
  110157. if (newConfiguration.lab.assetsRootURL) {
  110158. this.labs.assetsRootURL = newConfiguration.lab.assetsRootURL;
  110159. }
  110160. }
  110161. // update scene configuration
  110162. if (newConfiguration.scene) {
  110163. this._configureScene(newConfiguration.scene);
  110164. }
  110165. // optimizer
  110166. if (newConfiguration.optimizer !== undefined) {
  110167. this._configureOptimizer(newConfiguration.optimizer);
  110168. }
  110169. // configure model
  110170. /*if (newConfiguration.model && typeof newConfiguration.model === 'object') {
  110171. this._configureModel(newConfiguration.model);
  110172. }*/
  110173. // lights
  110174. this._configureLights(newConfiguration.lights);
  110175. // environment
  110176. if (newConfiguration.skybox !== undefined || newConfiguration.ground !== undefined) {
  110177. this._configureEnvironment(newConfiguration.skybox, newConfiguration.ground);
  110178. }
  110179. // camera
  110180. this._configureCamera(newConfiguration.camera);
  110181. if (newConfiguration.lab) {
  110182. if (newConfiguration.lab.environmentMap) {
  110183. var rot_1 = newConfiguration.lab.environmentMap.rotationY;
  110184. this.labs.loadEnvironment(newConfiguration.lab.environmentMap.texture, function () {
  110185. _this.labs.applyEnvironmentMapConfiguration(rot_1);
  110186. });
  110187. if (!newConfiguration.lab.environmentMap.texture && newConfiguration.lab.environmentMap.rotationY) {
  110188. this.labs.applyEnvironmentMapConfiguration(newConfiguration.lab.environmentMap.rotationY);
  110189. }
  110190. }
  110191. // rendering piplines
  110192. if (newConfiguration.lab.defaultRenderingPipelines) {
  110193. var pipelineConfig = newConfiguration.lab.defaultRenderingPipelines;
  110194. if (typeof pipelineConfig === 'boolean') {
  110195. this.defaultRenderingPipelineEnabled = pipelineConfig;
  110196. }
  110197. else {
  110198. this.defaultRenderingPipelineEnabled = true;
  110199. }
  110200. }
  110201. if (newConfiguration.lab.environmentMainColor) {
  110202. var mainColor = new babylonjs_1.Color3().copyFrom(newConfiguration.lab.environmentMainColor);
  110203. this.environmentHelper.setMainColor(mainColor);
  110204. }
  110205. if (newConfiguration.lab.globalLightRotation !== undefined) {
  110206. // rotate all lights that are shadow lights
  110207. this.scene.lights.filter(function (light) { return light instanceof babylonjs_1.ShadowLight; }).forEach(function (light) {
  110208. // casting and '!' are safe, due to the constraints tested before
  110209. _this.labs.rotateShadowLight(light, newConfiguration.lab.globalLightRotation);
  110210. });
  110211. this._forceShadowUpdate = true;
  110212. }
  110213. }
  110214. if (this._defaultRenderingPipeline && this._defaultRenderingPipeline.imageProcessing) {
  110215. this._defaultRenderingPipeline.imageProcessing.fromLinearSpace = true;
  110216. }
  110217. if (this._defaultRenderingPipelineShouldBuild && this._defaultRenderingPipeline) {
  110218. this._defaultRenderingPipelineShouldBuild = false;
  110219. this._defaultRenderingPipeline.prepare();
  110220. }
  110221. };
  110222. SceneManager.prototype._rebuildPostprocesses = function (configuration) {
  110223. if (!this._defaultRenderingPipelineEnabled || !configuration_1.getConfigurationKey("scene.imageProcessingConfiguration.isEnabled", this._globalConfiguration)) {
  110224. if (this._defaultRenderingPipeline) {
  110225. this._defaultRenderingPipeline.dispose();
  110226. this._defaultRenderingPipeline = null;
  110227. this.scene.autoClearDepthAndStencil = true;
  110228. this.scene.autoClear = true;
  110229. this.scene.imageProcessingConfiguration.applyByPostProcess = false;
  110230. }
  110231. return;
  110232. }
  110233. var pipelineConfig = configuration || (this._globalConfiguration.lab && this._globalConfiguration.lab.defaultRenderingPipelines);
  110234. if (pipelineConfig) {
  110235. if (!this._defaultRenderingPipeline) {
  110236. // Create pipeline in manual mode to avoid triggering multiple shader compilations
  110237. this._defaultRenderingPipeline = new babylonjs_1.DefaultRenderingPipeline("default rendering pipeline", this._hdrSupport, this.scene, [this.camera], false);
  110238. }
  110239. this.scene.autoClear = false;
  110240. this.scene.autoClearDepthAndStencil = false;
  110241. this._defaultRenderingPipelineShouldBuild = true;
  110242. var bloomEnabled = this._bloomEnabled;
  110243. if (typeof pipelineConfig !== 'boolean') {
  110244. helper_1.extendClassWithConfig(this._defaultRenderingPipeline, pipelineConfig);
  110245. this._bloomEnabled = !!pipelineConfig.bloomEnabled;
  110246. this._fxaaEnabled = !!pipelineConfig.fxaaEnabled;
  110247. bloomEnabled = this._bloomEnabled && pipelineConfig.bloomWeight !== undefined && pipelineConfig.bloomWeight > 0;
  110248. this._defaultRenderingPipeline.bloomWeight = (pipelineConfig.bloomWeight !== undefined && pipelineConfig.bloomWeight) || (this._defaultRenderingPipeline.bloomWeight);
  110249. }
  110250. this._defaultRenderingPipeline.bloomEnabled = bloomEnabled;
  110251. this._defaultRenderingPipeline.fxaaEnabled = this.fxaaEnabled;
  110252. }
  110253. };
  110254. Object.defineProperty(SceneManager.prototype, "bloomEnabled", {
  110255. get: function () {
  110256. return this._bloomEnabled;
  110257. },
  110258. set: function (value) {
  110259. if (this._bloomEnabled === value) {
  110260. return;
  110261. }
  110262. this._bloomEnabled = value;
  110263. this._rebuildPostprocesses();
  110264. if (this._defaultRenderingPipeline) {
  110265. this._defaultRenderingPipelineShouldBuild = false;
  110266. this._defaultRenderingPipeline.prepare();
  110267. this.scene.imageProcessingConfiguration.applyByPostProcess = true;
  110268. }
  110269. },
  110270. enumerable: true,
  110271. configurable: true
  110272. });
  110273. Object.defineProperty(SceneManager.prototype, "fxaaEnabled", {
  110274. get: function () {
  110275. return this._fxaaEnabled;
  110276. },
  110277. set: function (value) {
  110278. if (this._fxaaEnabled === value) {
  110279. return;
  110280. }
  110281. this._fxaaEnabled = value;
  110282. this._rebuildPostprocesses();
  110283. if (this._defaultRenderingPipeline) {
  110284. this._defaultRenderingPipelineShouldBuild = false;
  110285. this._defaultRenderingPipeline.prepare();
  110286. this.scene.imageProcessingConfiguration.applyByPostProcess = true;
  110287. }
  110288. },
  110289. enumerable: true,
  110290. configurable: true
  110291. });
  110292. /**
  110293. * internally configure the scene using the provided configuration.
  110294. * The scene will not be recreated, but just updated.
  110295. * @param sceneConfig the (new) scene configuration
  110296. */
  110297. SceneManager.prototype._configureScene = function (sceneConfig) {
  110298. // sanity check!
  110299. if (!this.scene) {
  110300. return;
  110301. }
  110302. var cc = sceneConfig.clearColor;
  110303. var oldcc = this.scene.clearColor;
  110304. if (cc) {
  110305. if (cc.r !== undefined) {
  110306. oldcc.r = cc.r;
  110307. }
  110308. if (cc.g !== undefined) {
  110309. oldcc.g = cc.g;
  110310. }
  110311. if (cc.b !== undefined) {
  110312. oldcc.b = cc.b;
  110313. }
  110314. if (cc.a !== undefined) {
  110315. oldcc.a = cc.a;
  110316. }
  110317. }
  110318. // image processing configuration - optional.
  110319. if (sceneConfig.imageProcessingConfiguration) {
  110320. helper_1.extendClassWithConfig(this.scene.imageProcessingConfiguration, sceneConfig.imageProcessingConfiguration);
  110321. }
  110322. //animation properties override
  110323. if (sceneConfig.animationPropertiesOverride) {
  110324. helper_1.extendClassWithConfig(this.scene.animationPropertiesOverride, sceneConfig.animationPropertiesOverride);
  110325. }
  110326. if (sceneConfig.environmentTexture) {
  110327. if (!(this.scene.environmentTexture && this.scene.environmentTexture.url === sceneConfig.environmentTexture)) {
  110328. if (this.scene.environmentTexture && this.scene.environmentTexture.dispose) {
  110329. this.scene.environmentTexture.dispose();
  110330. }
  110331. var environmentTexture = babylonjs_1.CubeTexture.CreateFromPrefilteredData(sceneConfig.environmentTexture, this.scene);
  110332. this.scene.environmentTexture = environmentTexture;
  110333. }
  110334. }
  110335. if (sceneConfig.debug === true) {
  110336. this.scene.debugLayer.show();
  110337. }
  110338. else if (sceneConfig.debug === false) {
  110339. if (this.scene.debugLayer.isVisible()) {
  110340. this.scene.debugLayer.hide();
  110341. }
  110342. }
  110343. if (sceneConfig.disableHdr) {
  110344. this._handleHardwareLimitations(false);
  110345. }
  110346. else {
  110347. this._handleHardwareLimitations(true);
  110348. }
  110349. if (sceneConfig.renderInBackground !== undefined) {
  110350. this._engine.renderEvenInBackground = !!sceneConfig.renderInBackground;
  110351. }
  110352. var canvas = this._engine.getRenderingCanvas();
  110353. if (canvas) {
  110354. if (this.camera && sceneConfig.disableCameraControl) {
  110355. this.camera.detachControl(canvas);
  110356. }
  110357. else if (this.camera && sceneConfig.disableCameraControl === false) {
  110358. this.camera.attachControl(canvas);
  110359. }
  110360. }
  110361. // process mainColor changes:
  110362. if (sceneConfig.mainColor) {
  110363. this._configurationContainer.mainColor = this.mainColor || babylonjs_1.Color3.White();
  110364. var mc = sceneConfig.mainColor;
  110365. if (mc.r !== undefined) {
  110366. this.mainColor.r = mc.r;
  110367. }
  110368. if (mc.g !== undefined) {
  110369. this.mainColor.g = mc.g;
  110370. }
  110371. if (mc.b !== undefined) {
  110372. this.mainColor.b = mc.b;
  110373. }
  110374. this.reflectionColor.copyFrom(this.mainColor);
  110375. var environmentTint = configuration_1.getConfigurationKey("lab.environmentMap.tintLevel", this._globalConfiguration) || 0;
  110376. // reflection color
  110377. this.reflectionColor.toLinearSpaceToRef(this.reflectionColor);
  110378. this.reflectionColor.scaleToRef(1 / this.scene.imageProcessingConfiguration.exposure, this.reflectionColor);
  110379. var tmpColor3 = babylonjs_1.Color3.Lerp(this._white, this.reflectionColor, environmentTint);
  110380. this.reflectionColor.copyFrom(tmpColor3);
  110381. //update the environment, if exists
  110382. if (this.environmentHelper) {
  110383. if (this.environmentHelper.groundMaterial) {
  110384. this.environmentHelper.groundMaterial._perceptualColor = this.mainColor;
  110385. }
  110386. if (this.environmentHelper.skyboxMaterial) {
  110387. this.environmentHelper.skyboxMaterial._perceptualColor = this.mainColor;
  110388. }
  110389. }
  110390. }
  110391. if (sceneConfig.defaultMaterial) {
  110392. var conf = sceneConfig.defaultMaterial;
  110393. if ((conf.materialType === 'standard' && this.scene.defaultMaterial.getClassName() !== 'StandardMaterial') ||
  110394. (conf.materialType === 'pbr' && this.scene.defaultMaterial.getClassName() !== 'PBRMaterial')) {
  110395. this.scene.defaultMaterial.dispose();
  110396. if (conf.materialType === 'standard') {
  110397. this.scene.defaultMaterial = new babylonjs_1.StandardMaterial("defaultMaterial", this.scene);
  110398. }
  110399. else {
  110400. this.scene.defaultMaterial = new babylonjs_1.PBRMaterial("defaultMaterial", this.scene);
  110401. }
  110402. }
  110403. helper_1.extendClassWithConfig(this.scene.defaultMaterial, conf);
  110404. }
  110405. if (sceneConfig.flags) {
  110406. helper_1.extendClassWithConfig(this.scene, sceneConfig.flags);
  110407. }
  110408. this.onSceneConfiguredObservable.notifyObservers({
  110409. sceneManager: this,
  110410. object: this.scene,
  110411. newConfiguration: sceneConfig
  110412. });
  110413. };
  110414. /**
  110415. * Configure the scene optimizer.
  110416. * The existing scene optimizer will be disposed and a new one will be created.
  110417. * @param optimizerConfig the (new) optimizer configuration
  110418. */
  110419. SceneManager.prototype._configureOptimizer = function (optimizerConfig) {
  110420. var _this = this;
  110421. if (typeof optimizerConfig === 'boolean') {
  110422. if (this.sceneOptimizer) {
  110423. this.sceneOptimizer.stop();
  110424. this.sceneOptimizer.dispose();
  110425. delete this.sceneOptimizer;
  110426. }
  110427. if (optimizerConfig) {
  110428. this.sceneOptimizer = new babylonjs_1.SceneOptimizer(this.scene);
  110429. this.sceneOptimizer.start();
  110430. }
  110431. }
  110432. else {
  110433. var optimizerOptions = new babylonjs_1.SceneOptimizerOptions(optimizerConfig.targetFrameRate, optimizerConfig.trackerDuration);
  110434. // check for degradation
  110435. if (optimizerConfig.degradation) {
  110436. switch (optimizerConfig.degradation) {
  110437. case "low":
  110438. optimizerOptions = babylonjs_1.SceneOptimizerOptions.LowDegradationAllowed(optimizerConfig.targetFrameRate);
  110439. break;
  110440. case "moderate":
  110441. optimizerOptions = babylonjs_1.SceneOptimizerOptions.ModerateDegradationAllowed(optimizerConfig.targetFrameRate);
  110442. break;
  110443. case "hight":
  110444. optimizerOptions = babylonjs_1.SceneOptimizerOptions.HighDegradationAllowed(optimizerConfig.targetFrameRate);
  110445. break;
  110446. }
  110447. }
  110448. if (this.sceneOptimizer) {
  110449. this.sceneOptimizer.stop();
  110450. this.sceneOptimizer.dispose();
  110451. }
  110452. if (optimizerConfig.custom) {
  110453. var customOptimizer_1 = _1.getCustomOptimizerByName(optimizerConfig.custom, optimizerConfig.improvementMode);
  110454. if (customOptimizer_1) {
  110455. optimizerOptions.addCustomOptimization(function () {
  110456. return customOptimizer_1(_this);
  110457. }, function () {
  110458. return "Babylon Viewer " + optimizerConfig.custom + " custom optimization";
  110459. });
  110460. }
  110461. }
  110462. this.sceneOptimizer = new babylonjs_1.SceneOptimizer(this.scene, optimizerOptions, optimizerConfig.autoGeneratePriorities, optimizerConfig.improvementMode);
  110463. this.sceneOptimizer.start();
  110464. }
  110465. this.onSceneOptimizerConfiguredObservable.notifyObservers({
  110466. sceneManager: this,
  110467. object: this.sceneOptimizer,
  110468. newConfiguration: optimizerConfig
  110469. });
  110470. };
  110471. /**
  110472. * configure all models using the configuration.
  110473. * @param modelConfiguration the configuration to use to reconfigure the models
  110474. */
  110475. /*protected _configureModel(modelConfiguration: Partial<IModelConfiguration>) {
  110476. this.models.forEach(model => {
  110477. model.updateConfiguration(modelConfiguration);
  110478. });
  110479. this.onModelsConfiguredObservable.notifyObservers({
  110480. sceneManager: this,
  110481. object: this.models,
  110482. newConfiguration: modelConfiguration
  110483. });
  110484. }*/
  110485. /**
  110486. * (Re) configure the camera. The camera will only be created once and from this point will only be reconfigured.
  110487. * @param cameraConfig the new camera configuration
  110488. * @param model optionally use the model to configure the camera.
  110489. */
  110490. SceneManager.prototype._configureCamera = function (cameraConfig) {
  110491. var _this = this;
  110492. if (cameraConfig === void 0) { cameraConfig = {}; }
  110493. if (!this.scene.activeCamera) {
  110494. var attachControl = true;
  110495. if (this._globalConfiguration.scene && this._globalConfiguration.scene.disableCameraControl) {
  110496. attachControl = false;
  110497. }
  110498. this.scene.createDefaultCamera(true, true, attachControl);
  110499. this.camera = this.scene.activeCamera;
  110500. this.camera.setTarget(babylonjs_1.Vector3.Zero());
  110501. }
  110502. if (cameraConfig.position) {
  110503. var newPosition = this.camera.position.clone();
  110504. helper_1.extendClassWithConfig(newPosition, cameraConfig.position);
  110505. this.camera.setPosition(newPosition);
  110506. }
  110507. if (cameraConfig.target) {
  110508. var newTarget = this.camera.target.clone();
  110509. helper_1.extendClassWithConfig(newTarget, cameraConfig.target);
  110510. this.camera.setTarget(newTarget);
  110511. } /*else if (this.models.length && !cameraConfig.disableAutoFocus) {
  110512. this._focusOnModel(this.models[0]);
  110513. }*/
  110514. if (cameraConfig.rotation) {
  110515. this.camera.rotationQuaternion = new babylonjs_1.Quaternion(cameraConfig.rotation.x || 0, cameraConfig.rotation.y || 0, cameraConfig.rotation.z || 0, cameraConfig.rotation.w || 0);
  110516. }
  110517. if (cameraConfig.behaviors) {
  110518. for (var name_1 in cameraConfig.behaviors) {
  110519. if (cameraConfig.behaviors[name_1] !== undefined) {
  110520. this._setCameraBehavior(name_1, cameraConfig.behaviors[name_1]);
  110521. }
  110522. }
  110523. }
  110524. ;
  110525. var sceneExtends = this.scene.getWorldExtends(function (mesh) {
  110526. return !_this.environmentHelper || (mesh !== _this.environmentHelper.ground && mesh !== _this.environmentHelper.rootMesh && mesh !== _this.environmentHelper.skybox);
  110527. });
  110528. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  110529. var sceneDiagonalLenght = sceneDiagonal.length();
  110530. if (isFinite(sceneDiagonalLenght))
  110531. this.camera.upperRadiusLimit = sceneDiagonalLenght * 4;
  110532. // sanity check!
  110533. if (this.scene.imageProcessingConfiguration) {
  110534. this.scene.imageProcessingConfiguration.colorCurvesEnabled = true;
  110535. this.scene.imageProcessingConfiguration.vignetteEnabled = true;
  110536. this.scene.imageProcessingConfiguration.toneMappingEnabled = !!configuration_1.getConfigurationKey("camera.toneMappingEnabled", this._globalConfiguration);
  110537. }
  110538. helper_1.extendClassWithConfig(this.camera, cameraConfig);
  110539. this.onCameraConfiguredObservable.notifyObservers({
  110540. sceneManager: this,
  110541. object: this.camera,
  110542. newConfiguration: cameraConfig
  110543. });
  110544. };
  110545. SceneManager.prototype._configureEnvironment = function (skyboxConifguration, groundConfiguration) {
  110546. var _this = this;
  110547. if (!skyboxConifguration && !groundConfiguration) {
  110548. if (this.environmentHelper) {
  110549. this.environmentHelper.dispose();
  110550. delete this.environmentHelper;
  110551. }
  110552. ;
  110553. }
  110554. else {
  110555. var options = {
  110556. createGround: !!groundConfiguration && this._groundEnabled,
  110557. createSkybox: !!skyboxConifguration,
  110558. setupImageProcessing: false,
  110559. };
  110560. // will that cause problems with model ground configuration?
  110561. /*if (model) {
  110562. const boundingInfo = model.rootMesh.getHierarchyBoundingVectors(true);
  110563. const sizeVec = boundingInfo.max.subtract(boundingInfo.min);
  110564. const halfSizeVec = sizeVec.scale(0.5);
  110565. const center = boundingInfo.min.add(halfSizeVec);
  110566. options.groundYBias = -center.y;
  110567. }*/
  110568. if (groundConfiguration) {
  110569. var groundConfig_1 = (typeof groundConfiguration === 'boolean') ? {} : groundConfiguration;
  110570. var groundSize = groundConfig_1.size || (typeof skyboxConifguration === 'object' && skyboxConifguration.scale);
  110571. if (groundSize) {
  110572. options.groundSize = groundSize;
  110573. }
  110574. options.enableGroundShadow = groundConfig_1 === true || groundConfig_1.receiveShadows;
  110575. if (groundConfig_1.shadowLevel !== undefined) {
  110576. options.groundShadowLevel = groundConfig_1.shadowLevel;
  110577. }
  110578. options.enableGroundMirror = !!groundConfig_1.mirror && this.groundMirrorEnabled;
  110579. if (groundConfig_1.texture) {
  110580. options.groundTexture = this.labs.getAssetUrl(groundConfig_1.texture);
  110581. }
  110582. if (groundConfig_1.color) {
  110583. options.groundColor = new babylonjs_1.Color3(groundConfig_1.color.r, groundConfig_1.color.g, groundConfig_1.color.b);
  110584. }
  110585. if (groundConfig_1.opacity !== undefined) {
  110586. options.groundOpacity = groundConfig_1.opacity;
  110587. }
  110588. if (groundConfig_1.mirror) {
  110589. options.enableGroundMirror = true;
  110590. // to prevent undefines
  110591. if (typeof groundConfig_1.mirror === "object") {
  110592. if (groundConfig_1.mirror.amount !== undefined)
  110593. options.groundMirrorAmount = groundConfig_1.mirror.amount;
  110594. if (groundConfig_1.mirror.sizeRatio !== undefined)
  110595. options.groundMirrorSizeRatio = groundConfig_1.mirror.sizeRatio;
  110596. if (groundConfig_1.mirror.blurKernel !== undefined)
  110597. options.groundMirrorBlurKernel = groundConfig_1.mirror.blurKernel;
  110598. if (groundConfig_1.mirror.fresnelWeight !== undefined)
  110599. options.groundMirrorFresnelWeight = groundConfig_1.mirror.fresnelWeight;
  110600. if (groundConfig_1.mirror.fallOffDistance !== undefined)
  110601. options.groundMirrorFallOffDistance = groundConfig_1.mirror.fallOffDistance;
  110602. if (this._defaultPipelineTextureType !== undefined)
  110603. options.groundMirrorTextureType = this._defaultPipelineTextureType;
  110604. }
  110605. }
  110606. }
  110607. var postInitSkyboxMaterial = false;
  110608. if (skyboxConifguration) {
  110609. var conf = skyboxConifguration === true ? {} : skyboxConifguration;
  110610. if (conf.material && conf.material.imageProcessingConfiguration) {
  110611. options.setupImageProcessing = false; // will be configured later manually.
  110612. }
  110613. var skyboxSize = conf.scale;
  110614. if (skyboxSize) {
  110615. options.skyboxSize = skyboxSize;
  110616. }
  110617. options.sizeAuto = !options.skyboxSize;
  110618. if (conf.color) {
  110619. options.skyboxColor = new babylonjs_1.Color3(conf.color.r, conf.color.g, conf.color.b);
  110620. }
  110621. if (conf.cubeTexture && conf.cubeTexture.url) {
  110622. if (typeof conf.cubeTexture.url === "string") {
  110623. options.skyboxTexture = this.labs.getAssetUrl(conf.cubeTexture.url);
  110624. }
  110625. else {
  110626. // init later!
  110627. postInitSkyboxMaterial = true;
  110628. }
  110629. }
  110630. if (conf.material) {
  110631. postInitSkyboxMaterial = true;
  110632. }
  110633. }
  110634. options.setupImageProcessing = false; // TMP
  110635. if (!this.environmentHelper) {
  110636. this.environmentHelper = this.scene.createDefaultEnvironment(options);
  110637. }
  110638. else {
  110639. // unlikely, but there might be a new scene! we need to dispose.
  110640. // get the scene used by the envHelper
  110641. var scene = this.environmentHelper.rootMesh.getScene();
  110642. // is it a different scene? Oh no!
  110643. if (scene !== this.scene) {
  110644. this.environmentHelper.dispose();
  110645. this.environmentHelper = this.scene.createDefaultEnvironment(options);
  110646. }
  110647. else {
  110648. //this.environmentHelper.updateOptions(options)!;
  110649. // update doesn't change the size of the skybox and ground, so we have to recreate!
  110650. this.environmentHelper.dispose();
  110651. this.environmentHelper = this.scene.createDefaultEnvironment(options);
  110652. }
  110653. }
  110654. if (this.environmentHelper.rootMesh && this._globalConfiguration.scene && this._globalConfiguration.scene.environmentRotationY !== undefined) {
  110655. this.environmentHelper.rootMesh.rotation.y = this._globalConfiguration.scene.environmentRotationY;
  110656. }
  110657. var groundConfig = (typeof groundConfiguration === 'boolean') ? {} : groundConfiguration;
  110658. if (this.environmentHelper.groundMaterial && groundConfig) {
  110659. this.environmentHelper.groundMaterial._perceptualColor = this.mainColor;
  110660. if (groundConfig.material) {
  110661. helper_1.extendClassWithConfig(this.environmentHelper.groundMaterial, groundConfig.material);
  110662. }
  110663. if (this.environmentHelper.groundMirror) {
  110664. var mirrorClearColor = this.environmentHelper.groundMaterial._perceptualColor.toLinearSpace();
  110665. // TODO user camera exposure value to set the mirror clear color
  110666. var exposure = Math.pow(2.0, -this.scene.imageProcessingConfiguration.exposure) * Math.PI;
  110667. mirrorClearColor.scaleToRef(1 / exposure, mirrorClearColor);
  110668. this.environmentHelper.groundMirror.clearColor.r = babylonjs_1.Scalar.Clamp(mirrorClearColor.r);
  110669. this.environmentHelper.groundMirror.clearColor.g = babylonjs_1.Scalar.Clamp(mirrorClearColor.g);
  110670. this.environmentHelper.groundMirror.clearColor.b = babylonjs_1.Scalar.Clamp(mirrorClearColor.b);
  110671. this.environmentHelper.groundMirror.clearColor.a = 1;
  110672. if (!this.groundMirrorEnabled) {
  110673. this.environmentHelper.groundMaterial.reflectionTexture = null;
  110674. }
  110675. }
  110676. }
  110677. var skyboxMaterial = this.environmentHelper.skyboxMaterial;
  110678. if (skyboxMaterial) {
  110679. skyboxMaterial._perceptualColor = this.mainColor;
  110680. if (postInitSkyboxMaterial) {
  110681. if (typeof skyboxConifguration === 'object' && skyboxConifguration.material) {
  110682. helper_1.extendClassWithConfig(skyboxMaterial, skyboxConifguration.material);
  110683. }
  110684. }
  110685. }
  110686. }
  110687. this._observablesManager && this._observablesManager.onModelLoadedObservable.add(function (model) {
  110688. _this._updateGroundMirrorRenderList(model);
  110689. });
  110690. this.onEnvironmentConfiguredObservable.notifyObservers({
  110691. sceneManager: this,
  110692. object: this.environmentHelper,
  110693. newConfiguration: {
  110694. skybox: skyboxConifguration,
  110695. ground: groundConfiguration
  110696. }
  110697. });
  110698. };
  110699. /**
  110700. * configure the lights.
  110701. *
  110702. * @param lightsConfiguration the (new) light(s) configuration
  110703. * @param model optionally use the model to configure the camera.
  110704. */
  110705. SceneManager.prototype._configureLights = function (lightsConfiguration) {
  110706. var _this = this;
  110707. if (lightsConfiguration === void 0) { lightsConfiguration = {}; }
  110708. // sanity check!
  110709. var lightKeys = Object.keys(lightsConfiguration).filter(function (name) { return name !== 'globalRotation'; });
  110710. if (!lightKeys.length) {
  110711. if (!this.scene.lights.length)
  110712. this.scene.createDefaultLight(true);
  110713. }
  110714. else {
  110715. var lightsAvailable_1 = this.scene.lights.map(function (light) { return light.name; });
  110716. // compare to the global (!) configuration object and dispose unneeded:
  110717. var lightsToConfigure_1 = Object.keys(this._globalConfiguration.lights || []);
  110718. if (Object.keys(lightsToConfigure_1).length !== lightsAvailable_1.length) {
  110719. lightsAvailable_1.forEach(function (lName) {
  110720. if (lightsToConfigure_1.indexOf(lName) === -1) {
  110721. _this.scene.getLightByName(lName).dispose();
  110722. }
  110723. });
  110724. }
  110725. lightKeys.forEach(function (name, idx) {
  110726. var lightConfig = { type: 0 };
  110727. if (typeof lightsConfiguration[name] === 'object') {
  110728. lightConfig = lightsConfiguration[name];
  110729. }
  110730. if (typeof lightsConfiguration[name] === 'number') {
  110731. lightConfig.type = lightsConfiguration[name];
  110732. }
  110733. lightConfig.name = name;
  110734. var light;
  110735. // light is not already available
  110736. if (lightsAvailable_1.indexOf(name) === -1) {
  110737. var constructor = babylonjs_1.Light.GetConstructorFromName(lightConfig.type, lightConfig.name, _this.scene);
  110738. if (!constructor)
  110739. return;
  110740. light = constructor();
  110741. }
  110742. else {
  110743. // available? get it from the scene
  110744. light = _this.scene.getLightByName(name);
  110745. if (typeof lightsConfiguration[name] === 'boolean') {
  110746. lightConfig.type = light.getTypeID();
  110747. }
  110748. lightsAvailable_1 = lightsAvailable_1.filter(function (ln) { return ln !== name; });
  110749. if (lightConfig.type !== undefined && light.getTypeID() !== lightConfig.type) {
  110750. light.dispose();
  110751. var constructor = babylonjs_1.Light.GetConstructorFromName(lightConfig.type, lightConfig.name, _this.scene);
  110752. if (!constructor)
  110753. return;
  110754. light = constructor();
  110755. }
  110756. }
  110757. // if config set the light to false, dispose it.
  110758. if (lightsConfiguration[name] === false) {
  110759. light.dispose();
  110760. return;
  110761. }
  110762. //enabled
  110763. var enabled = lightConfig.enabled !== undefined ? lightConfig.enabled : !lightConfig.disabled;
  110764. light.setEnabled(enabled);
  110765. helper_1.extendClassWithConfig(light, lightConfig);
  110766. //position. Some lights don't support shadows
  110767. if (light instanceof babylonjs_1.ShadowLight) {
  110768. // set default values
  110769. light.shadowMinZ = light.shadowMinZ || 0.2;
  110770. light.shadowMaxZ = Math.min(10, light.shadowMaxZ || 10); //large far clips reduce shadow depth precision
  110771. if (lightConfig.target) {
  110772. if (light.setDirectionToTarget) {
  110773. var target = babylonjs_1.Vector3.Zero().copyFrom(lightConfig.target);
  110774. light.setDirectionToTarget(target);
  110775. }
  110776. }
  110777. else if (lightConfig.direction) {
  110778. var direction = babylonjs_1.Vector3.Zero().copyFrom(lightConfig.direction);
  110779. light.direction = direction;
  110780. }
  110781. var isShadowEnabled = false;
  110782. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  110783. light.shadowFrustumSize = lightConfig.shadowFrustumSize || 2;
  110784. isShadowEnabled = true;
  110785. }
  110786. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  110787. var spotLight = light;
  110788. if (lightConfig.spotAngle !== undefined) {
  110789. spotLight.angle = lightConfig.spotAngle * Math.PI / 180;
  110790. }
  110791. if (spotLight.angle && lightConfig.shadowFieldOfView) {
  110792. spotLight.shadowAngleScale = lightConfig.shadowFieldOfView / spotLight.angle;
  110793. }
  110794. isShadowEnabled = true;
  110795. }
  110796. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  110797. if (lightConfig.shadowFieldOfView) {
  110798. light.shadowAngle = lightConfig.shadowFieldOfView * Math.PI / 180;
  110799. }
  110800. isShadowEnabled = true;
  110801. }
  110802. var shadowGenerator_1 = light.getShadowGenerator();
  110803. if (isShadowEnabled && lightConfig.shadowEnabled && _this._maxShadows) {
  110804. var bufferSize = lightConfig.shadowBufferSize || 256;
  110805. if (!shadowGenerator_1) {
  110806. shadowGenerator_1 = new babylonjs_1.ShadowGenerator(bufferSize, light);
  110807. }
  110808. var blurKernel = _this.getBlurKernel(light, bufferSize);
  110809. shadowGenerator_1.bias = _this._shadowGeneratorBias;
  110810. shadowGenerator_1.blurKernel = blurKernel;
  110811. //override defaults
  110812. helper_1.extendClassWithConfig(shadowGenerator_1, lightConfig.shadowConfig || {});
  110813. // add the focues meshes to the shadow list
  110814. _this._observablesManager && _this._observablesManager.onModelLoadedObservable.add(function (model) {
  110815. _this._updateShadowRenderList(shadowGenerator_1, model);
  110816. });
  110817. //if (model) {
  110818. _this._updateShadowRenderList(shadowGenerator_1);
  110819. //}
  110820. }
  110821. else if (shadowGenerator_1) {
  110822. shadowGenerator_1.dispose();
  110823. }
  110824. }
  110825. });
  110826. // render priority
  110827. var globalLightsConfiguration_1 = this._globalConfiguration.lights || {};
  110828. Object.keys(globalLightsConfiguration_1).sort().forEach(function (name, idx) {
  110829. var configuration = globalLightsConfiguration_1[name];
  110830. var light = _this.scene.getLightByName(name);
  110831. // sanity check
  110832. if (!light)
  110833. return;
  110834. light.renderPriority = -idx;
  110835. });
  110836. }
  110837. this.onLightsConfiguredObservable.notifyObservers({
  110838. sceneManager: this,
  110839. object: this.scene.lights,
  110840. newConfiguration: lightsConfiguration
  110841. });
  110842. };
  110843. SceneManager.prototype._updateShadowRenderList = function (shadowGenerator, model, resetList) {
  110844. var focusMeshes = model ? model.meshes : this.scene.meshes;
  110845. // add the focues meshes to the shadow list
  110846. var shadownMap = shadowGenerator.getShadowMap();
  110847. if (!shadownMap)
  110848. return;
  110849. if (resetList && shadownMap.renderList) {
  110850. shadownMap.renderList.length = 0;
  110851. }
  110852. else {
  110853. shadownMap.renderList = shadownMap.renderList || [];
  110854. }
  110855. for (var index = 0; index < focusMeshes.length; index++) {
  110856. var mesh = focusMeshes[index];
  110857. if (babylonjs_1.Tags.MatchesQuery(mesh, 'castShadow') && shadownMap.renderList.indexOf(mesh) === -1) {
  110858. shadownMap.renderList.push(mesh);
  110859. }
  110860. }
  110861. if (!this._shadowGroundPlane) {
  110862. if (shadowGenerator.useBlurCloseExponentialShadowMap) {
  110863. var shadowGroundPlane = babylonjs_1.Mesh.CreatePlane("shadowGroundPlane", 100, this.scene, false);
  110864. shadowGroundPlane.useVertexColors = false;
  110865. //material isn't ever used in rendering, just used to set back face culling
  110866. shadowGroundPlane.material = new babylonjs_1.StandardMaterial('shadowGroundPlaneMaterial', this.scene);
  110867. shadowGroundPlane.material.backFaceCulling = false;
  110868. shadowGroundPlane.rotation.x = Math.PI * 0.5;
  110869. shadowGroundPlane.freezeWorldMatrix();
  110870. this._shadowGroundPlane = shadowGroundPlane;
  110871. this.scene.removeMesh(shadowGroundPlane);
  110872. }
  110873. }
  110874. else {
  110875. if (!shadowGenerator.useBlurCloseExponentialShadowMap) {
  110876. this._shadowGroundPlane.dispose();
  110877. this._shadowGroundPlane = null;
  110878. }
  110879. }
  110880. if (this._shadowGroundPlane && shadownMap.renderList.indexOf(this._shadowGroundPlane) === -1) {
  110881. shadownMap.renderList.push(this._shadowGroundPlane);
  110882. }
  110883. };
  110884. SceneManager.prototype._updateGroundMirrorRenderList = function (model, resetList) {
  110885. if (this.environmentHelper.groundMirror && this.environmentHelper.groundMirror.renderList) {
  110886. var focusMeshes = model ? model.meshes : this.scene.meshes;
  110887. var renderList = this.environmentHelper.groundMirror.renderList;
  110888. if (resetList) {
  110889. renderList.length = 0;
  110890. }
  110891. for (var index = 0; index < focusMeshes.length; index++) {
  110892. var mesh = focusMeshes[index];
  110893. if (renderList.indexOf(mesh) === -1) {
  110894. renderList.push(mesh);
  110895. }
  110896. }
  110897. }
  110898. };
  110899. /**
  110900. * Gets the shadow map blur kernel according to the light configuration.
  110901. * @param light The light used to generate the shadows
  110902. * @param bufferSize The size of the shadow map
  110903. * @return the kernel blur size
  110904. */
  110905. SceneManager.prototype.getBlurKernel = function (light, bufferSize) {
  110906. var normalizedBlurKernel = 0.05; // TODO Should come from the config.
  110907. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  110908. normalizedBlurKernel = normalizedBlurKernel / light.shadowFrustumSize;
  110909. }
  110910. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  110911. normalizedBlurKernel = normalizedBlurKernel / light.shadowAngle;
  110912. }
  110913. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  110914. normalizedBlurKernel = normalizedBlurKernel / (light.angle * light.shadowAngleScale);
  110915. }
  110916. var minimumBlurKernel = 5 / (bufferSize / 256); //magic number that aims to keep away sawtooth shadows
  110917. var blurKernel = Math.max(bufferSize * normalizedBlurKernel, minimumBlurKernel);
  110918. return blurKernel;
  110919. };
  110920. /**
  110921. * Alters render settings to reduce features based on hardware feature limitations
  110922. * @param enableHDR Allows the viewer to run in HDR mode.
  110923. */
  110924. SceneManager.prototype._handleHardwareLimitations = function (enableHDR) {
  110925. if (enableHDR === void 0) { enableHDR = true; }
  110926. //flip rendering settings switches based on hardware support
  110927. var maxVaryingRows = this._engine.getCaps().maxVaryingVectors;
  110928. var maxFragmentSamplers = this._engine.getCaps().maxTexturesImageUnits;
  110929. //shadows are disabled if there's not enough varyings for a single shadow
  110930. if ((maxVaryingRows < 8) || (maxFragmentSamplers < 8)) {
  110931. this._maxShadows = 0;
  110932. }
  110933. else {
  110934. this._maxShadows = 3;
  110935. }
  110936. //can we render to any >= 16-bit targets (required for HDR)
  110937. var caps = this._engine.getCaps();
  110938. var linearHalfFloatTargets = caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering;
  110939. var linearFloatTargets = caps.textureFloatRender && caps.textureFloatLinearFiltering;
  110940. this._hdrSupport = enableHDR && !!(linearFloatTargets || linearHalfFloatTargets);
  110941. if (linearHalfFloatTargets) {
  110942. this._defaultHighpTextureType = babylonjs_1.Engine.TEXTURETYPE_HALF_FLOAT;
  110943. this._shadowGeneratorBias = 0.002;
  110944. }
  110945. else if (linearFloatTargets) {
  110946. this._defaultHighpTextureType = babylonjs_1.Engine.TEXTURETYPE_FLOAT;
  110947. this._shadowGeneratorBias = 0.001;
  110948. }
  110949. else {
  110950. this._defaultHighpTextureType = babylonjs_1.Engine.TEXTURETYPE_UNSIGNED_INT;
  110951. this._shadowGeneratorBias = 0.001;
  110952. }
  110953. this._defaultPipelineTextureType = this._hdrSupport ? this._defaultHighpTextureType : babylonjs_1.Engine.TEXTURETYPE_UNSIGNED_INT;
  110954. };
  110955. /**
  110956. * Dispoe the entire viewer including the scene and the engine
  110957. */
  110958. SceneManager.prototype.dispose = function () {
  110959. // this.onCameraConfiguredObservable.clear();
  110960. this.onEnvironmentConfiguredObservable.clear();
  110961. this.onLightsConfiguredObservable.clear();
  110962. this.onModelsConfiguredObservable.clear();
  110963. this.onSceneConfiguredObservable.clear();
  110964. this.onSceneInitObservable.clear();
  110965. this.onSceneOptimizerConfiguredObservable.clear();
  110966. if (this.sceneOptimizer) {
  110967. this.sceneOptimizer.stop();
  110968. this.sceneOptimizer.dispose();
  110969. }
  110970. if (this.environmentHelper) {
  110971. this.environmentHelper.dispose();
  110972. }
  110973. this.models.forEach(function (model) {
  110974. model.dispose();
  110975. });
  110976. if (this._defaultRenderingPipeline) {
  110977. this._defaultRenderingPipeline.dispose();
  110978. }
  110979. this.models.length = 0;
  110980. if (this.scene) {
  110981. this.scene.dispose();
  110982. }
  110983. };
  110984. SceneManager.prototype._setCameraBehavior = function (name, behaviorConfig, payload) {
  110985. var behavior;
  110986. var type;
  110987. if (typeof behaviorConfig === 'object') {
  110988. type = behaviorConfig.type;
  110989. }
  110990. else if (typeof behaviorConfig === 'number') {
  110991. type = behaviorConfig;
  110992. }
  110993. else {
  110994. type = this._cameraBehaviorMapping[name];
  110995. }
  110996. if (type === undefined)
  110997. return;
  110998. var config = (typeof behaviorConfig === "object") ? behaviorConfig : {};
  110999. var enabled = true;
  111000. if (typeof behaviorConfig === 'boolean') {
  111001. enabled = behaviorConfig;
  111002. }
  111003. // constructing behavior
  111004. switch (type) {
  111005. case 0 /* AUTOROTATION */:
  111006. this.camera.useAutoRotationBehavior = enabled;
  111007. behavior = this.camera.autoRotationBehavior;
  111008. break;
  111009. case 1 /* BOUNCING */:
  111010. this.camera.useBouncingBehavior = enabled;
  111011. behavior = this.camera.bouncingBehavior;
  111012. break;
  111013. case 2 /* FRAMING */:
  111014. this.camera.useFramingBehavior = enabled;
  111015. behavior = this.camera.framingBehavior;
  111016. break;
  111017. default:
  111018. behavior = null;
  111019. break;
  111020. }
  111021. if (behavior) {
  111022. this._cameraBehaviorMapping[name] = type;
  111023. if (typeof behaviorConfig === "object") {
  111024. helper_1.extendClassWithConfig(behavior, behaviorConfig);
  111025. }
  111026. }
  111027. // post attach configuration. Some functionalities require the attached camera.
  111028. switch (type) {
  111029. case 0 /* AUTOROTATION */:
  111030. break;
  111031. case 1 /* BOUNCING */:
  111032. break;
  111033. case 2 /* FRAMING */:
  111034. this._observablesManager && this._observablesManager.onModelLoadedObservable.add(function (model) {
  111035. if (config.zoomOnBoundingInfo) {
  111036. behavior.zoomOnMeshHierarchy(model.rootMesh);
  111037. }
  111038. });
  111039. break;
  111040. }
  111041. };
  111042. return SceneManager;
  111043. }());
  111044. exports.SceneManager = SceneManager;
  111045. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoic2NlbmVNYW5hZ2VyLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vLi4vc3JjL21hbmFnZXJzL3NjZW5lTWFuYWdlci50cyJdLCJuYW1lcyI6W10sIm1hcHBp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UIsQ0FBQyx1QkFBdUIsQ0FBQyxHQUFHLENBQUMsVUFBQyxLQUFLO29CQUNuRixJQUFJLE1BQU0sQ0FBQyxrQkFBa0IsRUFBRTt3QkFDVCxRQUFTLENBQUMsbUJBQW1CLENBQUMsS0FBSyxDQUFDLFFBQVEsQ0FBQyxDQUFDO3FCQUNuRTtnQkFDTCxDQUFDLENBQUMsQ0FBQztnQkFDSCxNQUFNO1NBQ2I7SUFDTCxDQUFDO0lBQ0wsbUJBQUM7QUFBRCxDQUFDLEFBOTJDRCxJQTgyQ0M7QUE5MkNZLG9DQUFZIn0=
  111046. /***/ }),
  111047. /* 23 */
  111048. /***/ (function(module, exports, __webpack_require__) {
  111049. "use strict";
  111050. Object.defineProperty(exports, "__esModule", { value: true });
  111051. /**
  111052. * The GroupModelAnimation is an implementation of the IModelAnimation interface using BABYLON's
  111053. * native GroupAnimation class.
  111054. */
  111055. var GroupModelAnimation = /** @class */ (function () {
  111056. /**
  111057. * Create a new GroupModelAnimation object using an AnimationGroup object
  111058. * @param _animationGroup The aniamtion group to base the class on
  111059. */
  111060. function GroupModelAnimation(_animationGroup) {
  111061. var _this = this;
  111062. this._animationGroup = _animationGroup;
  111063. this._state = 0 /* INIT */;
  111064. this._playMode = 1 /* LOOP */;
  111065. this._animationGroup.onAnimationEndObservable.add(function () {
  111066. _this.stop();
  111067. _this._state = 4 /* ENDED */;
  111068. });
  111069. }
  111070. Object.defineProperty(GroupModelAnimation.prototype, "name", {
  111071. /**
  111072. * Get the animation's name
  111073. */
  111074. get: function () {
  111075. return this._animationGroup.name;
  111076. },
  111077. enumerable: true,
  111078. configurable: true
  111079. });
  111080. Object.defineProperty(GroupModelAnimation.prototype, "state", {
  111081. /**
  111082. * Get the current animation's state
  111083. */
  111084. get: function () {
  111085. return this._state;
  111086. },
  111087. enumerable: true,
  111088. configurable: true
  111089. });
  111090. Object.defineProperty(GroupModelAnimation.prototype, "speedRatio", {
  111091. /**
  111092. * Gets the speed ratio to use for all animations
  111093. */
  111094. get: function () {
  111095. return this._animationGroup.speedRatio;
  111096. },
  111097. /**
  111098. * Sets the speed ratio to use for all animations
  111099. */
  111100. set: function (value) {
  111101. this._animationGroup.speedRatio = value;
  111102. },
  111103. enumerable: true,
  111104. configurable: true
  111105. });
  111106. Object.defineProperty(GroupModelAnimation.prototype, "frames", {
  111107. /**
  111108. * Get the max numbers of frame available in the animation group
  111109. *
  111110. * In correlation to an arry, this would be ".length"
  111111. */
  111112. get: function () {
  111113. return this._animationGroup.to - this._animationGroup.from;
  111114. },
  111115. enumerable: true,
  111116. configurable: true
  111117. });
  111118. Object.defineProperty(GroupModelAnimation.prototype, "currentFrame", {
  111119. /**
  111120. * Get the current frame playing right now.
  111121. * This can be used to poll the frame currently playing (and, for exmaple, display a progress bar with the data)
  111122. *
  111123. * In correlation to an array, this would be the current index
  111124. */
  111125. get: function () {
  111126. if (this._animationGroup.targetedAnimations[0] && this._animationGroup.targetedAnimations[0].animation.runtimeAnimations[0]) {
  111127. return this._animationGroup.targetedAnimations[0].animation.runtimeAnimations[0].currentFrame - this._animationGroup.from;
  111128. }
  111129. else {
  111130. return 0;
  111131. }
  111132. },
  111133. enumerable: true,
  111134. configurable: true
  111135. });
  111136. Object.defineProperty(GroupModelAnimation.prototype, "fps", {
  111137. /**
  111138. * Get the FPS value of this animation
  111139. */
  111140. get: function () {
  111141. // get the first currentFrame found
  111142. for (var i = 0; i < this._animationGroup.animatables.length; ++i) {
  111143. var animatable = this._animationGroup.animatables[i];
  111144. var animations = animatable.getAnimations();
  111145. if (!animations || !animations.length) {
  111146. continue;
  111147. }
  111148. for (var idx = 0; idx < animations.length; ++idx) {
  111149. if (animations[idx].animation && animations[idx].animation.framePerSecond) {
  111150. return animations[idx].animation.framePerSecond;
  111151. }
  111152. }
  111153. }
  111154. return 0;
  111155. },
  111156. enumerable: true,
  111157. configurable: true
  111158. });
  111159. Object.defineProperty(GroupModelAnimation.prototype, "playMode", {
  111160. /**
  111161. * What is the animation'S play mode (looping or played once)
  111162. */
  111163. get: function () {
  111164. return this._playMode;
  111165. },
  111166. /**
  111167. * Set the play mode.
  111168. * If the animation is played, it will continue playing at least once more, depending on the new play mode set.
  111169. * If the animation is not set, the will be initialized and will wait for the user to start playing it.
  111170. */
  111171. set: function (value) {
  111172. if (value === this._playMode) {
  111173. return;
  111174. }
  111175. this._playMode = value;
  111176. if (this.state === 1 /* PLAYING */) {
  111177. this._animationGroup.play(this._playMode === 1 /* LOOP */);
  111178. }
  111179. else {
  111180. this._animationGroup.reset();
  111181. this._state = 0 /* INIT */;
  111182. }
  111183. },
  111184. enumerable: true,
  111185. configurable: true
  111186. });
  111187. /**
  111188. * Reset the animation group
  111189. */
  111190. GroupModelAnimation.prototype.reset = function () {
  111191. this._animationGroup.reset();
  111192. };
  111193. /**
  111194. * Restart the animation group
  111195. */
  111196. GroupModelAnimation.prototype.restart = function () {
  111197. if (this.state === 2 /* PAUSED */)
  111198. this._animationGroup.restart();
  111199. else
  111200. this.start();
  111201. };
  111202. /**
  111203. *
  111204. * @param frameNumber Go to a specific frame in the animation
  111205. */
  111206. GroupModelAnimation.prototype.goToFrame = function (frameNumber) {
  111207. this._animationGroup.goToFrame(frameNumber + this._animationGroup.from);
  111208. };
  111209. /**
  111210. * Start playing the animation.
  111211. */
  111212. GroupModelAnimation.prototype.start = function () {
  111213. this._animationGroup.start(this.playMode === 1 /* LOOP */, this.speedRatio);
  111214. if (this._animationGroup.isStarted) {
  111215. this._state = 1 /* PLAYING */;
  111216. }
  111217. };
  111218. /**
  111219. * Pause the animation
  111220. */
  111221. GroupModelAnimation.prototype.pause = function () {
  111222. this._animationGroup.pause();
  111223. this._state = 2 /* PAUSED */;
  111224. };
  111225. /**
  111226. * Stop the animation.
  111227. * This will fail silently if the animation group is already stopped.
  111228. */
  111229. GroupModelAnimation.prototype.stop = function () {
  111230. this._animationGroup.stop();
  111231. if (!this._animationGroup.isStarted) {
  111232. this._state = 3 /* STOPPED */;
  111233. }
  111234. };
  111235. /**
  111236. * Dispose this animation object.
  111237. */
  111238. GroupModelAnimation.prototype.dispose = function () {
  111239. this._animationGroup.dispose();
  111240. };
  111241. return GroupModelAnimation;
  111242. }());
  111243. exports.GroupModelAnimation = GroupModelAnimation;
  111244. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoibW9kZWxBbmltYXRpb24uanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi9zcmMvbW9kZWwvbW9kZWxBbmltYXRpb24udHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUF3SUE7OztHQUdHO0FBQ0g7SUFLSTs7O09BR0c7SUFDSCw2QkFBb0IsZUFBK0I7UUFBbkQsaUJBUUM7UUFSbUIsb0JBQWUsR0FBZixlQUFlLENBQWdCO1FBQy9DLElBQUksQ0FBQyxNQUFNLGVBQXNCLENBQUM7UUFDbEMsSUFBSSxDQUFDLFNBQVMsZUFBeUIsQ0FBQztRQUV4QyxJQUFJLENBQUMsZUFBZSxDQUFDLHdCQUF3QixDQUFDLEdBQUcsQ0FBQztZQUM5QyxLQUFJLENBQUMsSUFBSSxFQUFFLENBQUM7WUFDWixLQUFJLENBQUMsTUFBTSxnQkFBdUIsQ0FBQztRQUN2QyxDQUFDLENBQUMsQ0FBQztJQUNQLENBQUM7SUFLRCxzQkFBVyxxQ0FBSTtRQUhmOztXQUVHO2FBQ0g7WUFDSSxPQUFPLElBQUksQ0FBQyxlQUFlLENBQUMsSUFBSSxDQUFDO1FBQ3JDLENBQUM7OztPQUFBO0lBS0Qsc0JBQVcsc0NBQUs7UUFIaEI7O1dBRUc7YUFDSDtZQUNJLE9BQU8sSUFBSSxDQUFDLE1BQU0sQ0FBQztRQUN2QixDQUFDOzs7T0FBQTtJQUtELHNCQUFXLDJDQUFVO1FBSHJCOztXQUVHO2FBQ0g7WUFDSSxPQUFPLElBQUksQ0FBQyxlQUFlLENBQUMsVUFBVSxDQUFDO1FBQzNDLEN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UFDO1FBQzVCLElBQUksQ0FBQyxJQUFJLENBQUMsZUFBZSxDQUFDLFNBQVMsRUFBRTtZQUNqQyxJQUFJLENBQUMsTUFBTSxrQkFBeUIsQ0FBQztTQUN4QztJQUNMLENBQUM7SUFFRDs7T0FFRztJQUNJLHFDQUFPLEdBQWQ7UUFDSSxJQUFJLENBQUMsZUFBZSxDQUFDLE9BQU8sRUFBRSxDQUFDO0lBQ25DLENBQUM7SUFDTCwwQkFBQztBQUFELENBQUMsQUFqTEQsSUFpTEM7QUFqTFksa0RBQW1CIn0=
  111245. /***/ }),
  111246. /* 24 */
  111247. /***/ (function(module, exports, __webpack_require__) {
  111248. "use strict";
  111249. Object.defineProperty(exports, "__esModule", { value: true });
  111250. var environmentSerializer_1 = __webpack_require__(25);
  111251. var babylonjs_1 = __webpack_require__(0);
  111252. var texture_1 = __webpack_require__(12);
  111253. /**
  111254. * The ViewerLabs class will hold functions that are not (!) backwards compatible.
  111255. * The APIs in all labs-related classes and configuration might change.
  111256. * Once stable, lab features will be moved to the publis API and configuration object.
  111257. */
  111258. var ViewerLabs = /** @class */ (function () {
  111259. function ViewerLabs(_scene) {
  111260. this._scene = _scene;
  111261. this.environment = {
  111262. //irradiance
  111263. irradiancePolynomialCoefficients: {
  111264. x: new babylonjs_1.Vector3(0, 0, 0),
  111265. y: new babylonjs_1.Vector3(0, 0, 0),
  111266. z: new babylonjs_1.Vector3(0, 0, 0),
  111267. xx: new babylonjs_1.Vector3(0, 0, 0),
  111268. yy: new babylonjs_1.Vector3(0, 0, 0),
  111269. zz: new babylonjs_1.Vector3(0, 0, 0),
  111270. yz: new babylonjs_1.Vector3(0, 0, 0),
  111271. zx: new babylonjs_1.Vector3(0, 0, 0),
  111272. xy: new babylonjs_1.Vector3(0, 0, 0)
  111273. },
  111274. textureIntensityScale: 1.0
  111275. };
  111276. }
  111277. ViewerLabs.prototype.loadEnvironment = function (data, onSuccess, onProgress, onError) {
  111278. var _this = this;
  111279. //@! todo: should loadEnvironment cancel any currently loading environments?
  111280. if (data instanceof ArrayBuffer) {
  111281. this.environment = environmentSerializer_1.EnvironmentDeserializer.Parse(data);
  111282. if (onSuccess)
  111283. onSuccess(this.environment);
  111284. }
  111285. else if (typeof data === 'string') {
  111286. var url = this.getAssetUrl(data);
  111287. this._scene._loadFile(url, function (arrayBuffer) {
  111288. _this.environment = environmentSerializer_1.EnvironmentDeserializer.Parse(arrayBuffer);
  111289. if (onSuccess)
  111290. onSuccess(_this.environment);
  111291. }, function (progressEvent) { if (onProgress)
  111292. onProgress(progressEvent.loaded, progressEvent.total); }, false, true, function (r, e) {
  111293. if (onError) {
  111294. onError(e);
  111295. }
  111296. });
  111297. }
  111298. else {
  111299. //data assumed to be PBREnvironment object
  111300. this.environment = data;
  111301. if (onSuccess)
  111302. onSuccess(data);
  111303. }
  111304. };
  111305. /**
  111306. * Applies an `EnvironmentMapConfiguration` to the scene
  111307. * @param environmentMapConfiguration Environment map configuration to apply
  111308. */
  111309. ViewerLabs.prototype.applyEnvironmentMapConfiguration = function (rotationY) {
  111310. if (!this.environment)
  111311. return;
  111312. //set orientation
  111313. var rotatquatRotationionY = babylonjs_1.Quaternion.RotationAxis(babylonjs_1.Axis.Y, rotationY || 0);
  111314. // Add env texture to the scene.
  111315. if (this.environment.specularTexture) {
  111316. // IE crashes when disposing the old texture and setting a new one
  111317. if (!this._scene.environmentTexture) {
  111318. this._scene.environmentTexture = texture_1.TextureUtils.GetBabylonCubeTexture(this._scene, this.environment.specularTexture, false, true);
  111319. }
  111320. if (this._scene.environmentTexture) {
  111321. this._scene.environmentTexture.level = this.environment.textureIntensityScale;
  111322. this._scene.environmentTexture.invertZ = true;
  111323. this._scene.environmentTexture.lodLevelInAlpha = true;
  111324. var poly = this._scene.environmentTexture.sphericalPolynomial || new babylonjs_1.SphericalPolynomial();
  111325. poly.x = this.environment.irradiancePolynomialCoefficients.x;
  111326. poly.y = this.environment.irradiancePolynomialCoefficients.y;
  111327. poly.z = this.environment.irradiancePolynomialCoefficients.z;
  111328. poly.xx = this.environment.irradiancePolynomialCoefficients.xx;
  111329. poly.xy = this.environment.irradiancePolynomialCoefficients.xy;
  111330. poly.yy = this.environment.irradiancePolynomialCoefficients.yy;
  111331. poly.yz = this.environment.irradiancePolynomialCoefficients.yz;
  111332. poly.zx = this.environment.irradiancePolynomialCoefficients.zx;
  111333. poly.zz = this.environment.irradiancePolynomialCoefficients.zz;
  111334. this._scene.environmentTexture.sphericalPolynomial = poly;
  111335. //set orientation
  111336. babylonjs_1.Matrix.FromQuaternionToRef(rotatquatRotationionY, this._scene.environmentTexture.getReflectionTextureMatrix());
  111337. }
  111338. }
  111339. };
  111340. /**
  111341. * Get an environment asset url by using the configuration if the path is not absolute.
  111342. * @param url Asset url
  111343. * @returns The Asset url using the `environmentAssetsRootURL` if the url is not an absolute path.
  111344. */
  111345. ViewerLabs.prototype.getAssetUrl = function (url) {
  111346. var returnUrl = url;
  111347. if (url && url.toLowerCase().indexOf("//") === -1) {
  111348. if (!this.assetsRootURL) {
  111349. // Tools.Warn("Please, specify the root url of your assets before loading the configuration (labs.environmentAssetsRootURL) or disable the background through the viewer options.");
  111350. return url;
  111351. }
  111352. returnUrl = this.assetsRootURL + returnUrl;
  111353. }
  111354. return returnUrl;
  111355. };
  111356. ViewerLabs.prototype.rotateShadowLight = function (shadowLight, amount, point, axis, target) {
  111357. if (point === void 0) { point = babylonjs_1.Vector3.Zero(); }
  111358. if (axis === void 0) { axis = babylonjs_1.Axis.Y; }
  111359. if (target === void 0) { target = babylonjs_1.Vector3.Zero(); }
  111360. axis.normalize();
  111361. point.subtractToRef(shadowLight.position, babylonjs_1.Tmp.Vector3[0]);
  111362. 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]);
  111363. babylonjs_1.Tmp.Matrix[0].invertToRef(babylonjs_1.Tmp.Matrix[2]);
  111364. babylonjs_1.Matrix.RotationAxisToRef(axis, amount, babylonjs_1.Tmp.Matrix[1]);
  111365. babylonjs_1.Tmp.Matrix[2].multiplyToRef(babylonjs_1.Tmp.Matrix[1], babylonjs_1.Tmp.Matrix[2]);
  111366. babylonjs_1.Tmp.Matrix[2].multiplyToRef(babylonjs_1.Tmp.Matrix[0], babylonjs_1.Tmp.Matrix[2]);
  111367. babylonjs_1.Tmp.Matrix[2].decompose(babylonjs_1.Tmp.Vector3[0], babylonjs_1.Tmp.Quaternion[0], babylonjs_1.Tmp.Vector3[1]);
  111368. shadowLight.position.addInPlace(babylonjs_1.Tmp.Vector3[1]);
  111369. shadowLight.setDirectionToTarget(target);
  111370. };
  111371. return ViewerLabs;
  111372. }());
  111373. exports.ViewerLabs = ViewerLabs;
  111374. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidmlld2VyTGFicy5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uL3NyYy9sYWJzL3ZpZXdlckxhYnMudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFBQSxpRUFBa0Y7QUFFbEYsdUNBQW1IO0FBQ25ILHFDQUF5QztBQUV6Qzs7OztHQUlHO0FBQ0g7SUFFSSxvQkFBb0IsTUFBYTtRQUFiLFdBQU0sR0FBTixNQUFNLENBQU87UUFHMUIsZ0JBQVcsR0FBbUI7WUFDakMsWUFBWTtZQUNaLGdDQUFnQyxFQUFFO2dCQUM5QixDQUFDLEVBQUUsSUFBSSxtQkFBTyxDQUFDLENBQUMsRUFBRSxDQUFDLEVBQUUsQ0FBQyxDQUFDO2dCQUN2QixDQUFDLEVBQUUsSUFBSSxtQkFBTyxDQUFDLENBQUMsRUFBRSxDQUFDLEVBQUUsQ0FBQyxDQUFDO2dCQUN2QixDQUFDLEVBQUUsSUFBSSxtQkFBTyxDQUFDLENBQUMsRUFBRSxDQUFDLEVBQUUsQ0FBQyx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E1BQU0sQ0FBQyxDQUFDLENBQUMsQ0FBQyxhQUFhLENBQUMsZUFBRyxDQUFDLE1BQU0sQ0FBQyxDQUFDLENBQUMsRUFBRSxlQUFHLENBQUMsTUFBTSxDQUFDLENBQUMsQ0FBQyxDQUFDLENBQUM7UUFDMUQsZUFBRyxDQUFDLE1BQU0sQ0FBQyxDQUFDLENBQUMsQ0FBQyxhQUFhLENBQUMsZUFBRyxDQUFDLE1BQU0sQ0FBQyxDQUFDLENBQUMsRUFBRSxlQUFHLENBQUMsTUFBTSxDQUFDLENBQUMsQ0FBQyxDQUFDLENBQUM7UUFFMUQsZUFBRyxDQUFDLE1BQU0sQ0FBQyxDQUFDLENBQUMsQ0FBQyxTQUFTLENBQUMsZUFBRyxDQUFDLE9BQU8sQ0FBQyxDQUFDLENBQUMsRUFBRSxlQUFHLENBQUMsVUFBVSxDQUFDLENBQUMsQ0FBQyxFQUFFLGVBQUcsQ0FBQyxPQUFPLENBQUMsQ0FBQyxDQUFDLENBQUMsQ0FBQztRQUUzRSxXQUFXLENBQUMsUUFBUSxDQUFDLFVBQVUsQ0FBQyxlQUFHLENBQUMsT0FBTyxDQUFDLENBQUMsQ0FBQyxDQUFDLENBQUM7UUFFaEQsV0FBVyxDQUFDLG9CQUFvQixDQUFDLE1BQU0sQ0FBQyxDQUFDO0lBQzdDLENBQUM7SUFFTCxpQkFBQztBQUFELENBQUMsQUFySkQsSUFxSkM7QUFySlksZ0NBQVUifQ==
  111375. /***/ }),
  111376. /* 25 */
  111377. /***/ (function(module, exports, __webpack_require__) {
  111378. "use strict";
  111379. Object.defineProperty(exports, "__esModule", { value: true });
  111380. var babylonjs_1 = __webpack_require__(0);
  111381. var texture_1 = __webpack_require__(12);
  111382. /**
  111383. * A static class proving methods to aid parsing Spectre environment files
  111384. */
  111385. var EnvironmentDeserializer = /** @class */ (function () {
  111386. function EnvironmentDeserializer() {
  111387. }
  111388. /**
  111389. * Parses an arraybuffer into a new PBREnvironment object
  111390. * @param arrayBuffer The arraybuffer of the Spectre environment file
  111391. * @return a PBREnvironment object
  111392. */
  111393. EnvironmentDeserializer.Parse = function (arrayBuffer) {
  111394. var environment = {
  111395. //irradiance
  111396. irradiancePolynomialCoefficients: {
  111397. x: new babylonjs_1.Vector3(0, 0, 0),
  111398. y: new babylonjs_1.Vector3(0, 0, 0),
  111399. z: new babylonjs_1.Vector3(0, 0, 0),
  111400. xx: new babylonjs_1.Vector3(0, 0, 0),
  111401. yy: new babylonjs_1.Vector3(0, 0, 0),
  111402. zz: new babylonjs_1.Vector3(0, 0, 0),
  111403. yz: new babylonjs_1.Vector3(0, 0, 0),
  111404. zx: new babylonjs_1.Vector3(0, 0, 0),
  111405. xy: new babylonjs_1.Vector3(0, 0, 0)
  111406. },
  111407. //specular
  111408. textureIntensityScale: 1.0,
  111409. };
  111410. //read .env
  111411. var littleEndian = false;
  111412. var magicBytes = [0x86, 0x16, 0x87, 0x96, 0xf6, 0xd6, 0x96, 0x36];
  111413. var dataView = new DataView(arrayBuffer);
  111414. var pos = 0;
  111415. for (var i = 0; i < magicBytes.length; i++) {
  111416. if (dataView.getUint8(pos++) !== magicBytes[i]) {
  111417. babylonjs_1.Tools.Error('Not a Spectre environment map');
  111418. }
  111419. }
  111420. var version = dataView.getUint16(pos, littleEndian);
  111421. pos += 2;
  111422. if (version !== 1) {
  111423. babylonjs_1.Tools.Warn('Unsupported Spectre environment map version "' + version + '"');
  111424. }
  111425. //read json descriptor - collect characters up to null terminator
  111426. var descriptorString = '';
  111427. var charCode = 0x00;
  111428. while ((charCode = dataView.getUint8(pos++))) {
  111429. descriptorString += String.fromCharCode(charCode);
  111430. }
  111431. var descriptor = JSON.parse(descriptorString);
  111432. var payloadPos = pos;
  111433. //irradiance
  111434. switch (descriptor.irradiance.type) {
  111435. case 'irradiance_sh_coefficients_9':
  111436. //irradiance
  111437. var harmonics = descriptor.irradiance;
  111438. EnvironmentDeserializer._ConvertSHIrradianceToLambertianRadiance(harmonics);
  111439. //harmonics now represent radiance
  111440. EnvironmentDeserializer._ConvertSHToSP(harmonics, environment.irradiancePolynomialCoefficients);
  111441. break;
  111442. default:
  111443. babylonjs_1.Tools.Error('Unhandled MapType descriptor.irradiance.type (' + descriptor.irradiance.type + ')');
  111444. }
  111445. //specular
  111446. switch (descriptor.specular.type) {
  111447. case 'cubemap_faces':
  111448. var specularDescriptor = descriptor.specular;
  111449. var specularTexture = environment.specularTexture = new texture_1.TextureCube(6408 /* RGBA */, 5121 /* UNSIGNED_BYTE */);
  111450. environment.textureIntensityScale = specularDescriptor.multiplier != null ? specularDescriptor.multiplier : 1.0;
  111451. var mipmaps = specularDescriptor.mipmaps;
  111452. var imageType = specularDescriptor.imageType;
  111453. for (var l = 0; l < mipmaps.length; l++) {
  111454. var faceRanges = mipmaps[l];
  111455. specularTexture.source[l] = [];
  111456. for (var i = 0; i < 6; i++) {
  111457. var range = faceRanges[i];
  111458. var bytes = new Uint8Array(arrayBuffer, payloadPos + range.pos, range.length);
  111459. switch (imageType) {
  111460. case 'png':
  111461. //construct image element from bytes
  111462. var image = new Image();
  111463. var src = URL.createObjectURL(new Blob([bytes], { type: 'image/png' }));
  111464. image.src = src;
  111465. specularTexture.source[l][i] = image;
  111466. break;
  111467. default:
  111468. babylonjs_1.Tools.Error('Unhandled ImageType descriptor.specular.imageType (' + imageType + ')');
  111469. }
  111470. }
  111471. }
  111472. break;
  111473. default:
  111474. babylonjs_1.Tools.Error('Unhandled MapType descriptor.specular.type (' + descriptor.specular.type + ')');
  111475. }
  111476. return environment;
  111477. };
  111478. /**
  111479. * Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  111480. * L = (1/pi) * E * rho
  111481. *
  111482. * This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  111483. * @param harmonics Spherical harmonic coefficients (9)
  111484. */
  111485. EnvironmentDeserializer._ConvertSHIrradianceToLambertianRadiance = function (harmonics) {
  111486. EnvironmentDeserializer._ScaleSH(harmonics, 1 / Math.PI);
  111487. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  111488. // (The pixel shader must apply albedo after texture fetches, etc).
  111489. };
  111490. /**
  111491. * Convert spherical harmonics to spherical polynomial coefficients
  111492. * @param harmonics Spherical harmonic coefficients (9)
  111493. * @param outPolynomialCoefficents Polynomial coefficients (9) object to store result
  111494. */
  111495. EnvironmentDeserializer._ConvertSHToSP = function (harmonics, outPolynomialCoefficents) {
  111496. var rPi = 1 / Math.PI;
  111497. //x
  111498. outPolynomialCoefficents.x.x = 1.02333 * harmonics.l11[0] * rPi;
  111499. outPolynomialCoefficents.x.y = 1.02333 * harmonics.l11[1] * rPi;
  111500. outPolynomialCoefficents.x.z = 1.02333 * harmonics.l11[2] * rPi;
  111501. outPolynomialCoefficents.y.x = 1.02333 * harmonics.l1_1[0] * rPi;
  111502. outPolynomialCoefficents.y.y = 1.02333 * harmonics.l1_1[1] * rPi;
  111503. outPolynomialCoefficents.y.z = 1.02333 * harmonics.l1_1[2] * rPi;
  111504. outPolynomialCoefficents.z.x = 1.02333 * harmonics.l10[0] * rPi;
  111505. outPolynomialCoefficents.z.y = 1.02333 * harmonics.l10[1] * rPi;
  111506. outPolynomialCoefficents.z.z = 1.02333 * harmonics.l10[2] * rPi;
  111507. //xx
  111508. outPolynomialCoefficents.xx.x = (0.886277 * harmonics.l00[0] - 0.247708 * harmonics.l20[0] + 0.429043 * harmonics.l22[0]) * rPi;
  111509. outPolynomialCoefficents.xx.y = (0.886277 * harmonics.l00[1] - 0.247708 * harmonics.l20[1] + 0.429043 * harmonics.l22[1]) * rPi;
  111510. outPolynomialCoefficents.xx.z = (0.886277 * harmonics.l00[2] - 0.247708 * harmonics.l20[2] + 0.429043 * harmonics.l22[2]) * rPi;
  111511. outPolynomialCoefficents.yy.x = (0.886277 * harmonics.l00[0] - 0.247708 * harmonics.l20[0] - 0.429043 * harmonics.l22[0]) * rPi;
  111512. outPolynomialCoefficents.yy.y = (0.886277 * harmonics.l00[1] - 0.247708 * harmonics.l20[1] - 0.429043 * harmonics.l22[1]) * rPi;
  111513. outPolynomialCoefficents.yy.z = (0.886277 * harmonics.l00[2] - 0.247708 * harmonics.l20[2] - 0.429043 * harmonics.l22[2]) * rPi;
  111514. outPolynomialCoefficents.zz.x = (0.886277 * harmonics.l00[0] + 0.495417 * harmonics.l20[0]) * rPi;
  111515. outPolynomialCoefficents.zz.y = (0.886277 * harmonics.l00[1] + 0.495417 * harmonics.l20[1]) * rPi;
  111516. outPolynomialCoefficents.zz.z = (0.886277 * harmonics.l00[2] + 0.495417 * harmonics.l20[2]) * rPi;
  111517. //yz
  111518. outPolynomialCoefficents.yz.x = 0.858086 * harmonics.l2_1[0] * rPi;
  111519. outPolynomialCoefficents.yz.y = 0.858086 * harmonics.l2_1[1] * rPi;
  111520. outPolynomialCoefficents.yz.z = 0.858086 * harmonics.l2_1[2] * rPi;
  111521. outPolynomialCoefficents.zx.x = 0.858086 * harmonics.l21[0] * rPi;
  111522. outPolynomialCoefficents.zx.y = 0.858086 * harmonics.l21[1] * rPi;
  111523. outPolynomialCoefficents.zx.z = 0.858086 * harmonics.l21[2] * rPi;
  111524. outPolynomialCoefficents.xy.x = 0.858086 * harmonics.l2_2[0] * rPi;
  111525. outPolynomialCoefficents.xy.y = 0.858086 * harmonics.l2_2[1] * rPi;
  111526. outPolynomialCoefficents.xy.z = 0.858086 * harmonics.l2_2[2] * rPi;
  111527. };
  111528. /**
  111529. * Multiplies harmonic coefficients in place
  111530. * @param harmonics Spherical harmonic coefficients (9)
  111531. * @param scaleFactor Value to multiply by
  111532. */
  111533. EnvironmentDeserializer._ScaleSH = function (harmonics, scaleFactor) {
  111534. harmonics.l00[0] *= scaleFactor;
  111535. harmonics.l00[1] *= scaleFactor;
  111536. harmonics.l00[2] *= scaleFactor;
  111537. harmonics.l1_1[0] *= scaleFactor;
  111538. harmonics.l1_1[1] *= scaleFactor;
  111539. harmonics.l1_1[2] *= scaleFactor;
  111540. harmonics.l10[0] *= scaleFactor;
  111541. harmonics.l10[1] *= scaleFactor;
  111542. harmonics.l10[2] *= scaleFactor;
  111543. harmonics.l11[0] *= scaleFactor;
  111544. harmonics.l11[1] *= scaleFactor;
  111545. harmonics.l11[2] *= scaleFactor;
  111546. harmonics.l2_2[0] *= scaleFactor;
  111547. harmonics.l2_2[1] *= scaleFactor;
  111548. harmonics.l2_2[2] *= scaleFactor;
  111549. harmonics.l2_1[0] *= scaleFactor;
  111550. harmonics.l2_1[1] *= scaleFactor;
  111551. harmonics.l2_1[2] *= scaleFactor;
  111552. harmonics.l20[0] *= scaleFactor;
  111553. harmonics.l20[1] *= scaleFactor;
  111554. harmonics.l20[2] *= scaleFactor;
  111555. harmonics.l21[0] *= scaleFactor;
  111556. harmonics.l21[1] *= scaleFactor;
  111557. harmonics.l21[2] *= scaleFactor;
  111558. harmonics.l22[0] *= scaleFactor;
  111559. harmonics.l22[1] *= scaleFactor;
  111560. harmonics.l22[2] *= scaleFactor;
  111561. };
  111562. return EnvironmentDeserializer;
  111563. }());
  111564. exports.EnvironmentDeserializer = EnvironmentDeserializer;
  111565. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZW52aXJvbm1lbnRTZXJpYWxpemVyLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vLi4vc3JjL2xhYnMvZW52aXJvbm1lbnRTZXJpYWxpemVyLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7O0FBQUEsdUNBQTJDO0FBQzNDLHFDQUFnRTtBQW1IaEU7O0dBRUc7QUFDSDtJQUFBO0lBcU5BLENBQUM7SUFuTkc7Ozs7T0FJRztJQUNXLDZCQUFLLEdBQW5CLFVBQW9CLFdBQXdCO1FBQ3hDLElBQUksV0FBVyxHQUFtQjtZQUM5QixZQUFZO1lBQ1osZ0NBQWdDLEVBQUU7Z0JBQzlCLENBQUMsRUFBRSxJQUFJLG1CQUFPLENBQUM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yxTQUFTLENBQUMsR0FBRyxDQUFDLENBQUMsQ0FBQyxJQUFJLFdBQVcsQ0FBQztRQUNoQyxTQUFTLENBQUMsR0FBRyxDQUFDLENBQUMsQ0FBQyxJQUFJLFdBQVcsQ0FBQztRQUNoQyxTQUFTLENBQUMsR0FBRyxDQUFDLENBQUMsQ0FBQyxJQUFJLFdBQVcsQ0FBQztRQUNoQyxTQUFTLENBQUMsR0FBRyxDQUFDLENBQUMsQ0FBQyxJQUFJLFdBQVcsQ0FBQztRQUNoQyxTQUFTLENBQUMsR0FBRyxDQUFDLENBQUMsQ0FBQyxJQUFJLFdBQVcsQ0FBQztRQUNoQyxTQUFTLENBQUMsR0FBRyxDQUFDLENBQUMsQ0FBQyxJQUFJLFdBQVcsQ0FBQztRQUNoQyxTQUFTLENBQUMsR0FBRyxDQUFDLENBQUMsQ0FBQyxJQUFJLFdBQVcsQ0FBQztRQUNoQyxTQUFTLENBQUMsR0FBRyxDQUFDLENBQUMsQ0FBQyxJQUFJLFdBQVcsQ0FBQztRQUNoQyxTQUFTLENBQUMsR0FBRyxDQUFDLENBQUMsQ0FBQyxJQUFJLFdBQVcsQ0FBQztJQUNwQyxDQUFDO0lBQ0wsOEJBQUM7QUFBRCxDQUFDLEFBck5ELElBcU5DO0FBck5ZLDBEQUF1QiJ9
  111566. /***/ }),
  111567. /* 26 */
  111568. /***/ (function(module, exports, __webpack_require__) {
  111569. "use strict";
  111570. Object.defineProperty(exports, "__esModule", { value: true });
  111571. var extended_1 = __webpack_require__(27);
  111572. var cache = {};
  111573. /**
  111574. *
  111575. * @param name the name of the custom optimizer configuration
  111576. * @param upgrade set to true if you want to upgrade optimizer and false if you want to degrade
  111577. */
  111578. function getCustomOptimizerByName(name, upgrade) {
  111579. if (!cache[name]) {
  111580. switch (name) {
  111581. case 'extended':
  111582. if (upgrade) {
  111583. return extended_1.extendedUpgrade;
  111584. }
  111585. else {
  111586. return extended_1.extendedDegrade;
  111587. }
  111588. }
  111589. }
  111590. return cache[name];
  111591. }
  111592. exports.getCustomOptimizerByName = getCustomOptimizerByName;
  111593. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi8uLi9zcmMvb3B0aW1pemVyL2N1c3RvbS9pbmRleC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUFBLHVDQUE4RDtBQUc5RCxJQUFNLEtBQUssR0FBK0QsRUFBRSxDQUFDO0FBRTdFOzs7O0dBSUc7QUFDSCxrQ0FBeUMsSUFBWSxFQUFFLE9BQWlCO0lBQ3BFLElBQUksQ0FBQyxLQUFLLENBQUMsSUFBSSxDQUFDLEVBQUU7UUFDZCxRQUFRLElBQUksRUFBRTtZQUNWLEtBQUssVUFBVTtnQkFDWCxJQUFJLE9BQU8sRUFBRTtvQkFDVCxPQUFPLDBCQUFlLENBQUM7aUJBQzFCO3FCQUNJO29CQUNELE9BQU8sMEJBQWUsQ0FBQztpQkFDMUI7U0FDUjtLQUNKO0lBRUQsT0FBTyxLQUFLLENBQUMsSUFBSSxDQUFDLENBQUM7QUFDdkIsQ0FBQztBQWRELDREQWNDIn0=
  111594. /***/ }),
  111595. /* 27 */
  111596. /***/ (function(module, exports, __webpack_require__) {
  111597. "use strict";
  111598. Object.defineProperty(exports, "__esModule", { value: true });
  111599. var babylonjs_1 = __webpack_require__(0);
  111600. /**
  111601. * A custom upgrade-oriented function configuration for the scene optimizer.
  111602. *
  111603. * @param viewer the viewer to optimize
  111604. */
  111605. function extendedUpgrade(sceneManager) {
  111606. var defaultPipeline = sceneManager.defaultRenderingPipeline;
  111607. // if (!this.Scene.BackgroundHelper) {
  111608. // this.Scene.EngineScene.autoClear = false;
  111609. // this.Scene.BackgroundHelper = true;
  111610. // Would require a dedicated clear color;
  111611. // return false;
  111612. // }
  111613. if (sceneManager.scene.getEngine().getHardwareScalingLevel() > 1) {
  111614. var scaling = babylonjs_1.Scalar.Clamp(sceneManager.scene.getEngine().getHardwareScalingLevel() - 0.25, 0, 1);
  111615. sceneManager.scene.getEngine().setHardwareScalingLevel(scaling);
  111616. return false;
  111617. }
  111618. if (!sceneManager.scene.postProcessesEnabled) {
  111619. sceneManager.scene.postProcessesEnabled = true;
  111620. return false;
  111621. }
  111622. if (!sceneManager.groundEnabled) {
  111623. sceneManager.groundEnabled = true;
  111624. return false;
  111625. }
  111626. if (defaultPipeline && !sceneManager.fxaaEnabled) {
  111627. sceneManager.fxaaEnabled = true;
  111628. return false;
  111629. }
  111630. var hardwareScalingLevel = Math.max(1 / 2, 1 / (window.devicePixelRatio || 2));
  111631. if (sceneManager.scene.getEngine().getHardwareScalingLevel() > hardwareScalingLevel) {
  111632. var scaling = babylonjs_1.Scalar.Clamp(sceneManager.scene.getEngine().getHardwareScalingLevel() - 0.25, 0, hardwareScalingLevel);
  111633. sceneManager.scene.getEngine().setHardwareScalingLevel(scaling);
  111634. return false;
  111635. }
  111636. if (!sceneManager.processShadows) {
  111637. sceneManager.processShadows = true;
  111638. return false;
  111639. }
  111640. if (defaultPipeline && !sceneManager.bloomEnabled) {
  111641. sceneManager.bloomEnabled = true;
  111642. return false;
  111643. }
  111644. if (!sceneManager.groundMirrorEnabled) {
  111645. sceneManager.groundMirrorEnabled = true;
  111646. return false;
  111647. }
  111648. return true;
  111649. }
  111650. exports.extendedUpgrade = extendedUpgrade;
  111651. /**
  111652. * A custom degrade-oriented function configuration for the scene optimizer.
  111653. *
  111654. * @param viewer the viewer to optimize
  111655. */
  111656. function extendedDegrade(sceneManager) {
  111657. var defaultPipeline = sceneManager.defaultRenderingPipeline;
  111658. if (sceneManager.groundMirrorEnabled) {
  111659. sceneManager.groundMirrorEnabled = false;
  111660. return false;
  111661. }
  111662. if (defaultPipeline && sceneManager.bloomEnabled) {
  111663. sceneManager.bloomEnabled = false;
  111664. return false;
  111665. }
  111666. if (sceneManager.processShadows) {
  111667. sceneManager.processShadows = false;
  111668. return false;
  111669. }
  111670. if (sceneManager.scene.getEngine().getHardwareScalingLevel() < 1) {
  111671. var scaling = babylonjs_1.Scalar.Clamp(sceneManager.scene.getEngine().getHardwareScalingLevel() + 0.25, 0, 1);
  111672. sceneManager.scene.getEngine().setHardwareScalingLevel(scaling);
  111673. return false;
  111674. }
  111675. if (defaultPipeline && sceneManager.fxaaEnabled) {
  111676. sceneManager.fxaaEnabled = false;
  111677. return false;
  111678. }
  111679. if (sceneManager.groundEnabled) {
  111680. sceneManager.groundEnabled = false;
  111681. return false;
  111682. }
  111683. if (sceneManager.scene.postProcessesEnabled) {
  111684. sceneManager.scene.postProcessesEnabled = false;
  111685. return false;
  111686. }
  111687. if (sceneManager.scene.getEngine().getHardwareScalingLevel() < 1.25) {
  111688. var scaling = babylonjs_1.Scalar.Clamp(sceneManager.scene.getEngine().getHardwareScalingLevel() + 0.25, 0, 1.25);
  111689. sceneManager.scene.getEngine().setHardwareScalingLevel(scaling);
  111690. return false;
  111691. }
  111692. // if (this.Scene.BackgroundHelper) {
  111693. // this.Scene.EngineScene.autoClear = true;
  111694. // this.Scene.BackgroundHelper = false;
  111695. // Would require a dedicated clear color;
  111696. // return false;
  111697. // }
  111698. return true;
  111699. }
  111700. exports.extendedDegrade = extendedDegrade;
  111701. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZXh0ZW5kZWQuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi8uLi9zcmMvb3B0aW1pemVyL2N1c3RvbS9leHRlbmRlZC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUFBLHVDQUFvRTtBQUdwRTs7OztHQUlHO0FBQ0gseUJBQWdDLFlBQTBCO0lBQ3RELElBQUksZUFBZSxHQUE2QixZQUFZLENBQUMsd0JBQXdCLENBQUM7SUFDdEYsc0NBQXNDO0lBQ3RDLDZDQUE2QztJQUM3QyxzQ0FBc0M7SUFD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DLG9CQUFvQixHQUFHLEtBQUssQ0FBQztRQUNoRCxPQUFPLEtBQUssQ0FBQztLQUNoQjtJQUNELElBQUksWUFBWSxDQUFDLEtBQUssQ0FBQyxTQUFTLEVBQUUsQ0FBQyx1QkFBdUIsRUFBRSxHQUFHLElBQUksRUFBRTtRQUNqRSxJQUFJLE9BQU8sR0FBRyxrQkFBTSxDQUFDLEtBQUssQ0FBQyxZQUFZLENBQUMsS0FBSyxDQUFDLFNBQVMsRUFBRSxDQUFDLHVCQUF1QixFQUFFLEdBQUcsSUFBSSxFQUFFLENBQUMsRUFBRSxJQUFJLENBQUMsQ0FBQztRQUNyRyxZQUFZLENBQUMsS0FBSyxDQUFDLFNBQVMsRUFBRSxDQUFDLHVCQUF1QixDQUFDLE9BQU8sQ0FBQyxDQUFDO1FBQ2hFLE9BQU8sS0FBSyxDQUFDO0tBQ2hCO0lBQ0QscUNBQXFDO0lBQ3JDLDRDQUE0QztJQUM1Qyx1Q0FBdUM7SUFDdkMseUNBQXlDO0lBQ3pDLGdCQUFnQjtJQUNoQixJQUFJO0lBQ0osT0FBTyxJQUFJLENBQUM7QUFDaEIsQ0FBQztBQTVDRCwwQ0E0Q0MifQ==
  111702. /***/ }),
  111703. /* 28 */
  111704. /***/ (function(module, exports, __webpack_require__) {
  111705. "use strict";
  111706. Object.defineProperty(exports, "__esModule", { value: true });
  111707. var mappers_1 = __webpack_require__(3);
  111708. var types_1 = __webpack_require__(29);
  111709. var configurationCompatibility_1 = __webpack_require__(53);
  111710. var _1 = __webpack_require__(1);
  111711. var babylonjs_1 = __webpack_require__(0);
  111712. /**
  111713. * The configuration loader will load the configuration object from any source and will use the defined mapper to
  111714. * parse the object and return a conform ViewerConfiguration.
  111715. * It is a private member of the scene.
  111716. */
  111717. var ConfigurationLoader = /** @class */ (function () {
  111718. function ConfigurationLoader(_enableCache) {
  111719. if (_enableCache === void 0) { _enableCache = false; }
  111720. this._enableCache = _enableCache;
  111721. this._configurationCache = {};
  111722. this._loadRequests = [];
  111723. }
  111724. /**
  111725. * load a configuration object that is defined in the initial configuration provided.
  111726. * The viewer configuration can extend different types of configuration objects and have an extra configuration defined.
  111727. *
  111728. * @param initConfig the initial configuration that has the definitions of further configuration to load.
  111729. * @param callback an optional callback that will be called sync, if noconfiguration needs to be loaded or configuration is payload-only
  111730. * @returns A promise that delivers the extended viewer configuration, when done.
  111731. */
  111732. ConfigurationLoader.prototype.loadConfiguration = function (initConfig, callback) {
  111733. var _this = this;
  111734. if (initConfig === void 0) { initConfig = {}; }
  111735. var loadedConfig = _1.deepmerge({}, initConfig);
  111736. var extendedConfiguration = types_1.getConfigurationType(loadedConfig.extends || "");
  111737. if (loadedConfig.configuration) {
  111738. var mapperType_1 = "json";
  111739. return Promise.resolve().then(function () {
  111740. if (typeof loadedConfig.configuration === "string" || (loadedConfig.configuration && loadedConfig.configuration.url)) {
  111741. // a file to load
  111742. var url = '';
  111743. if (typeof loadedConfig.configuration === "string") {
  111744. url = loadedConfig.configuration;
  111745. }
  111746. // if configuration is an object
  111747. if (typeof loadedConfig.configuration === "object" && loadedConfig.configuration.url) {
  111748. url = loadedConfig.configuration.url;
  111749. var type = loadedConfig.configuration.mapper;
  111750. // empty string?
  111751. if (!type) {
  111752. // load mapper type from filename / url
  111753. type = loadedConfig.configuration.url.split('.').pop();
  111754. }
  111755. mapperType_1 = type || mapperType_1;
  111756. }
  111757. return _this._loadFile(url);
  111758. }
  111759. else {
  111760. if (typeof loadedConfig.configuration === "object") {
  111761. mapperType_1 = loadedConfig.configuration.mapper || mapperType_1;
  111762. return loadedConfig.configuration.payload || {};
  111763. }
  111764. return {};
  111765. }
  111766. }).then(function (data) {
  111767. var mapper = mappers_1.mapperManager.getMapper(mapperType_1);
  111768. var parsed = _1.deepmerge(mapper.map(data), loadedConfig);
  111769. var merged = _1.deepmerge(extendedConfiguration, parsed);
  111770. configurationCompatibility_1.processConfigurationCompatibility(merged);
  111771. if (callback)
  111772. callback(merged);
  111773. return merged;
  111774. });
  111775. }
  111776. else {
  111777. loadedConfig = _1.deepmerge(extendedConfiguration, loadedConfig);
  111778. configurationCompatibility_1.processConfigurationCompatibility(loadedConfig);
  111779. if (callback)
  111780. callback(loadedConfig);
  111781. return Promise.resolve(loadedConfig);
  111782. }
  111783. };
  111784. /**
  111785. * Dispose the configuration loader. This will cancel file requests, if active.
  111786. */
  111787. ConfigurationLoader.prototype.dispose = function () {
  111788. this._loadRequests.forEach(function (request) {
  111789. request.abort();
  111790. });
  111791. this._loadRequests.length = 0;
  111792. };
  111793. ConfigurationLoader.prototype._loadFile = function (url) {
  111794. var _this = this;
  111795. var cacheReference = this._configurationCache;
  111796. if (this._enableCache && cacheReference[url]) {
  111797. return Promise.resolve(cacheReference[url]);
  111798. }
  111799. return new Promise(function (resolve, reject) {
  111800. var fileRequest = babylonjs_1.Tools.LoadFile(url, function (result) {
  111801. var idx = _this._loadRequests.indexOf(fileRequest);
  111802. if (idx !== -1)
  111803. _this._loadRequests.splice(idx, 1);
  111804. if (_this._enableCache)
  111805. cacheReference[url] = result;
  111806. resolve(result);
  111807. }, undefined, undefined, false, function (request, error) {
  111808. var idx = _this._loadRequests.indexOf(fileRequest);
  111809. if (idx !== -1)
  111810. _this._loadRequests.splice(idx, 1);
  111811. reject(error);
  111812. });
  111813. _this._loadRequests.push(fileRequest);
  111814. });
  111815. };
  111816. return ConfigurationLoader;
  111817. }());
  111818. exports.ConfigurationLoader = ConfigurationLoader;
  111819. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoibG9hZGVyLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vLi4vc3JjL2NvbmZpZ3VyYXRpb24vbG9hZGVyLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7O0FBQUEscUNBQTBDO0FBRTFDLGlDQUErQztBQUMvQywyRUFBaUY7QUFFakYsK0JBQXVDO0FBQ3ZDLHVDQUFnRDtBQUVoRDs7OztHQ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/***/ (function(module, exports, __webpack_require__) {
  111823. "use strict";
  111824. Object.defineProperty(exports, "__esModule", { value: true });
  111825. var minimal_1 = __webpack_require__(30);
  111826. exports.minimalConfiguration = minimal_1.minimalConfiguration;
  111827. var default_1 = __webpack_require__(49);
  111828. exports.defaultConfiguration = default_1.defaultConfiguration;
  111829. var extended_1 = __webpack_require__(50);
  111830. var shadowLight_1 = __webpack_require__(51);
  111831. var environmentMap_1 = __webpack_require__(52);
  111832. var _1 = __webpack_require__(1);
  111833. /**
  111834. * Get the configuration type you need to use as the base for your viewer.
  111835. * The types can either be a single string, or comma separated types that will extend each other. for example:
  111836. *
  111837. * "default, environmentMap" will first load the default configuration and will extend it using the environmentMap configuration.
  111838. *
  111839. * @param types a comma-separated string of the type(s) or configuration to load.
  111840. */
  111841. var getConfigurationType = function (types) {
  111842. var config = {};
  111843. var typesSeparated = types.split(",");
  111844. typesSeparated.forEach(function (type) {
  111845. switch (type.trim()) {
  111846. case 'environmentMap':
  111847. config = _1.deepmerge(config, environmentMap_1.environmentMapConfiguration);
  111848. break;
  111849. case 'shadowDirectionalLight':
  111850. config = _1.deepmerge(config, shadowLight_1.shadowDirectionalLightConfiguration);
  111851. break;
  111852. case 'shadowSpotLight':
  111853. config = _1.deepmerge(config, shadowLight_1.shadowSpotlLightConfiguration);
  111854. break;
  111855. case 'extended':
  111856. config = _1.deepmerge(config, extended_1.extendedConfiguration);
  111857. break;
  111858. case 'minimal':
  111859. config = _1.deepmerge(config, minimal_1.minimalConfiguration);
  111860. break;
  111861. case 'none':
  111862. break;
  111863. case 'default':
  111864. default:
  111865. config = _1.deepmerge(config, default_1.defaultConfiguration);
  111866. break;
  111867. }
  111868. if (config.extends) {
  111869. config = _1.deepmerge(config, getConfigurationType(config.extends));
  111870. }
  111871. });
  111872. return config;
  111873. };
  111874. exports.getConfigurationType = getConfigurationType;
  111875. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJz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FBUztnQkFDVixNQUFNLEdBQUcsWUFBUyxDQUFDLE1BQU0sRUFBRSw4QkFBb0IsQ0FBQyxDQUFDO2dCQUNqRCxNQUFNO1lBQ1YsS0FBSyxNQUFNO2dCQUNQLE1BQU07WUFDVixLQUFLLFNBQVMsQ0FBQztZQUNmO2dCQUNJLE1BQU0sR0FBRyxZQUFTLENBQUMsTUFBTSxFQUFFLDhCQUFvQixDQUFDLENBQUM7Z0JBQ2pELE1BQU07U0FDYjtRQUVELElBQUksTUFBTSxDQUFDLE9BQU8sRUFBRTtZQUNoQixNQUFNLEdBQUcsWUFBUyxDQUFDLE1BQU0sRUFBRSxvQkFBb0IsQ0FBQyxNQUFNLENBQUMsT0FBTyxDQUFDLENBQUMsQ0FBQztTQUNwRTtJQUNMLENBQUMsQ0FBQyxDQUFDO0lBQ0gsT0FBTyxNQUFNLENBQUM7QUFFbEIsQ0FBQyxDQUFBO0FBRVEsb0RBQW9CIn0=
  111876. /***/ }),
  111877. /* 30 */
  111878. /***/ (function(module, exports, __webpack_require__) {
  111879. "use strict";
  111880. Object.defineProperty(exports, "__esModule", { value: true });
  111881. var babylonjs_viewer_assets_1 = __webpack_require__(2);
  111882. var babylonjs_viewer_assets_2 = __webpack_require__(2);
  111883. /**
  111884. * The minimal configuration needed to make the viewer work.
  111885. * Some functionalities might not work correctly (like fill-screen)
  111886. */
  111887. exports.minimalConfiguration = {
  111888. version: "0.1",
  111889. templates: {
  111890. main: {
  111891. html: babylonjs_viewer_assets_1.defaultTemplate
  111892. },
  111893. fillContainer: {
  111894. html: babylonjs_viewer_assets_1.fillContainer,
  111895. params: {
  111896. disable: false
  111897. }
  111898. },
  111899. loadingScreen: {
  111900. html: babylonjs_viewer_assets_1.loadingScreen,
  111901. params: {
  111902. backgroundColor: "#000000",
  111903. loadingImage: babylonjs_viewer_assets_2.loading
  111904. }
  111905. },
  111906. viewer: {
  111907. html: babylonjs_viewer_assets_1.defaultViewer,
  111908. },
  111909. overlay: {
  111910. html: babylonjs_viewer_assets_1.overlay,
  111911. params: {
  111912. closeImage: babylonjs_viewer_assets_2.close,
  111913. closeText: 'Close'
  111914. }
  111915. },
  111916. error: {
  111917. html: babylonjs_viewer_assets_1.error
  111918. }
  111919. },
  111920. engine: {
  111921. antialiasing: true
  111922. }
  111923. };
  111924. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoibWluaW1hbC5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uLy4uL3NyYy9jb25maWd1cmF0aW9uL3R5cGVzL21pbmltYWwudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFDQSxtRUFBdUg7QUFDdkgsbUVBQXlEO0FBRXpEOzs7R0FHRztBQUNRLFFBQUEsb0JBQW9CLEdBQXdCO0lBQ25ELE9BQU8sRUFBRSxLQUFLO0lBQ2QsU0FBUyxFQUFFO1FBQ1AsSUFBSSxFQUFFO1lBQ0YsSUFBSSxFQUFFLHlDQUFlO1NBQ3hCO1FBQ0QsYUFBYSxFQUFFO1lBQ1gsSUFBSSxFQUFFLHVDQUFhO1lBQ25CLE1BQU0sRUFBRTtnQkFDSixPQUFPLEVBQUUsS0FBSzthQUNqQjtTQUNKO1FBQ0QsYUFBYSxFQUFFO1lBQ1gsSUFBSSxFQUFFLHVDQUFhO1lBQ25CLE1BQU0sRUFBRTtnQkFDSixlQUFlLEVBQUUsU0FBUztnQkFDMUIsWUFBWSxFQUFFLGlDQUFPO2FBQ3hCO1NBQ0o7UUFDRCxNQUFNLEVBQUU7WUFDSixJQUFJLEVBQUUsdUNBQWE7U0FDdEI7UUFDRCxPQUFPLEVBQUU7WUFDTCxJQUFJLEVBQUUsaUNBQU87WUFDYixNQUFNLEVBQUU7Z0JBQ0osVUFBVSxFQUFFLCtCQUFLO2dCQUNqQixTQUFTLEVBQUUsT0FBTzthQUNyQjtTQUNKO1FBQ0QsS0FBSyxFQUFFO1lBQ0gsSUFBSSxFQUFFLCtCQUFLO1NBQ2Q7S0FFSjtJQUNELE1BQU0sRUFBRTtRQUNKLFlBQVksRUFBRSxJQUFJO0tBQ3JCO0NBQ0osQ0FBQSJ9
  111925. /***/ }),
  111926. /* 31 */
  111927. /***/ (function(module, exports, __webpack_require__) {
  111928. "use strict";
  111929. Object.defineProperty(exports, "__esModule", { value: true });
  111930. exports.babylonFont = __webpack_require__(32);
  111931. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZm9udC5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uL3NyYy9hc3NldHMvZm9udC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUFhLFFBQUEsV0FBVyxHQUFHLE9BQU8sQ0FBQywyQkFBMkIsQ0FBQyxDQUFDIn0=
  111932. /***/ }),
  111933. /* 32 */
  111934. /***/ (function(module, exports) {
  111935. module.exports = "data:application/font-woff;charset=utf-8;base64,d09GRgABAAAAABIgAA8AAAAAH7gAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABPUy8yAAABWAAAAEcAAABgSlp9rlZETVgAAAGgAAACBQAABeCBXolxY21hcAAAA6gAAABxAAAAsqyRvzljdnQgAAAEHAAAACAAAAAqCdkJr2ZwZ20AAAQ8AAAA8AAAAVn8nuaOZ2FzcAAABSwAAAAMAAAADAAIABtnbHlmAAAFOAAABlUAAAh+MHVDHWhlYWQAAAuQAAAAMgAAADb+LvI4aGhlYQAAC8QAAAAVAAAAJBABCAZobXR4AAAL3AAAACYAAAAqErQDvGxvY2EAAAwEAAAAIgAAACIJ6we4bWF4cAAADCgAAAAcAAAAIACJANFuYW1lAAAMRAAABTsAAAvzM/OUeXBvc3QAABGAAAAAEwAAACD/UQB3cHJlcAAAEZQAAACJAAAA03i98g542mNgZk9knMDAysDBOovVmIGBURpCM19kSGMS4mBl5WJkYgQDBiAQYEAA32AFBQYHBt7vwhxgPoRkA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o3ehnXnGFMJ9ndB7yHVrWyjDH4Ivg0ZdXMXNA3Ei9mIfwCJoYWxAHjaY2BmAIP/fgzlDFgAACkqAcgAeNrbwKDNsImRk0mbcRMXiNzO1ZobaqvKwKG9nTs12EFPBsTiifCw0JAEsXidzbXlhUEsPh0VGREeEItfTkKYjwPEEuDj4WRnAbEEwQDEEtowoSDAAMhi2M4IN5oJbjQz3GgWuNGscKPZ5CShRrPDjeaAG80JN3qTMCO79gYGBdfaTAkXAMQBKBoAAAA="
  111936. /***/ }),
  111937. /* 33 */
  111938. /***/ (function(module, exports, __webpack_require__) {
  111939. "use strict";
  111940. Object.defineProperty(exports, "__esModule", { value: true });
  111941. exports.babylonLogo = __webpack_require__(34);
  111942. exports.close = __webpack_require__(35);
  111943. exports.fullscreen = __webpack_require__(36);
  111944. exports.helpCircle = __webpack_require__(37);
  111945. exports.loading = __webpack_require__(38);
  111946. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW1nLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vLi4vc3JjL2Fzc2V0cy9pbWcudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFBYSxRQUFBLFdBQVcsR0FBRyxPQUFPLENBQUMsMkNBQTJDLENBQUMsQ0FBQztBQUNuRSxRQUFBLEtBQUssR0FBRyxPQUFPLENBQUMsNEJBQTRCLENBQUMsQ0FBQztBQUM5QyxRQUFBLFVBQVUsR0FBRyxPQUFPLENBQUMsaUNBQWlDLENBQUMsQ0FBQztBQUN4RCxRQUFBLFVBQVUsR0FBRyxPQUFPLENBQUMsa0NBQWtDLENBQUMsQ0FBQztBQUN6RCxRQUFBLE9BQU8sR0FBRyxPQUFPLENBQUMsOEJBQThCLENBQUMsQ0FBQyJ9
  111947. /***/ }),
  111948. /* 34 */
  111949. /***/ (function(module, exports) {
  111950. module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgA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/DYuUAnvl4wAAAACAw1BmAwAwBE2S8wP/f1phAwAAAMARKbMBABiKdZLTA/z/WGEDAAAAQA8oswEAGIpJkpt08/7sbUqBPY8VNgAAAAD0gjIbAIAhmSb51uL/3lVKib0ULQAAAAD0izIbAIChmSW5fMHff7/CblKW3gAAAABADymzAQAYoibJ+RP/HitsAAAAABgQZTYAAEO1TnL6i79ml/27sG9EBgAAAADDocwGAGCo3qQU2icP/HfX2Z8SBwAAAAAGSJkNAMCQnSX5evefrbABAAAAoCLKbAAAhu5dkkmssAEAAACgKv8F3qtfY+YVvDIAAAAASUVORK5CYII="
  111951. /***/ }),
  111952. /* 35 */
  111953. /***/ (function(module, exports) {
  111954. module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAQAAAD9CzEMAAAAt0lEQVR42u2WAQbDQBBFQ9IbRtDcrrqK3LBbXrEH6OuHEPMBjPd2xHyZKtdNpcLMg11Pr7y4/YdvwIdd4jtw4BU0Rjrbz9mNzkjzgpU3wNhCvH5M3i1fKzzeK3K8V+R4r8jxTpHjlULhc0WOd8fU6e4I8y3y13tFjHel4GswwAvFSR/ZN6Zv2gjvmzbGhwqPzxUenys83is8Pld4vFac/9sy8/SVNrbgYJl8WGhsvkpoA1+pVK6ZLyLNXm2txsT5AAAAAElFTkSuQmCC"
  111955. /***/ }),
  111956. /* 36 */
  111957. /***/ (function(module, exports) {
  111958. module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwAQAAAAB/ecQqAAAAAnRSTlMAAHaTzTgAAAAeSURBVHgBY6ASsP/A/wcXZQNGhCkyAfE24HUndQAAXlkXcQ24P7gAAAAASUVORK5CYII="
  111959. /***/ }),
  111960. /* 37 */
  111961. /***/ (function(module, exports) {
  111962. 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=="
  111963. /***/ }),
  111964. /* 38 */
  111965. /***/ (function(module, exports) {
  111966. module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAHgAAAB4CAYAAAA5ZDbSAAAStUlEQVR42uyaA7TrShiFn23btm3btm3btm3btm372LWd9+318nSRNk2mtz3trLXX5PbmZOafPT9nxmq1VmuKFggEZs1ms0uVSqUj8vn8Q/SP5nK5lRpMjFYLh8NTZTKZhSBxi2KxeDlEPgh+BQVrhKbfwDNgZf45QZ2J0mrxeHxGtHJRCDoUQm+FpLd4joKc5aKJaDbDNzxuZT3yyLg1FqPVWPip0un0PBCxMUScD+6wtTJr+dz49hdsmh14nMiAKK0WiUSmgbjFC4XCYSz2VeB9/p2wyaxJK9EY93set+dxwhYr1QU9U7B4s4CNIfMM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E8WCrDaqxfI2z976FlFzhWfG4B7VSvIvj5ZpNaMTbpbbda/fLknDDv09Sz2p9JsbqPYKRptRCLd1Dhj5Pe3CgL1P7ke1V5UfL/WHXiy5HrFWAyAG763EGXwfYVmhANDbd6Ogsokfaahw6k0h7hvDNEQ58KZYcQ5r7HFbbBz/wbO+YJZkavri9o3hyzAyobZwULtmyPgMR9lhWx71d0Z8Q7FauTlnVB3azWIGxux4G4KoWYNcGiX0n1ELr7CZwssRXgpzAp1vVYjodv39cYCdspILRaGjUsf/gHJaAWdrW+QG0Rv/QrFbPHSBywngFzzDeiEkB2zovybktEch90C9wcI/zQjSelhUQ3DJTkpdrCxwD+IJroCvCdPXnMAg2PLfDU6qoF/eX6TZVl8Lclzax0dsyrVqBpO4pqAQHcDecz3EvxQwkI16kGkp9m0v2ljxoU/UGfElBUCxYCMK/HKejMj5LpRriWVx1yNIgfmhyz+83U4WzFvDsAZUa1yYwfcLAh4P3kwI+S6RMybBcrHjKg8XQshTiOZESR+bS+prONUK1niITtvezTcAGYEid2zasSpGUY1ekSztpgRcpHpsK5co1er1YRDu6DelsCMOL5d6DmVo78FBgRzcRy+pgTzFeiqVq1Ki43KZo0b/wP23paVqC/D3gAAAABJRU5ErkJggg=="
  111967. /***/ }),
  111968. /* 39 */
  111969. /***/ (function(module, exports, __webpack_require__) {
  111970. "use strict";
  111971. Object.defineProperty(exports, "__esModule", { value: true });
  111972. exports.defaultTemplate = __webpack_require__(40);
  111973. exports.defaultViewer = __webpack_require__(41);
  111974. exports.error = __webpack_require__(42);
  111975. exports.fillContainer = __webpack_require__(43);
  111976. exports.help = __webpack_require__(44);
  111977. exports.loadingScreen = __webpack_require__(45);
  111978. exports.navbar = __webpack_require__(46);
  111979. exports.overlay = __webpack_require__(47);
  111980. exports.share = __webpack_require__(48);
  111981. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidGVtcGxhdGVzLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vLi4vc3JjL2Fzc2V0cy90ZW1wbGF0ZXMudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFBYSxRQUFBLGVBQWUsR0FBRyxPQUFPLENBQUMscURBQXFELENBQUMsQ0FBQztBQUNqRixRQUFBLGFBQWEsR0FBRyxPQUFPLENBQUMsbURBQW1ELENBQUMsQ0FBQztBQUM3RSxRQUFBLEtBQUssR0FBRyxPQUFPLENBQUMsMkNBQTJDLENBQUMsQ0FBQztBQUM3RCxRQUFBLGFBQWEsR0FBRyxPQUFPLENBQUMsbURBQW1ELENBQUMsQ0FBQztBQUM3RSxRQUFBLElBQUksR0FBRyxPQUFPLENBQUMsMENBQTBDLENBQUMsQ0FBQztBQUMzRCxRQUFBLGFBQWEsR0FBRyxPQUFPLENBQUMsbURBQW1ELENBQUMsQ0FBQztBQUM3RSxRQUFBLE1BQU0sR0FBRyxPQUFPLENBQUMsNENBQTRDLENBQUMsQ0FBQztBQUMvRCxRQUFBLE9BQU8sR0FBRyxPQUFPLENBQUMsNkNBQTZDLENBQUMsQ0FBQztBQUNqRSxRQUFBLEtBQUssR0FBRyxPQUFPLENBQUMsMkNBQTJDLENBQUMsQ0FBQyJ9
  111982. /***/ }),
  111983. /* 40 */
  111984. /***/ (function(module, exports) {
  111985. 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>";
  111986. /***/ }),
  111987. /* 41 */
  111988. /***/ (function(module, exports) {
  111989. 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>";
  111990. /***/ }),
  111991. /* 42 */
  111992. /***/ (function(module, exports) {
  111993. module.exports = "Error loading the model";
  111994. /***/ }),
  111995. /* 43 */
  111996. /***/ (function(module, exports) {
  111997. 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>";
  111998. /***/ }),
  111999. /* 44 */
  112000. /***/ (function(module, exports) {
  112001. module.exports = "HELP";
  112002. /***/ }),
  112003. /* 45 */
  112004. /***/ (function(module, exports) {
  112005. 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}}>";
  112006. /***/ }),
  112007. /* 46 */
  112008. /***/ (function(module, exports) {
  112009. 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>";
  112010. /***/ }),
  112011. /* 47 */
  112012. /***/ (function(module, exports) {
  112013. 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>";
  112014. /***/ }),
  112015. /* 48 */
  112016. /***/ (function(module, exports) {
  112017. module.exports = "SHARE";
  112018. /***/ }),
  112019. /* 49 */
  112020. /***/ (function(module, exports, __webpack_require__) {
  112021. "use strict";
  112022. Object.defineProperty(exports, "__esModule", { value: true });
  112023. var babylonjs_viewer_assets_1 = __webpack_require__(2);
  112024. var babylonjs_viewer_assets_2 = __webpack_require__(2);
  112025. var images = __webpack_require__(2);
  112026. /**
  112027. * The default configuration of the viewer, including templates (canvas, overly, loading screen)
  112028. * This configuration doesn't hold specific parameters, and only defines objects that are needed for the viewer to fully work correctly.
  112029. */
  112030. exports.defaultConfiguration = {
  112031. version: "3.2.0-alpha4",
  112032. templates: {
  112033. main: {
  112034. html: babylonjs_viewer_assets_1.defaultTemplate,
  112035. params: {
  112036. babylonFont: babylonjs_viewer_assets_2.babylonFont,
  112037. noEscape: true
  112038. }
  112039. },
  112040. fillContainer: {
  112041. html: babylonjs_viewer_assets_1.fillContainer,
  112042. params: {
  112043. disable: false
  112044. }
  112045. },
  112046. loadingScreen: {
  112047. html: babylonjs_viewer_assets_1.loadingScreen,
  112048. params: {
  112049. backgroundColor: "#000000",
  112050. loadingImage: images.loading
  112051. }
  112052. },
  112053. viewer: {
  112054. html: babylonjs_viewer_assets_1.defaultViewer,
  112055. params: {
  112056. enableDragAndDrop: false
  112057. }
  112058. },
  112059. navBar: {
  112060. html: babylonjs_viewer_assets_1.navbar,
  112061. params: {
  112062. speedList: {
  112063. "0.5x": "0.5",
  112064. "1.0x": "1.0",
  112065. "1.5x": "1.5",
  112066. "2.0x": "2.0",
  112067. },
  112068. logoImage: images.babylonLogo,
  112069. logoText: 'BabylonJS',
  112070. logoLink: 'https://babylonjs.com',
  112071. hideHelp: true,
  112072. disableOnFullscreen: false,
  112073. },
  112074. events: {
  112075. pointerdown: {
  112076. 'navbar-control': true,
  112077. 'help-button': true
  112078. },
  112079. input: {
  112080. 'progress-wrapper': true
  112081. },
  112082. pointerup: {
  112083. 'progress-wrapper': true
  112084. }
  112085. }
  112086. },
  112087. overlay: {
  112088. html: babylonjs_viewer_assets_1.overlay,
  112089. params: {
  112090. closeImage: images.close,
  112091. closeText: 'Close'
  112092. }
  112093. },
  112094. help: {
  112095. html: babylonjs_viewer_assets_1.help
  112096. },
  112097. share: {
  112098. html: babylonjs_viewer_assets_1.share
  112099. },
  112100. error: {
  112101. html: babylonjs_viewer_assets_1.error
  112102. }
  112103. },
  112104. camera: {
  112105. behaviors: {
  112106. autoRotate: {
  112107. type: 0
  112108. },
  112109. framing: {
  112110. type: 2,
  112111. zoomOnBoundingInfo: true,
  112112. zoomStopsAnimation: false
  112113. },
  112114. bouncing: {
  112115. type: 1
  112116. }
  112117. }
  112118. },
  112119. skybox: {},
  112120. ground: {
  112121. receiveShadows: true
  112122. },
  112123. engine: {
  112124. antialiasing: true
  112125. },
  112126. scene: {}
  112127. };
  112128. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZGVmYXVsdC5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uLy4uL3NyYy9jb25maWd1cmF0aW9uL3R5cGVzL2RlZmF1bHQudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFDQSxtRUFBNEk7QUFDNUksbUVBQXNEO0FBQ3RELGdEQUFrRDtBQUVsRDs7O0dBR0c7QUFDUSxRQUFBLG9CQUFvQixHQUF3QjtJQUNuRCxPQUFPLEVBQUUsY0FBYztJQUN2QixTQUFTLEVBQUU7UUFDUCxJQUFJLEVBQUU7WUFDRixJQUFJLEVBQUUseUNBQWU7WUFDckIsTUFBTSxFQUFFO2dCQUNKLFdBQVcsRUFBRSxxQ0FBVztnQkFDeEIsUUFBUSxFQUFFLElBQUk7YUFDakI7U0FDSjtRQUNELGFBQWEsRUFBRTtZQUNYLElBQUksRUFBRSx1Q0FBYTtZQUNuQixNQUFNLEVBQUU7Z0JBQ0osT0FBTyxFQUFFLEtBQ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FTLEVBQUUsT0FBTzthQUNyQjtTQUNKO1FBQ0QsSUFBSSxFQUFFO1lBQ0YsSUFBSSxFQUFFLDhCQUFJO1NBQ2I7UUFDRCxLQUFLLEVBQUU7WUFDSCxJQUFJLEVBQUUsK0JBQUs7U0FDZDtRQUNELEtBQUssRUFBRTtZQUNILElBQUksRUFBRSwrQkFBSztTQUNkO0tBRUo7SUFDRCxNQUFNLEVBQUU7UUFDSixTQUFTLEVBQUU7WUFDUCxVQUFVLEVBQUU7Z0JBQ1IsSUFBSSxFQUFFLENBQUM7YUFDVjtZQUNELE9BQU8sRUFBRTtnQkFDTCxJQUFJLEVBQUUsQ0FBQztnQkFDUCxrQkFBa0IsRUFBRSxJQUFJO2dCQUN4QixrQkFBa0IsRUFBRSxLQUFLO2FBQzVCO1lBQ0QsUUFBUSxFQUFFO2dCQUNOLElBQUksRUFBRSxDQUFDO2FBQ1Y7U0FDSjtLQUNKO0lBQ0QsTUFBTSxFQUFFLEVBQ1A7SUFDRCxNQUFNLEVBQUU7UUFDSixjQUFjLEVBQUUsSUFBSTtLQUN2QjtJQUNELE1BQU0sRUFBRTtRQUNKLFlBQVksRUFBRSxJQUFJO0tBQ3JCO0lBQ0QsS0FBSyxFQUFFLEVBQ047Q0FDSixDQUFBIn0=
  112129. /***/ }),
  112130. /* 50 */
  112131. /***/ (function(module, exports, __webpack_require__) {
  112132. "use strict";
  112133. Object.defineProperty(exports, "__esModule", { value: true });
  112134. var babylonjs_1 = __webpack_require__(0);
  112135. /**
  112136. * The viewer's "extended" configuration.
  112137. * This configuration defines specific obejcts and parameters that we think make any model look good.
  112138. */
  112139. exports.extendedConfiguration = {
  112140. version: "3.2.0",
  112141. extends: "default",
  112142. camera: {
  112143. exposure: 3.034578,
  112144. fov: 0.7853981633974483,
  112145. contrast: 1.6,
  112146. toneMappingEnabled: true,
  112147. upperBetaLimit: 1.3962634015954636 + Math.PI / 2,
  112148. lowerBetaLimit: -1.4835298641951802 + Math.PI / 2,
  112149. behaviors: {
  112150. framing: {
  112151. type: 2,
  112152. mode: 0,
  112153. positionScale: 0.5,
  112154. defaultElevation: 0.2617993877991494,
  112155. elevationReturnWaitTime: 3000,
  112156. elevationReturnTime: 2000,
  112157. framingTime: 500,
  112158. zoomStopsAnimation: false,
  112159. radiusScale: 0.866
  112160. },
  112161. autoRotate: {
  112162. type: 0,
  112163. idleRotationWaitTime: 4000,
  112164. idleRotationSpeed: 0.17453292519943295,
  112165. idleRotationSpinupTime: 2500,
  112166. zoomStopsAnimation: false
  112167. },
  112168. bouncing: {
  112169. type: 1,
  112170. lowerRadiusTransitionRange: 0.05,
  112171. upperRadiusTransitionRange: -0.2
  112172. }
  112173. },
  112174. upperRadiusLimit: 5,
  112175. lowerRadiusLimit: 0.5,
  112176. frameOnModelLoad: true,
  112177. framingElevation: 0.2617993877991494,
  112178. framingRotation: 1.5707963267948966,
  112179. radius: 2,
  112180. alpha: 1.5708,
  112181. beta: Math.PI * 0.5 - 0.2618,
  112182. wheelPrecision: 300,
  112183. minZ: 0.1,
  112184. maxZ: 50,
  112185. fovMode: 0,
  112186. pinchPrecision: 1500,
  112187. panningSensibility: 3000
  112188. },
  112189. lights: {
  112190. light0: {
  112191. type: 0,
  112192. frustumEdgeFalloff: 0,
  112193. intensity: 7,
  112194. intensityMode: 0,
  112195. radius: 0.6,
  112196. range: 0.6,
  112197. spotAngle: 60,
  112198. diffuse: {
  112199. r: 1,
  112200. g: 1,
  112201. b: 1
  112202. },
  112203. position: {
  112204. x: -2,
  112205. y: 2.5,
  112206. z: 2
  112207. },
  112208. target: {
  112209. x: 0,
  112210. y: 0,
  112211. z: 0
  112212. },
  112213. enabled: true,
  112214. shadowEnabled: true,
  112215. shadowBufferSize: 512,
  112216. shadowMinZ: 1,
  112217. shadowMaxZ: 10,
  112218. shadowFieldOfView: 60,
  112219. shadowFrustumSize: 2,
  112220. shadowConfig: {
  112221. useBlurCloseExponentialShadowMap: true,
  112222. useKernelBlur: true,
  112223. blurScale: 1.0,
  112224. bias: 0.001,
  112225. depthScale: 50 * (10 - 1),
  112226. frustumEdgeFalloff: 0
  112227. }
  112228. },
  112229. light1: {
  112230. type: 0,
  112231. frustumEdgeFalloff: 0,
  112232. intensity: 7,
  112233. intensityMode: 0,
  112234. radius: 0.4,
  112235. range: 0.4,
  112236. spotAngle: 57,
  112237. diffuse: {
  112238. r: 1,
  112239. g: 1,
  112240. b: 1
  112241. },
  112242. position: {
  112243. x: 4,
  112244. y: 3,
  112245. z: -0.5
  112246. },
  112247. target: {
  112248. x: 0,
  112249. y: 0,
  112250. z: 0
  112251. },
  112252. enabled: true,
  112253. shadowEnabled: false,
  112254. shadowBufferSize: 512,
  112255. shadowMinZ: 0.2,
  112256. shadowMaxZ: 10,
  112257. shadowFieldOfView: 28,
  112258. shadowFrustumSize: 2
  112259. },
  112260. light2: {
  112261. type: 0,
  112262. frustumEdgeFalloff: 0,
  112263. intensity: 1,
  112264. intensityMode: 0,
  112265. radius: 0.5,
  112266. range: 0.5,
  112267. spotAngle: 42.85,
  112268. diffuse: {
  112269. r: 0.8,
  112270. g: 0.8,
  112271. b: 0.8
  112272. },
  112273. position: {
  112274. x: -1,
  112275. y: 3,
  112276. z: -3
  112277. },
  112278. target: {
  112279. x: 0,
  112280. y: 0,
  112281. z: 0
  112282. },
  112283. enabled: true,
  112284. shadowEnabled: false,
  112285. shadowBufferSize: 512,
  112286. shadowMinZ: 0.2,
  112287. shadowMaxZ: 10,
  112288. shadowFieldOfView: 45,
  112289. shadowFrustumSize: 2
  112290. }
  112291. },
  112292. ground: {
  112293. shadowLevel: 0.9,
  112294. texture: "Ground_2.0-1024.png",
  112295. material: {
  112296. primaryColorHighlightLevel: 0.035,
  112297. primaryColorShadowLevel: 0,
  112298. enableNoise: true,
  112299. useRGBColor: false,
  112300. maxSimultaneousLights: 1,
  112301. diffuseTexture: {
  112302. gammaSpace: true
  112303. }
  112304. },
  112305. opacity: 1,
  112306. mirror: false,
  112307. receiveShadows: true,
  112308. size: 5
  112309. },
  112310. skybox: {
  112311. scale: 11,
  112312. cubeTexture: {
  112313. url: "Skybox_2.0-256.dds"
  112314. },
  112315. material: {
  112316. primaryColorHighlightLevel: 0.03,
  112317. primaryColorShadowLevel: 0.03,
  112318. enableNoise: true,
  112319. useRGBColor: false,
  112320. reflectionTexture: {
  112321. gammaSpace: true
  112322. }
  112323. }
  112324. },
  112325. engine: {
  112326. renderInBackground: true
  112327. },
  112328. scene: {
  112329. flags: {
  112330. shadowsEnabled: true,
  112331. particlesEnabled: false,
  112332. collisionsEnabled: false,
  112333. lightsEnabled: true,
  112334. texturesEnabled: true,
  112335. lensFlaresEnabled: false,
  112336. proceduralTexturesEnabled: false,
  112337. renderTargetsEnabled: true,
  112338. spritesEnabled: false,
  112339. skeletonsEnabled: true,
  112340. audioEnabled: false,
  112341. },
  112342. defaultMaterial: {
  112343. materialType: 'pbr',
  112344. reflectivityColor: {
  112345. r: 0.1,
  112346. g: 0.1,
  112347. b: 0.1
  112348. },
  112349. microSurface: 0.6
  112350. },
  112351. clearColor: {
  112352. r: 0.9,
  112353. g: 0.9,
  112354. b: 0.9,
  112355. a: 1.0
  112356. },
  112357. imageProcessingConfiguration: {
  112358. vignetteCentreX: 0,
  112359. vignetteCentreY: 0,
  112360. vignetteColor: {
  112361. r: 0.086,
  112362. g: 0.184,
  112363. b: 0.259,
  112364. a: 1
  112365. },
  112366. vignetteWeight: 0.855,
  112367. vignetteStretch: 0.5,
  112368. vignetteBlendMode: 0,
  112369. vignetteCameraFov: 0.7853981633974483,
  112370. isEnabled: true,
  112371. colorCurves: {
  112372. shadowsHue: 0,
  112373. shadowsDensity: 0,
  112374. shadowsSaturation: 0,
  112375. shadowsExposure: 0,
  112376. midtonesHue: 0,
  112377. midtonesDensity: 0,
  112378. midtonesExposure: 0,
  112379. midtonesSaturation: 0,
  112380. highlightsHue: 0,
  112381. highlightsDensity: 0,
  112382. highlightsExposure: 0,
  112383. highlightsSaturation: 0
  112384. }
  112385. },
  112386. mainColor: {
  112387. r: 0.8823529411764706,
  112388. g: 0.8823529411764706,
  112389. b: 0.8823529411764706
  112390. }
  112391. },
  112392. loaderPlugins: {
  112393. extendedMaterial: true,
  112394. applyMaterialConfig: true,
  112395. msftLod: true,
  112396. telemetry: true
  112397. },
  112398. model: {
  112399. rotationOffsetAxis: {
  112400. x: 0,
  112401. y: -1,
  112402. z: 0
  112403. },
  112404. rotationOffsetAngle: babylonjs_1.Tools.ToRadians(210),
  112405. material: {
  112406. directEnabled: true,
  112407. directIntensity: 0.884,
  112408. emissiveIntensity: 1.04,
  112409. environmentIntensity: 0.6
  112410. },
  112411. entryAnimation: {
  112412. scaling: {
  112413. x: 0,
  112414. y: 0,
  112415. z: 0
  112416. },
  112417. time: 0.5,
  112418. easingFunction: 4,
  112419. easingMode: 1
  112420. },
  112421. exitAnimation: {
  112422. scaling: {
  112423. x: 0,
  112424. y: 0,
  112425. z: 0
  112426. },
  112427. time: 0.5,
  112428. easingFunction: 4,
  112429. easingMode: 1
  112430. },
  112431. normalize: true,
  112432. castShadow: true,
  112433. receiveShadows: true
  112434. },
  112435. lab: {
  112436. assetsRootURL: 'https://viewer.babylonjs.com/assets/environment/',
  112437. environmentMap: {
  112438. texture: "EnvMap_2.0-256.env",
  112439. rotationY: 3,
  112440. tintLevel: 0.4
  112441. },
  112442. defaultRenderingPipelines: {
  112443. bloomEnabled: true,
  112444. bloomThreshold: 1.0,
  112445. fxaaEnabled: true,
  112446. bloomWeight: 0.05
  112447. }
  112448. }
  112449. };
  112450. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZXh0ZW5kZWQuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi8uLi9zcmMvY29uZmlndXJhdGlvbi90eXBlcy9leHRlbmRlZC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUNBLHVDQUFrQztBQUVsQzs7O0dBR0c7QUFDUSxRQUFBLHFCQUFxQix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BSSxFQUFFLEdBQUc7WUFDVCxjQUFjLEVBQUUsQ0FBQztZQUNqQixVQUFVLEVBQUUsQ0FBQztTQUNoQjtRQUNELFNBQVMsRUFBRSxJQUFJO1FBQ2YsVUFBVSxFQUFFLElBQUk7UUFDaEIsY0FBYyxFQUFFLElBQUk7S0FDdkI7SUFDRCxHQUFHLEVBQUU7UUFDRCxhQUFhLEVBQUUsa0RBQWtEO1FBQ2pFLGNBQWMsRUFBRTtZQUNaLE9BQU8sRUFBRSxvQkFBb0I7WUFDN0IsU0FBUyxFQUFFLENBQUM7WUFDWixTQUFTLEVBQUUsR0FBRztTQUNqQjtRQUNELHlCQUF5QixFQUFFO1lBQ3ZCLFlBQVksRUFBRSxJQUFJO1lBQ2xCLGNBQWMsRUFBRSxHQUFHO1lBQ25CLFdBQVcsRUFBRSxJQUFJO1lBQ2pCLFdBQVcsRUFBRSxJQUFJO1NBQ3BCO0tBQ0o7Q0FDSixDQUFBIn0=
  112451. /***/ }),
  112452. /* 51 */
  112453. /***/ (function(module, exports, __webpack_require__) {
  112454. "use strict";
  112455. Object.defineProperty(exports, "__esModule", { value: true });
  112456. /**
  112457. * Defines a default directional shadow light for normalized objects (!)
  112458. */
  112459. exports.shadowDirectionalLightConfiguration = {
  112460. model: {
  112461. receiveShadows: true,
  112462. castShadow: true
  112463. },
  112464. ground: {
  112465. receiveShadows: true
  112466. },
  112467. lights: {
  112468. shadowDirectionalLight: {
  112469. type: 1,
  112470. shadowEnabled: true,
  112471. target: { x: 0, y: 0, z: 0.5 },
  112472. position: { x: 1.49, y: 2.39, z: -1.33 },
  112473. diffuse: { r: 0.867, g: 0.816, b: 0.788 },
  112474. intensity: 4.887,
  112475. intensityMode: 0,
  112476. shadowBufferSize: 1024,
  112477. shadowFrustumSize: 6.0,
  112478. shadowFieldOfView: 50.977,
  112479. shadowMinZ: 0.1,
  112480. shadowMaxZ: 10.0,
  112481. shadowConfig: {
  112482. blurKernel: 32,
  112483. useBlurCloseExponentialShadowMap: true
  112484. }
  112485. }
  112486. }
  112487. };
  112488. /**
  112489. * Defines a default shadow-enabled spot light for normalized objects.
  112490. */
  112491. exports.shadowSpotlLightConfiguration = {
  112492. model: {
  112493. receiveShadows: true,
  112494. castShadow: true
  112495. },
  112496. ground: {
  112497. receiveShadows: true
  112498. },
  112499. lights: {
  112500. shadowSpotLight: {
  112501. type: 2,
  112502. intensity: 2,
  112503. shadowEnabled: true,
  112504. target: { x: 0, y: 0, z: 0.5 },
  112505. position: { x: 0, y: 3.5, z: 3.7 },
  112506. angle: 1,
  112507. shadowOrthoScale: 0.5,
  112508. shadowBufferSize: 1024,
  112509. shadowMinZ: 0.1,
  112510. shadowMaxZ: 50.0,
  112511. shadowConfig: {
  112512. frustumEdgeFalloff: 0.5,
  112513. blurKernel: 32,
  112514. useBlurExponentialShadowMap: true
  112515. }
  112516. }
  112517. }
  112518. };
  112519. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoic2hhZG93TGlnaHQuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi8uLi9zcmMvY29uZmlndXJhdGlvbi90eXBlcy9zaGFkb3dMaWdodC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUVBOztHQUVHO0FBQ1UsUUFBQSxtQ0FBbUMsR0FBd0I7SUFDcEUsS0FBSyxFQUFFO1FBQ0gsY0FBYyxFQUFFLElBQUk7UUFDcEIsVUFBVSxFQUFFLElBQUk7S0FDbkI7SUFDRCxNQUFNLEVBQUU7UUFDSixjQUFjLEVBQUUsSUFBSTtLQUN2QjtJQUNELE1BQU0sRUFBRTtRQUNKLHNCQUFzQixFQUFFO1lBQ3BCLElBQUksRUFBRSxDQUFDO1lBQ1AsYUFBYSxFQUFFLElBQUk7WUFDbkIsTUFBTSxFQUFFLEVBQUUsQ0FBQyxFQUFFLENBQUMsRUFBRSxDQUFDLEVBQUUsQ0FBQyxFQUFFLENBQUMsRU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sR0FBRyxFQUFFLENBQUMsRUFBRSxHQUFHLEVBQUU7WUFDbEMsS0FBSyxFQUFFLENBQUM7WUFDUixnQkFBZ0IsRUFBRSxHQUFHO1lBQ3JCLGdCQUFnQixFQUFFLElBQUk7WUFDdEIsVUFBVSxFQUFFLEdBQUc7WUFDZixVQUFVLEVBQUUsSUFBSTtZQUNoQixZQUFZLEVBQUU7Z0JBQ1Ysa0JBQWtCLEVBQUUsR0FBRztnQkFDdkIsVUFBVSxFQUFFLEVBQUU7Z0JBQ2QsMkJBQTJCLEVBQUUsSUFBSTthQUNwQztTQUNKO0tBQ0o7Q0FDSixDQUFBIn0=
  112520. /***/ }),
  112521. /* 52 */
  112522. /***/ (function(module, exports, __webpack_require__) {
  112523. "use strict";
  112524. Object.defineProperty(exports, "__esModule", { value: true });
  112525. /**
  112526. * Lab-oriented default .env support
  112527. */
  112528. exports.environmentMapConfiguration = {
  112529. lab: {
  112530. assetsRootURL: '/assets/environment/',
  112531. environmentMap: {
  112532. texture: 'EnvMap_2.0-256.env',
  112533. rotationY: 0,
  112534. tintLevel: 0.4
  112535. }
  112536. }
  112537. };
  112538. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZW52aXJvbm1lbnRNYXAuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi8uLi9zcmMvY29uZmlndXJhdGlvbi90eXBlcy9lbnZpcm9ubWVudE1hcC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUVBOztHQUVHO0FBQ1UsUUFBQSwyQkFBMkIsR0FBd0I7SUFDNUQsR0FBRyxFQUFFO1FBQ0QsYUFBYSxFQUFFLHNCQUFzQjtRQUNyQyxjQUFjLEVBQUU7WUFDWixPQUFPLEVBQUUsb0JBQW9CO1lBQzdCLFNBQVMsRUFBRSxDQUFDO1lBQ1osU0FBUyxFQUFFLEdBQUc7U0FDakI7S0FDSjtDQUNKLENBQUEifQ==
  112539. /***/ }),
  112540. /* 53 */
  112541. /***/ (function(module, exports, __webpack_require__) {
  112542. "use strict";
  112543. Object.defineProperty(exports, "__esModule", { value: true });
  112544. var configuration_1 = __webpack_require__(11);
  112545. /**
  112546. * This function will make sure the configuration file is taking deprecated fields into account
  112547. * and is setting them to the correct keys and values.
  112548. *
  112549. * @param configuration The configuration to process. Mutable!
  112550. */
  112551. function processConfigurationCompatibility(configuration) {
  112552. if (configuration.camera) {
  112553. // camera contrast -> image processing contrast
  112554. if (configuration.camera.contrast !== undefined) {
  112555. setKeyInObject(configuration, "scene.imageProcessingConfiguration.contrast", configuration.camera.contrast);
  112556. }
  112557. // camera exposure -> image processing exposure
  112558. if (configuration.camera.exposure !== undefined) {
  112559. setKeyInObject(configuration, "scene.imageProcessingConfiguration.exposure", configuration.camera.exposure);
  112560. }
  112561. }
  112562. if (configuration.scene) {
  112563. //glow
  112564. if (configuration.scene.glow) {
  112565. setKeyInObject(configuration, "lab.defaultRenderingPipelines.glowLayerEnabled", true);
  112566. var enabledProcessing = configuration_1.getConfigurationKey("scene.imageProcessingConfiguration.isEnabled", configuration);
  112567. if (enabledProcessing !== false) {
  112568. setKeyInObject(configuration, "scene.imageProcessingConfiguration.isEnabled", true);
  112569. }
  112570. }
  112571. }
  112572. }
  112573. exports.processConfigurationCompatibility = processConfigurationCompatibility;
  112574. function setKeyInObject(object, keys, value, shouldOverwrite) {
  112575. var keySplit = keys.split(".");
  112576. if (keySplit.length === 0)
  112577. return;
  112578. var lastKey = keySplit.pop();
  112579. if (!lastKey)
  112580. return;
  112581. var curObj = object;
  112582. keySplit.forEach(function (key) {
  112583. curObj[key] = curObj[key] || {};
  112584. curObj = curObj[key];
  112585. });
  112586. if (curObj[lastKey] !== undefined && !shouldOverwrite)
  112587. return;
  112588. curObj[lastKey] = value;
  112589. }
  112590. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiY29uZmlndXJhdGlvbkNvbXBhdGliaWxp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TFCRCw4RUEwQkM7QUFFRCx3QkFBd0IsTUFBVyxFQUFFLElBQVksRUFBRSxLQUFVLEVBQUUsZUFBeUI7SUFDcEYsSUFBSSxRQUFRLEdBQUcsSUFBSSxDQUFDLEtBQUssQ0FBQyxHQUFHLENBQUMsQ0FBQztJQUMvQixJQUFJLFFBQVEsQ0FBQyxNQUFNLEtBQUssQ0FBQztRQUFFLE9BQU87SUFDbEMsSUFBSSxPQUFPLEdBQUcsUUFBUSxDQUFDLEdBQUcsRUFBRSxDQUFDO0lBQzdCLElBQUksQ0FBQyxPQUFPO1FBQUUsT0FBTztJQUNyQixJQUFJLE1BQU0sR0FBRyxNQUFNLENBQUM7SUFDcEIsUUFBUSxDQUFDLE9BQU8sQ0FBQyxVQUFBLEdBQUc7UUFDaEIsTUFBTSxDQUFDLEdBQUcsQ0FBQyxHQUFHLE1BQU0sQ0FBQyxHQUFHLENBQUMsSUFBSSxFQUFFLENBQUM7UUFDaEMsTUFBTSxHQUFHLE1BQU0sQ0FBQyxHQUFHLENBQUMsQ0FBQztJQUN6QixDQUFDLENBQUMsQ0FBQztJQUNILElBQUksTUFBTSxDQUFDLE9BQU8sQ0FBQyxLQUFLLFNBQVMsSUFBSSxDQUFDLGVBQWU7UUFBRSxPQUFPO0lBQzlELE1BQU0sQ0FBQyxPQUFPLENBQUMsR0FBRyxLQUFLLENBQUM7QUFDNUIsQ0FBQyJ9
  112591. /***/ }),
  112592. /* 54 */
  112593. /***/ (function(module, exports, __webpack_require__) {
  112594. "use strict";
  112595. Object.defineProperty(exports, "__esModule", { value: true });
  112596. var telemetryLoaderPlugin_1 = __webpack_require__(55);
  112597. exports.TelemetryLoaderPlugin = telemetryLoaderPlugin_1.TelemetryLoaderPlugin;
  112598. var msftLodLoaderPlugin_1 = __webpack_require__(56);
  112599. exports.MSFTLodLoaderPlugin = msftLodLoaderPlugin_1.MSFTLodLoaderPlugin;
  112600. var applyMaterialConfig_1 = __webpack_require__(57);
  112601. exports.ApplyMaterialConfigPlugin = applyMaterialConfig_1.ApplyMaterialConfigPlugin;
  112602. var extendedMaterialLoaderPlugin_1 = __webpack_require__(58);
  112603. exports.ExtendedMaterialLoaderPlugin = extendedMaterialLoaderPlugin_1.ExtendedMaterialLoaderPlugin;
  112604. var babylonjs_1 = __webpack_require__(0);
  112605. var pluginCache = {};
  112606. /**
  112607. * Get a loader plugin according to its name.
  112608. * The plugin will be cached and will be reused if called for again.
  112609. *
  112610. * @param name the name of the plugin
  112611. */
  112612. function getLoaderPluginByName(name) {
  112613. if (!pluginCache[name]) {
  112614. switch (name) {
  112615. case 'telemetry':
  112616. pluginCache[name] = new telemetryLoaderPlugin_1.TelemetryLoaderPlugin();
  112617. break;
  112618. case 'msftLod':
  112619. pluginCache[name] = new msftLodLoaderPlugin_1.MSFTLodLoaderPlugin();
  112620. break;
  112621. case 'applyMaterialConfig':
  112622. pluginCache[name] = new applyMaterialConfig_1.ApplyMaterialConfigPlugin();
  112623. break;
  112624. case 'extendedMaterial':
  112625. pluginCache[name] = new extendedMaterialLoaderPlugin_1.ExtendedMaterialLoaderPlugin();
  112626. break;
  112627. }
  112628. }
  112629. return pluginCache[name];
  112630. }
  112631. exports.getLoaderPluginByName = getLoaderPluginByName;
  112632. /**
  112633. *
  112634. */
  112635. function addLoaderPlugin(name, plugin) {
  112636. if (pluginCache[name]) {
  112637. babylonjs_1.Tools.Warn("Overwriting plugin with the same name - " + name);
  112638. }
  112639. pluginCache[name] = plugin;
  112640. }
  112641. exports.addLoaderPlugin = addLoaderPlugin;
  112642. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi8uLi9zcmMvbG9hZGVyL3BsdWdpbnMvaW5kZXgudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFBQSxpRUFBZ0U7QUFTdkQsZ0NBVEEsNkNBQXFCLENBU0E7Q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sV0FBVyxDQUFDLElBQUksQ0FBQyxHQUFHLE1BQU0sQ0FBQztBQUMvQixDQUFDO0FBTEQsMENBS0MifQ==
  112643. /***/ }),
  112644. /* 55 */
  112645. /***/ (function(module, exports, __webpack_require__) {
  112646. "use strict";
  112647. Object.defineProperty(exports, "__esModule", { value: true });
  112648. var telemetryManager_1 = __webpack_require__(6);
  112649. var babylonjs_1 = __webpack_require__(0);
  112650. var TelemetryLoaderPlugin = /** @class */ (function () {
  112651. function TelemetryLoaderPlugin() {
  112652. }
  112653. TelemetryLoaderPlugin.prototype.onInit = function (loader, model) {
  112654. this._model = model;
  112655. this._loadStart = babylonjs_1.Tools.Now;
  112656. };
  112657. TelemetryLoaderPlugin.prototype.onLoaded = function (model) {
  112658. telemetryManager_1.telemetryManager.broadcast("Model Loaded", model.getViewerId(), {
  112659. model: model,
  112660. loadTime: babylonjs_1.Tools.Now - this._loadStart
  112661. });
  112662. telemetryManager_1.telemetryManager.flushWebGLErrors(model.rootMesh.getEngine(), model.getViewerId());
  112663. };
  112664. TelemetryLoaderPlugin.prototype.onError = function (message, exception) {
  112665. this._loadEnd = babylonjs_1.Tools.Now;
  112666. telemetryManager_1.telemetryManager.broadcast("Load Error", this._model.getViewerId(), {
  112667. model: this._model,
  112668. loadTime: this._loadEnd - this._loadStart
  112669. });
  112670. telemetryManager_1.telemetryManager.flushWebGLErrors(this._model.rootMesh.getEngine(), this._model.getViewerId());
  112671. };
  112672. TelemetryLoaderPlugin.prototype.onComplete = function () {
  112673. this._loadEnd = babylonjs_1.Tools.Now;
  112674. telemetryManager_1.telemetryManager.broadcast("Load Complete", this._model.getViewerId(), {
  112675. model: this._model,
  112676. loadTime: this._loadEnd - this._loadStart
  112677. });
  112678. telemetryManager_1.telemetryManager.flushWebGLErrors(this._model.rootMesh.getEngine(), this._model.getViewerId());
  112679. };
  112680. return TelemetryLoaderPlugin;
  112681. }());
  112682. exports.TelemetryLoaderPlugin = TelemetryLoaderPlugin;
  112683. //# sourceMapping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UFBRSxFQUFFO1lBQ2hFLEtBQUssRUFBRSxJQUFJLENBQUMsTUFBTTtZQUNsQixRQUFRLEVBQUUsSUFBSSxDQUFDLFFBQVEsR0FBRyxJQUFJLENBQUMsVUFBVTtTQUM1QyxDQUFDLENBQUM7UUFFSCxtQ0FBZ0IsQ0FBQyxnQkFBZ0IsQ0FBQyxJQUFJLENBQUMsTUFBTSxDQUFDLFFBQVEsQ0FBQyxTQUFTLEVBQUUsRUFBRSxJQUFJLENBQUMsTUFBTSxDQUFDLFdBQVcsRUFBRSxDQUFDLENBQUM7SUFDbkcsQ0FBQztJQUVNLDBDQUFVLEdBQWpCO1FBQ0ksSUFBSSxDQUFDLFFBQVEsR0FBRyxpQkFBSyxDQUFDLEdBQUcsQ0FBQztRQUMxQixtQ0FBZ0IsQ0FBQyxTQUFTLENBQUMsZUFBZSxFQUFFLElBQUksQ0FBQyxNQUFNLENBQUMsV0FBVyxFQUFFLEVBQUU7WUFDbkUsS0FBSyxFQUFFLElBQUksQ0FBQyxNQUFNO1lBQ2xCLFFBQVEsRUFBRSxJQUFJLENBQUMsUUFBUSxHQUFHLElBQUksQ0FBQyxVQUFVO1NBQzVDLENBQUMsQ0FBQztRQUVILG1DQUFnQixDQUFDLGdCQUFnQixDQUFDLElBQUksQ0FBQyxNQUFNLENBQUMsUUFBUSxDQUFDLFNBQVMsRUFBRSxFQUFFLElBQUksQ0FBQyxNQUFNLENBQUMsV0FBVyxFQUFFLENBQUMsQ0FBQztJQUNuRyxDQUFDO0lBQ0wsNEJBQUM7QUFBRCxDQUFDLEFBdkNELElBdUNDO0FBdkNZLHNEQUFxQiJ9
  112684. /***/ }),
  112685. /* 56 */
  112686. /***/ (function(module, exports, __webpack_require__) {
  112687. "use strict";
  112688. Object.defineProperty(exports, "__esModule", { value: true });
  112689. /**
  112690. * A loder plugin to use MSFT_lod extension correctly (glTF)
  112691. */
  112692. var MSFTLodLoaderPlugin = /** @class */ (function () {
  112693. function MSFTLodLoaderPlugin() {
  112694. }
  112695. MSFTLodLoaderPlugin.prototype.onInit = function (loader, model) {
  112696. this._model = model;
  112697. };
  112698. MSFTLodLoaderPlugin.prototype.onExtensionLoaded = function (extension) {
  112699. if (extension.name === "MSFT_lod" && this._model.configuration.loaderConfiguration) {
  112700. var MSFT_lod = extension;
  112701. MSFT_lod.enabled = !!this._model.configuration.loaderConfiguration.progressiveLoading;
  112702. MSFT_lod.maxLODsToLoad = this._model.configuration.loaderConfiguration.maxLODsToLoad || Number.MAX_VALUE;
  112703. }
  112704. };
  112705. return MSFTLodLoaderPlugin;
  112706. }());
  112707. exports.MSFTLodLoaderPlugin = MSFTLodLoaderPlugin;
  112708. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoibXNmdExvZExvYWRlclBsdWdpbi5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uLy4uL3NyYy9sb2FkZXIvcGx1Z2lucy9tc2Z0TG9kTG9hZGVyUGx1Z2luLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7O0FBS0E7O0dBRUc7QUFDSDtJQUFBO0lBZUEsQ0FBQztJQVhVLG9DQUFNLEdBQWIsVUFBYyxNQUFvRCxFQUFFLEtBQWtCO1FBQ2xGLElBQUksQ0FBQyxNQUFNLEdBQUcsS0FBSyxDQUFDO0lBQ3hCLENBQUM7SUFFTSwrQ0FBaUIsR0FBeEIsVUFBeUIsU0FBK0I7UUFDcEQsSUFBSSxTQUFTLENBQUMsSUFBSSxLQUFLLFVBQVUsSUFBSSxJQUFJLENBQUMsTUFBTSxDQUFDLGFBQWEsQ0FBQyxtQkFBbUIsRUFBRTtZQUNoRixJQUFNLFFBQVEsR0FBRyxTQUFzQyxDQUFDO1lBQ3hELFFBQVEsQ0FBQyxPQUFPLEdBQUcsQ0FBQyxDQUFDLElBQUksQ0FBQyxNQUFNLENBQUMsYUFBYSxDQUFDLG1CQUFtQixDQUFDLGtCQUFrQixDQUFDO1lBQ3RGLFFBQVEsQ0FBQyxhQUFhLEdBQUcsSUFBSSxDQUFDLE1BQU0sQ0FBQyxhQUFhLENBQUMsbUJBQW1CLENBQUMsYUFBYSxJQUFJLE1BQU0sQ0FBQyxTQUFTLENBQUM7U0FDNUc7SUFDTCxDQUFDO0lBQ0wsMEJBQUM7QUFBRCxDQUFDLEFBZkQsSUFlQztBQWZZLGtEQUFtQiJ9
  112709. /***/ }),
  112710. /* 57 */
  112711. /***/ (function(module, exports, __webpack_require__) {
  112712. "use strict";
  112713. Object.defineProperty(exports, "__esModule", { value: true });
  112714. /**
  112715. * Force-apply material configuration right after a material was loaded.
  112716. */
  112717. var ApplyMaterialConfigPlugin = /** @class */ (function () {
  112718. function ApplyMaterialConfigPlugin() {
  112719. }
  112720. ApplyMaterialConfigPlugin.prototype.onInit = function (loader, model) {
  112721. this._model = model;
  112722. };
  112723. ApplyMaterialConfigPlugin.prototype.onMaterialLoaded = function (material) {
  112724. this._model && this._model._applyModelMaterialConfiguration(material);
  112725. };
  112726. return ApplyMaterialConfigPlugin;
  112727. }());
  112728. exports.ApplyMaterialConfigPlugin = ApplyMaterialConfigPlugin;
  112729. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiYXBwbHlNYXRlcmlhbENvbmZpZy5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uLy4uL3NyYy9sb2FkZXIvcGx1Z2lucy9hcHBseU1hdGVyaWFsQ29uZmlnLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7O0FBS0E7O0dBRUc7QUFDSDtJQUFBO0lBV0EsQ0FBQztJQVBVLDBDQUFNLEdBQWIsVUFBYyxNQUFvRCxFQUFFLEtBQWtCO1FBQ2xGLElBQUksQ0FBQyxNQUFNLEdBQUcsS0FBSyxDQUFDO0lBQ3hCLENBQUM7SUFFTSxvREFBZ0IsR0FBdkIsVUFBd0IsUUFBa0I7UUFDdEMsSUFBSSxDQUFDLE1BQU0sSUFBSSxJQUFJLENBQUMsTUFBTSxDQUFDLGdDQUFnQyxDQUFDLFFBQVEsQ0FBQyxDQUFDO0lBQzFFLENBQUM7SUFDTCxnQ0FBQztBQUFELENBQUMsQUFYRCxJQVdDO0FBWFksOERBQXlCIn0=
  112730. /***/ }),
  112731. /* 58 */
  112732. /***/ (function(module, exports, __webpack_require__) {
  112733. "use strict";
  112734. Object.defineProperty(exports, "__esModule", { value: true });
  112735. var babylonjs_1 = __webpack_require__(0);
  112736. /**
  112737. * A (PBR) material will be extended using this function.
  112738. * This function will hold extra default configuration for the viewer, if not implemented in Babylon itself.
  112739. */
  112740. var ExtendedMaterialLoaderPlugin = /** @class */ (function () {
  112741. function ExtendedMaterialLoaderPlugin() {
  112742. }
  112743. ExtendedMaterialLoaderPlugin.prototype.onMaterialLoaded = function (baseMaterial) {
  112744. var material = baseMaterial;
  112745. material.alphaMode = babylonjs_1.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  112746. };
  112747. return ExtendedMaterialLoaderPlugin;
  112748. }());
  112749. exports.ExtendedMaterialLoaderPlugin = ExtendedMaterialLoaderPlugin;
  112750. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZXh0ZW5kZWRNYXRlcmlhbExvYWRlclBsdWdpbi5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uLy4uL3NyYy9sb2FkZXIvcGx1Z2lucy9leHRlbmRlZE1hdGVyaWFsTG9hZGVyUGx1Z2luLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7O0FBRUEsdUNBQTRJO0FBRTVJOzs7R0FHRztBQUNIO0lBQUE7SUFNQSxDQUFDO0lBSlUsdURBQWdCLEdBQXZCLFVBQXdCLFlBQXNCO1FBQzFDLElBQUksUUFBUSxHQUFHLFlBQTJCLENBQUM7UUFDM0MsUUFBUSxDQUFDLFNBQVMsR0FBRyxrQkFBTSxDQUFDLDhCQUE4QixDQUFDO0lBQy9ELENBQUM7SUFDTCxtQ0FBQztBQUFELENBQUMsQUFORCxJQU1DO0FBTlksb0VBQTRCIn0=
  112751. /***/ }),
  112752. /* 59 */
  112753. /***/ (function(module, exports, __webpack_require__) {
  112754. "use strict";
  112755. Object.defineProperty(exports, "__esModule", { value: true });
  112756. var babylonjs_1 = __webpack_require__(0);
  112757. var ObservablesManager = /** @class */ (function () {
  112758. function ObservablesManager() {
  112759. this.onSceneInitObservable = new babylonjs_1.Observable();
  112760. this.onEngineInitObservable = new babylonjs_1.Observable();
  112761. this.onModelLoadedObservable = new babylonjs_1.Observable();
  112762. this.onModelLoadProgressObservable = new babylonjs_1.Observable();
  112763. this.onModelLoadErrorObservable = new babylonjs_1.Observable();
  112764. this.onModelAddedObservable = new babylonjs_1.Observable();
  112765. this.onModelRemovedObservable = new babylonjs_1.Observable();
  112766. this.onViewerInitDoneObservable = new babylonjs_1.Observable();
  112767. this.onLoaderInitObservable = new babylonjs_1.Observable();
  112768. this.onFrameRenderedObservable = new babylonjs_1.Observable();
  112769. }
  112770. ObservablesManager.prototype.dispose = function () {
  112771. this.onSceneInitObservable.clear();
  112772. this.onEngineInitObservable.clear();
  112773. this.onModelLoadedObservable.clear();
  112774. this.onModelLoadProgressObservable.clear();
  112775. this.onModelLoadErrorObservable.clear();
  112776. this.onModelAddedObservable.clear();
  112777. this.onModelRemovedObservable.clear();
  112778. this.onViewerInitDoneObservable.clear();
  112779. this.onLoaderInitObservable.clear();
  112780. this.onFrameRenderedObservable.clear();
  112781. };
  112782. return ObservablesManager;
  112783. }());
  112784. exports.ObservablesManager = ObservablesManager;
  112785. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoib2JzZXJ2YWJsZXNNYW5hZ2VyLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vLi4vc3JjL21hbmFnZXJ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SyxFQUFFLENBQUM7UUFDeEMsSUFBSSxDQUFDLHNCQUFzQixDQUFDLEtBQUssRUFBRSxDQUFDO1FBQ3BDLElBQUksQ0FBQyx3QkFBd0IsQ0FBQyxLQUFLLEVBQUUsQ0FBQztRQUN0QyxJQUFJLENBQUMsMEJBQTBCLENBQUMsS0FBSyxFQUFFLENBQUM7UUFDeEMsSUFBSSxDQUFDLHNCQUFzQixDQUFDLEtBQUssRUFBRSxDQUFDO1FBQ3BDLElBQUksQ0FBQyx5QkFBeUIsQ0FBQyxLQUFLLEVBQUUsQ0FBQztJQUMzQyxDQUFDO0lBRUwseUJBQUM7QUFBRCxDQUFDLEFBekVELElBeUVDO0FBekVZLGdEQUFrQiJ9
  112786. /***/ }),
  112787. /* 60 */
  112788. /***/ (function(module, exports, __webpack_require__) {
  112789. "use strict";
  112790. Object.defineProperty(exports, "__esModule", { value: true });
  112791. var babylonjs_1 = __webpack_require__(0);
  112792. var ConfigurationContainer = /** @class */ (function () {
  112793. function ConfigurationContainer() {
  112794. this.mainColor = babylonjs_1.Color3.White();
  112795. this.reflectionColor = babylonjs_1.Color3.White();
  112796. }
  112797. return ConfigurationContainer;
  112798. }());
  112799. exports.ConfigurationContainer = ConfigurationContainer;
  112800. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiY29uZmlndXJhdGlvbkNvbnRhaW5lci5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uL3NyYy9jb25maWd1cmF0aW9uL2NvbmZpZ3VyYXRpb25Db250YWluZXIudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFDQSx1Q0FBbUM7QUFFbkM7SUFBQTtRQU1XLGNBQVMsR0FBVyxrQkFBTSxDQUFDLEtBQUssRUFBRSxDQUFDO1FBQ25DLG9CQUFlLEdBQVcsa0JBQU0sQ0FBQyxLQUFLLEVBQUUsQ0FBQztJQUNwRCxDQUFDO0lBQUQsNkJBQUM7QUFBRCxDQUFDLEFBUkQsSUFRQztBQVJZLHdEQUFzQiJ9
  112801. /***/ }),
  112802. /* 61 */
  112803. /***/ (function(module, exports, __webpack_require__) {
  112804. "use strict";
  112805. Object.defineProperty(exports, "__esModule", { value: true });
  112806. var babylonjs_1 = __webpack_require__(0);
  112807. var helper_1 = __webpack_require__(1);
  112808. var Handlebars = __webpack_require__(62);
  112809. var eventManager_1 = __webpack_require__(63);
  112810. var _1 = __webpack_require__(1);
  112811. /**
  112812. * The template manager, a member of the viewer class, will manage the viewer's templates and generate the HTML.
  112813. * The template manager managers a single viewer and can be seen as the collection of all sub-templates of the viewer.
  112814. */
  112815. var TemplateManager = /** @class */ (function () {
  112816. function TemplateManager(containerElement) {
  112817. this.containerElement = containerElement;
  112818. this.templates = {};
  112819. this.onTemplateInit = new babylonjs_1.Observable();
  112820. this.onTemplateLoaded = new babylonjs_1.Observable();
  112821. this.onTemplateStateChange = new babylonjs_1.Observable();
  112822. this.onAllLoaded = new babylonjs_1.Observable();
  112823. this.onEventTriggered = new babylonjs_1.Observable();
  112824. this.eventManager = new eventManager_1.EventManager(this);
  112825. }
  112826. /**
  112827. * Initialize the template(s) for the viewer. Called bay the Viewer class
  112828. * @param templates the templates to be used to initialize the main template
  112829. */
  112830. TemplateManager.prototype.initTemplate = function (templates) {
  112831. var _this = this;
  112832. var internalInit = function (dependencyMap, name, parentTemplate) {
  112833. //init template
  112834. var template = _this.templates[name];
  112835. var childrenTemplates = Object.keys(dependencyMap).map(function (childName) {
  112836. return internalInit(dependencyMap[childName], childName, template);
  112837. });
  112838. // register the observers
  112839. //template.onLoaded.add(() => {
  112840. var addToParent = function () {
  112841. var containingElement = parentTemplate && parentTemplate.parent.querySelector(helper_1.camelToKebab(name)) || _this.containerElement;
  112842. template.appendTo(containingElement);
  112843. _this._checkLoadedState();
  112844. };
  112845. if (parentTemplate && !parentTemplate.parent) {
  112846. parentTemplate.onAppended.add(function () {
  112847. addToParent();
  112848. });
  112849. }
  112850. else {
  112851. addToParent();
  112852. }
  112853. //});
  112854. return template;
  112855. };
  112856. //build the html tree
  112857. return this._buildHTMLTree(templates).then(function (htmlTree) {
  112858. if (_this.templates['main']) {
  112859. internalInit(htmlTree, 'main');
  112860. }
  112861. else {
  112862. _this._checkLoadedState();
  112863. }
  112864. return;
  112865. });
  112866. };
  112867. /**
  112868. *
  112869. * This function will create a simple map with child-dependencies of the template html tree.
  112870. * It will compile each template, check if its children exist in the configuration and will add them if they do.
  112871. * It is expected that the main template will be called main!
  112872. *
  112873. * @param templates
  112874. */
  112875. TemplateManager.prototype._buildHTMLTree = function (templates) {
  112876. var _this = this;
  112877. var promises = Object.keys(templates).map(function (name) {
  112878. // if the template was overridden
  112879. if (!templates[name])
  112880. return Promise.resolve(false);
  112881. // else - we have a template, let's do our job!
  112882. var template = new Template(name, templates[name]);
  112883. template.onLoaded.add(function () {
  112884. _this.onTemplateLoaded.notifyObservers(template);
  112885. });
  112886. template.onStateChange.add(function () {
  112887. _this.onTemplateStateChange.notifyObservers(template);
  112888. });
  112889. _this.onTemplateInit.notifyObservers(template);
  112890. // make sure the global onEventTriggered is called as well
  112891. template.onEventTriggered.add(function (eventData) { return _this.onEventTriggered.notifyObservers(eventData); });
  112892. _this.templates[name] = template;
  112893. return template.initPromise;
  112894. });
  112895. return Promise.all(promises).then(function () {
  112896. var templateStructure = {};
  112897. // now iterate through all templates and check for children:
  112898. var buildTree = function (parentObject, name) {
  112899. _this.templates[name].isInHtmlTree = true;
  112900. var childNodes = _this.templates[name].getChildElements().filter(function (n) { return !!_this.templates[n]; });
  112901. childNodes.forEach(function (element) {
  112902. parentObject[element] = {};
  112903. buildTree(parentObject[element], element);
  112904. });
  112905. };
  112906. if (_this.templates['main']) {
  112907. buildTree(templateStructure, "main");
  112908. }
  112909. return templateStructure;
  112910. });
  112911. };
  112912. /**
  112913. * Get the canvas in the template tree.
  112914. * There must be one and only one canvas inthe template.
  112915. */
  112916. TemplateManager.prototype.getCanvas = function () {
  112917. return this.containerElement.querySelector('canvas');
  112918. };
  112919. /**
  112920. * Get a specific template from the template tree
  112921. * @param name the name of the template to load
  112922. */
  112923. TemplateManager.prototype.getTemplate = function (name) {
  112924. return this.templates[name];
  112925. };
  112926. TemplateManager.prototype._checkLoadedState = function () {
  112927. var _this = this;
  112928. var done = Object.keys(this.templates).length === 0 || Object.keys(this.templates).every(function (key) {
  112929. return (_this.templates[key].isLoaded && !!_this.templates[key].parent) || !_this.templates[key].isInHtmlTree;
  112930. });
  112931. if (done) {
  112932. this.onAllLoaded.notifyObservers(this);
  112933. }
  112934. };
  112935. /**
  112936. * Dispose the template manager
  112937. */
  112938. TemplateManager.prototype.dispose = function () {
  112939. var _this = this;
  112940. // dispose all templates
  112941. Object.keys(this.templates).forEach(function (template) {
  112942. _this.templates[template].dispose();
  112943. });
  112944. this.templates = {};
  112945. this.eventManager.dispose();
  112946. this.onTemplateInit.clear();
  112947. this.onAllLoaded.clear();
  112948. this.onEventTriggered.clear();
  112949. this.onTemplateLoaded.clear();
  112950. this.onTemplateStateChange.clear();
  112951. };
  112952. return TemplateManager;
  112953. }());
  112954. exports.TemplateManager = TemplateManager;
  112955. // register a new helper. modified https://stackoverflow.com/questions/9838925/is-there-any-method-to-iterate-a-map-with-handlebars-js
  112956. Handlebars.registerHelper('eachInMap', function (map, block) {
  112957. var out = '';
  112958. Object.keys(map).map(function (prop) {
  112959. var data = map[prop];
  112960. if (typeof data === 'object') {
  112961. data.id = data.id || prop;
  112962. out += block.fn(data);
  112963. }
  112964. else {
  112965. out += block.fn({ id: prop, value: data });
  112966. }
  112967. });
  112968. return out;
  112969. });
  112970. Handlebars.registerHelper('add', function (a, b) {
  112971. var out = a + b;
  112972. return out;
  112973. });
  112974. Handlebars.registerHelper('eq', function (a, b) {
  112975. var out = (a == b);
  112976. return out;
  112977. });
  112978. Handlebars.registerHelper('or', function (a, b) {
  112979. var out = a || b;
  112980. return out;
  112981. });
  112982. Handlebars.registerHelper('not', function (a) {
  112983. var out = !a;
  112984. return out;
  112985. });
  112986. Handlebars.registerHelper('count', function (map) {
  112987. return map.length;
  112988. });
  112989. Handlebars.registerHelper('gt', function (a, b) {
  112990. var out = a > b;
  112991. return out;
  112992. });
  112993. /**
  112994. * This class represents a single template in the viewer's template tree.
  112995. * An example for a template is a single canvas, an overlay (containing sub-templates) or the navigation bar.
  112996. * A template is injected using the template manager in the correct position.
  112997. * The template is rendered using Handlebars and can use Handlebars' features (such as parameter injection)
  112998. *
  112999. * For further information please refer to the documentation page, https://doc.babylonjs.com
  113000. */
  113001. var Template = /** @class */ (function () {
  113002. function Template(name, _configuration) {
  113003. var _this = this;
  113004. this.name = name;
  113005. this._configuration = _configuration;
  113006. this.onLoaded = new babylonjs_1.Observable();
  113007. this.onAppended = new babylonjs_1.Observable();
  113008. this.onStateChange = new babylonjs_1.Observable();
  113009. this.onEventTriggered = new babylonjs_1.Observable();
  113010. this.loadRequests = [];
  113011. this.isLoaded = false;
  113012. this.isShown = false;
  113013. this.isInHtmlTree = false;
  113014. var htmlContentPromise = this._getTemplateAsHtml(_configuration);
  113015. this.initPromise = htmlContentPromise.then(function (htmlTemplate) {
  113016. if (htmlTemplate) {
  113017. _this._htmlTemplate = htmlTemplate;
  113018. var compiledTemplate = Handlebars.compile(htmlTemplate, { noEscape: (_this._configuration.params && !!_this._configuration.params.noEscape) });
  113019. var config = _this._configuration.params || {};
  113020. _this._rawHtml = compiledTemplate(config);
  113021. try {
  113022. _this._fragment = document.createRange().createContextualFragment(_this._rawHtml);
  113023. }
  113024. catch (e) {
  113025. var test = document.createElement(_this.name);
  113026. test.innerHTML = _this._rawHtml;
  113027. _this._fragment = test;
  113028. }
  113029. _this.isLoaded = true;
  113030. _this.isShown = true;
  113031. _this.onLoaded.notifyObservers(_this);
  113032. }
  113033. return _this;
  113034. });
  113035. }
  113036. /**
  113037. * Some templates have parameters (like background color for example).
  113038. * The parameters are provided to Handlebars which in turn generates the template.
  113039. * This function will update the template with the new parameters
  113040. *
  113041. * Note that when updating parameters the events will be registered again (after being cleared).
  113042. *
  113043. * @param params the new template parameters
  113044. */
  113045. Template.prototype.updateParams = function (params, append) {
  113046. if (append === void 0) { append = true; }
  113047. if (append) {
  113048. this._configuration.params = _1.deepmerge(this._configuration.params, params);
  113049. }
  113050. else {
  113051. this._configuration.params = params;
  113052. }
  113053. // update the template
  113054. if (this.isLoaded) {
  113055. // this.dispose();
  113056. }
  113057. var compiledTemplate = Handlebars.compile(this._htmlTemplate);
  113058. var config = this._configuration.params || {};
  113059. this._rawHtml = compiledTemplate(config);
  113060. try {
  113061. this._fragment = document.createRange().createContextualFragment(this._rawHtml);
  113062. }
  113063. catch (e) {
  113064. var test = document.createElement(this.name);
  113065. test.innerHTML = this._rawHtml;
  113066. this._fragment = test;
  113067. }
  113068. if (this.parent) {
  113069. this.appendTo(this.parent, true);
  113070. }
  113071. };
  113072. Object.defineProperty(Template.prototype, "configuration", {
  113073. /**
  113074. * Get the template'S configuration
  113075. */
  113076. get: function () {
  113077. return this._configuration;
  113078. },
  113079. enumerable: true,
  113080. configurable: true
  113081. });
  113082. /**
  113083. * A template can be a parent element for other templates or HTML elements.
  113084. * This function will deliver all child HTML elements of this template.
  113085. */
  113086. Template.prototype.getChildElements = function () {
  113087. var childrenArray = [];
  113088. //Edge and IE don't support frage,ent.children
  113089. var children = this._fragment && this._fragment.children;
  113090. if (!this._fragment) {
  113091. var fragment = this.parent.querySelector(this.name);
  113092. if (fragment) {
  113093. children = fragment.querySelectorAll('*');
  113094. }
  113095. }
  113096. if (!children) {
  113097. // casting to HTMLCollection, as both NodeListOf and HTMLCollection have 'item()' and 'length'.
  113098. children = this._fragment.querySelectorAll('*');
  113099. }
  113100. for (var i = 0; i < children.length; ++i) {
  113101. childrenArray.push(helper_1.kebabToCamel(children.item(i).nodeName.toLowerCase()));
  113102. }
  113103. return childrenArray;
  113104. };
  113105. /**
  113106. * Appending the template to a parent HTML element.
  113107. * If a parent is already set and you wish to replace the old HTML with new one, forceRemove should be true.
  113108. * @param parent the parent to which the template is added
  113109. * @param forceRemove if the parent already exists, shoud the template be removed from it?
  113110. */
  113111. Template.prototype.appendTo = function (parent, forceRemove) {
  113112. var _this = this;
  113113. if (this.parent) {
  113114. if (forceRemove && this._addedFragment) {
  113115. /*let fragement = this.parent.querySelector(this.name)
  113116. if (fragement)
  113117. this.parent.removeChild(fragement);*/
  113118. this.parent.innerHTML = '';
  113119. }
  113120. else {
  113121. return;
  113122. }
  113123. }
  113124. this.parent = parent;
  113125. if (this._configuration.id) {
  113126. this.parent.id = this._configuration.id;
  113127. }
  113128. if (this._fragment) {
  113129. this.parent.appendChild(this._fragment);
  113130. this._addedFragment = this._fragment;
  113131. }
  113132. else {
  113133. this.parent.insertAdjacentHTML("beforeend", this._rawHtml);
  113134. }
  113135. // appended only one frame after.
  113136. setTimeout(function () {
  113137. _this._registerEvents();
  113138. _this.onAppended.notifyObservers(_this);
  113139. });
  113140. };
  113141. /**
  113142. * Show the template using the provided visibilityFunction, or natively using display: flex.
  113143. * The provided function returns a promise that should be fullfilled when the element is shown.
  113144. * Since it is a promise async operations are more than possible.
  113145. * See the default viewer for an opacity example.
  113146. * @param visibilityFunction The function to execute to show the template.
  113147. */
  113148. Template.prototype.show = function (visibilityFunction) {
  113149. var _this = this;
  113150. if (this._isHiding)
  113151. return Promise.resolve(this);
  113152. return Promise.resolve().then(function () {
  113153. _this._isShowing = true;
  113154. if (visibilityFunction) {
  113155. return visibilityFunction(_this);
  113156. }
  113157. else {
  113158. // flex? box? should this be configurable easier than the visibilityFunction?
  113159. _this.parent.style.display = 'flex';
  113160. // support old browsers with no flex:
  113161. if (_this.parent.style.display !== 'flex') {
  113162. _this.parent.style.display = '';
  113163. }
  113164. return _this;
  113165. }
  113166. }).then(function () {
  113167. _this.isShown = true;
  113168. _this._isShowing = false;
  113169. _this.onStateChange.notifyObservers(_this);
  113170. return _this;
  113171. });
  113172. };
  113173. /**
  113174. * Hide the template using the provided visibilityFunction, or natively using display: none.
  113175. * The provided function returns a promise that should be fullfilled when the element is hidden.
  113176. * Since it is a promise async operations are more than possible.
  113177. * See the default viewer for an opacity example.
  113178. * @param visibilityFunction The function to execute to show the template.
  113179. */
  113180. Template.prototype.hide = function (visibilityFunction) {
  113181. var _this = this;
  113182. if (this._isShowing)
  113183. return Promise.resolve(this);
  113184. return Promise.resolve().then(function () {
  113185. _this._isHiding = true;
  113186. if (visibilityFunction) {
  113187. return visibilityFunction(_this);
  113188. }
  113189. else {
  113190. // flex? box? should this be configurable easier than the visibilityFunction?
  113191. _this.parent.style.display = 'none';
  113192. return _this;
  113193. }
  113194. }).then(function () {
  113195. _this.isShown = false;
  113196. _this._isHiding = false;
  113197. _this.onStateChange.notifyObservers(_this);
  113198. return _this;
  113199. });
  113200. };
  113201. /**
  113202. * Dispose this template
  113203. */
  113204. Template.prototype.dispose = function () {
  113205. this.onAppended.clear();
  113206. this.onEventTriggered.clear();
  113207. this.onLoaded.clear();
  113208. this.onStateChange.clear();
  113209. this.isLoaded = false;
  113210. // remove from parent
  113211. try {
  113212. this.parent.removeChild(this._fragment);
  113213. }
  113214. catch (e) {
  113215. //noop
  113216. }
  113217. this.loadRequests.forEach(function (request) {
  113218. request.abort();
  113219. });
  113220. if (this._registeredEvents) {
  113221. this._registeredEvents.forEach(function (evt) {
  113222. evt.htmlElement.removeEventListener(evt.eventName, evt.function);
  113223. });
  113224. }
  113225. delete this._fragment;
  113226. };
  113227. Template.prototype._getTemplateAsHtml = function (templateConfig) {
  113228. var _this = this;
  113229. if (!templateConfig) {
  113230. return Promise.reject('No templateConfig provided');
  113231. }
  113232. else if (templateConfig.html !== undefined) {
  113233. return Promise.resolve(templateConfig.html);
  113234. }
  113235. else {
  113236. var location_1 = this._getTemplateLocation(templateConfig);
  113237. if (helper_1.isUrl(location_1)) {
  113238. return new Promise(function (resolve, reject) {
  113239. var fileRequest = babylonjs_1.Tools.LoadFile(location_1, function (data) {
  113240. resolve(data);
  113241. }, undefined, undefined, false, function (request, error) {
  113242. reject(error);
  113243. });
  113244. _this.loadRequests.push(fileRequest);
  113245. });
  113246. }
  113247. else {
  113248. location_1 = location_1.replace('#', '');
  113249. var element = document.getElementById(location_1);
  113250. if (element) {
  113251. return Promise.resolve(element.innerHTML);
  113252. }
  113253. else {
  113254. return Promise.reject('Template ID not found');
  113255. }
  113256. }
  113257. }
  113258. };
  113259. Template.prototype._registerEvents = function () {
  113260. var _this = this;
  113261. this._registeredEvents = this._registeredEvents || [];
  113262. if (this._registeredEvents.length) {
  113263. // first remove the registered events
  113264. this._registeredEvents.forEach(function (evt) {
  113265. evt.htmlElement.removeEventListener(evt.eventName, evt.function);
  113266. });
  113267. }
  113268. if (this._configuration.events) {
  113269. var _loop_1 = function (eventName) {
  113270. if (this_1._configuration.events && this_1._configuration.events[eventName]) {
  113271. var functionToFire_1 = function (selector, event) {
  113272. _this.onEventTriggered.notifyObservers({ event: event, template: _this, selector: selector });
  113273. };
  113274. // if boolean, set the parent as the event listener
  113275. if (typeof this_1._configuration.events[eventName] === 'boolean') {
  113276. var selector = this_1.parent.id;
  113277. if (selector) {
  113278. selector = '#' + selector;
  113279. }
  113280. else {
  113281. selector = this_1.parent.tagName;
  113282. }
  113283. var binding = functionToFire_1.bind(this_1, selector);
  113284. this_1.parent.addEventListener(eventName, functionToFire_1.bind(this_1, selector), false);
  113285. this_1._registeredEvents.push({
  113286. htmlElement: this_1.parent,
  113287. eventName: eventName,
  113288. function: binding
  113289. });
  113290. }
  113291. else if (typeof this_1._configuration.events[eventName] === 'object') {
  113292. var selectorsArray = Object.keys(this_1._configuration.events[eventName] || {});
  113293. // strict null checl is working incorrectly, must override:
  113294. var event_1 = this_1._configuration.events[eventName] || {};
  113295. selectorsArray.filter(function (selector) { return event_1[selector]; }).forEach(function (selector) {
  113296. if (selector && selector.indexOf('#') !== 0) {
  113297. selector = '#' + selector;
  113298. }
  113299. var htmlElement = _this.parent.querySelector(selector);
  113300. if (htmlElement) {
  113301. var binding = functionToFire_1.bind(_this, selector);
  113302. htmlElement.addEventListener(eventName, binding, false);
  113303. _this._registeredEvents.push({
  113304. htmlElement: htmlElement,
  113305. eventName: eventName,
  113306. function: binding
  113307. });
  113308. }
  113309. });
  113310. }
  113311. }
  113312. };
  113313. var this_1 = this;
  113314. for (var eventName in this._configuration.events) {
  113315. _loop_1(eventName);
  113316. }
  113317. }
  113318. };
  113319. Template.prototype._getTemplateLocation = function (templateConfig) {
  113320. if (!templateConfig || typeof templateConfig === 'string') {
  113321. return templateConfig;
  113322. }
  113323. else {
  113324. return templateConfig.location;
  113325. }
  113326. };
  113327. return Template;
  113328. }());
  113329. exports.Template = Template;
  113330. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidGVtcGxhdGVNYW5hZ2VyLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vLi4vc3JjL3RlbXBsYXRpbmcvdGVtcGxhdGVNYW5hZ2VyLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7O0FBQ0EsdUNBQTREO0FBQzVELG9DQUE4RDtBQUU5RCx1REFBeUQ7QUFDekQsK0NBQThDO0FBRTlDLCtCQUF1QztBQVl2Qzs7O0dBR0c7QUFDSDtJQThCSSx5QkFBbUIsZ0JBQTZCO1FBQTdCLHFCQUFnQixHQUFoQixnQkFBZ0IsQ0FBYTtRQUM1QyxJQUFJLENBQUMsU0FBUyxHQUFHLEVBQUUsQ0FBQztRQUVwQixJQUFJLENBQUMsY0FBYyxHQUFHLElBQUksc0JBQVUsRUFBWSxDQUFDO1FBQ2pELElBQUksQ0FBQyxnQkFBZ0IsR0FBRyxJQUFJLHNCQUFVLEVBQVksQ0FBQztRQUNuRCxJQUFJLENBQUMscUJBQXFCLEdBQUcsSUFBSSxzQkFBVSxFQUFZLENBQUM7UUFDeEQsSUFBSSxDQUFDLFdBQVcsR0FBRyxJQUFJLHNCQUFVLEVBQW1CLENBQUM7UUFDckQsSUFBSSxDQUFDLG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FBTyxjQUFjLENBQUM7U0FDekI7YUFBTTtZQUNILE9BQU8sY0FBYyxDQUFDLFFBQVEsQ0FBQztTQUNsQztJQUNMLENBQUM7SUFDTCxlQUFDO0FBQUQsQ0FBQyxBQS9XRCxJQStXQztBQS9XWSw0QkFBUSJ9
  113331. /***/ }),
  113332. /* 62 */
  113333. /***/ (function(module, exports, __webpack_require__) {
  113334. /**!
  113335. @license
  113336. handlebars v4.0.11
  113337. Copyright (C) 2011-2017 by Yehuda Katz
  113338. Permission is hereby granted, free of charge, to any person obtaining a copy
  113339. of this software and associated documentation files (the "Software"), to deal
  113340. in the Software without restriction, including without limitation the rights
  113341. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  113342. copies of the Software, and to permit persons to whom the Software is
  113343. furnished to do so, subject to the following conditions:
  113344. The above copyright notice and this permission notice shall be included in
  113345. all copies or substantial portions of the Software.
  113346. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  113347. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  113348. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  113349. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  113350. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  113351. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  113352. THE SOFTWARE.
  113353. */
  113354. (function webpackUniversalModuleDefinition(root, factory) {
  113355. if(true)
  113356. module.exports = factory();
  113357. else if(typeof define === 'function' && define.amd)
  113358. define([], factory);
  113359. else if(typeof exports === 'object')
  113360. exports["Handlebars"] = factory();
  113361. else
  113362. root["Handlebars"] = factory();
  113363. })(this, function() {
  113364. return /******/ (function(modules) { // webpackBootstrap
  113365. /******/ // The module cache
  113366. /******/ var installedModules = {};
  113367. /******/ // The require function
  113368. /******/ function __webpack_require__(moduleId) {
  113369. /******/ // Check if module is in cache
  113370. /******/ if(installedModules[moduleId])
  113371. /******/ return installedModules[moduleId].exports;
  113372. /******/ // Create a new module (and put it into the cache)
  113373. /******/ var module = installedModules[moduleId] = {
  113374. /******/ exports: {},
  113375. /******/ id: moduleId,
  113376. /******/ loaded: false
  113377. /******/ };
  113378. /******/ // Execute the module function
  113379. /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
  113380. /******/ // Flag the module as loaded
  113381. /******/ module.loaded = true;
  113382. /******/ // Return the exports of the module
  113383. /******/ return module.exports;
  113384. /******/ }
  113385. /******/ // expose the modules object (__webpack_modules__)
  113386. /******/ __webpack_require__.m = modules;
  113387. /******/ // expose the module cache
  113388. /******/ __webpack_require__.c = installedModules;
  113389. /******/ // __webpack_public_path__
  113390. /******/ __webpack_require__.p = "";
  113391. /******/ // Load entry module and return exports
  113392. /******/ return __webpack_require__(0);
  113393. /******/ })
  113394. /************************************************************************/
  113395. /******/ ([
  113396. /* 0 */
  113397. /***/ (function(module, exports, __webpack_require__) {
  113398. 'use strict';
  113399. var _interopRequireDefault = __webpack_require__(1)['default'];
  113400. exports.__esModule = true;
  113401. var _handlebarsRuntime = __webpack_require__(2);
  113402. var _handlebarsRuntime2 = _interopRequireDefault(_handlebarsRuntime);
  113403. // Compiler imports
  113404. var _handlebarsCompilerAst = __webpack_require__(35);
  113405. var _handlebarsCompilerAst2 = _interopRequireDefault(_handlebarsCompilerAst);
  113406. var _handlebarsCompilerBase = __webpack_require__(36);
  113407. var _handlebarsCompilerCompiler = __webpack_require__(41);
  113408. var _handlebarsCompilerJavascriptCompiler = __webpack_require__(42);
  113409. var _handlebarsCompilerJavascriptCompiler2 = _interopRequireDefault(_handlebarsCompilerJavascriptCompiler);
  113410. var _handlebarsCompilerVisitor = __webpack_require__(39);
  113411. var _handlebarsCompilerVisitor2 = _interopRequireDefault(_handlebarsCompilerVisitor);
  113412. var _handlebarsNoConflict = __webpack_require__(34);
  113413. var _handlebarsNoConflict2 = _interopRequireDefault(_handlebarsNoConflict);
  113414. var _create = _handlebarsRuntime2['default'].create;
  113415. function create() {
  113416. var hb = _create();
  113417. hb.compile = function (input, options) {
  113418. return _handlebarsCompilerCompiler.compile(input, options, hb);
  113419. };
  113420. hb.precompile = function (input, options) {
  113421. return _handlebarsCompilerCompiler.precompile(input, options, hb);
  113422. };
  113423. hb.AST = _handlebarsCompilerAst2['default'];
  113424. hb.Compiler = _handlebarsCompilerCompiler.Compiler;
  113425. hb.JavaScriptCompiler = _handlebarsCompilerJavascriptCompiler2['default'];
  113426. hb.Parser = _handlebarsCompilerBase.parser;
  113427. hb.parse = _handlebarsCompilerBase.parse;
  113428. return hb;
  113429. }
  113430. var inst = create();
  113431. inst.create = create;
  113432. _handlebarsNoConflict2['default'](inst);
  113433. inst.Visitor = _handlebarsCompilerVisitor2['default'];
  113434. inst['default'] = inst;
  113435. exports['default'] = inst;
  113436. module.exports = exports['default'];
  113437. /***/ }),
  113438. /* 1 */
  113439. /***/ (function(module, exports) {
  113440. "use strict";
  113441. exports["default"] = function (obj) {
  113442. return obj && obj.__esModule ? obj : {
  113443. "default": obj
  113444. };
  113445. };
  113446. exports.__esModule = true;
  113447. /***/ }),
  113448. /* 2 */
  113449. /***/ (function(module, exports, __webpack_require__) {
  113450. 'use strict';
  113451. var _interopRequireWildcard = __webpack_require__(3)['default'];
  113452. var _interopRequireDefault = __webpack_require__(1)['default'];
  113453. exports.__esModule = true;
  113454. var _handlebarsBase = __webpack_require__(4);
  113455. var base = _interopRequireWildcard(_handlebarsBase);
  113456. // Each of these augment the Handlebars object. No need to setup here.
  113457. // (This is done to easily share code between commonjs and browse envs)
  113458. var _handlebarsSafeString = __webpack_require__(21);
  113459. var _handlebarsSafeString2 = _interopRequireDefault(_handlebarsSafeString);
  113460. var _handlebarsException = __webpack_require__(6);
  113461. var _handlebarsException2 = _interopRequireDefault(_handlebarsException);
  113462. var _handlebarsUtils = __webpack_require__(5);
  113463. var Utils = _interopRequireWildcard(_handlebarsUtils);
  113464. var _handlebarsRuntime = __webpack_require__(22);
  113465. var runtime = _interopRequireWildcard(_handlebarsRuntime);
  113466. var _handlebarsNoConflict = __webpack_require__(34);
  113467. var _handlebarsNoConflict2 = _interopRequireDefault(_handlebarsNoConflict);
  113468. // For compatibility and usage outside of module systems, make the Handlebars object a namespace
  113469. function create() {
  113470. var hb = new base.HandlebarsEnvironment();
  113471. Utils.extend(hb, base);
  113472. hb.SafeString = _handlebarsSafeString2['default'];
  113473. hb.Exception = _handlebarsException2['default'];
  113474. hb.Utils = Utils;
  113475. hb.escapeExpression = Utils.escapeExpression;
  113476. hb.VM = runtime;
  113477. hb.template = function (spec) {
  113478. return runtime.template(spec, hb);
  113479. };
  113480. return hb;
  113481. }
  113482. var inst = create();
  113483. inst.create = create;
  113484. _handlebarsNoConflict2['default'](inst);
  113485. inst['default'] = inst;
  113486. exports['default'] = inst;
  113487. module.exports = exports['default'];
  113488. /***/ }),
  113489. /* 3 */
  113490. /***/ (function(module, exports) {
  113491. "use strict";
  113492. exports["default"] = function (obj) {
  113493. if (obj && obj.__esModule) {
  113494. return obj;
  113495. } else {
  113496. var newObj = {};
  113497. if (obj != null) {
  113498. for (var key in obj) {
  113499. if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key];
  113500. }
  113501. }
  113502. newObj["default"] = obj;
  113503. return newObj;
  113504. }
  113505. };
  113506. exports.__esModule = true;
  113507. /***/ }),
  113508. /* 4 */
  113509. /***/ (function(module, exports, __webpack_require__) {
  113510. 'use strict';
  113511. var _interopRequireDefault = __webpack_require__(1)['default'];
  113512. exports.__esModule = true;
  113513. exports.HandlebarsEnvironment = HandlebarsEnvironment;
  113514. var _utils = __webpack_require__(5);
  113515. var _exception = __webpack_require__(6);
  113516. var _exception2 = _interopRequireDefault(_exception);
  113517. var _helpers = __webpack_require__(10);
  113518. var _decorators = __webpack_require__(18);
  113519. var _logger = __webpack_require__(20);
  113520. var _logger2 = _interopRequireDefault(_logger);
  113521. var VERSION = '4.0.11';
  113522. exports.VERSION = VERSION;
  113523. var COMPILER_REVISION = 7;
  113524. exports.COMPILER_REVISION = COMPILER_REVISION;
  113525. var REVISION_CHANGES = {
  113526. 1: '<= 1.0.rc.2', // 1.0.rc.2 is actually rev2 but doesn't report it
  113527. 2: '== 1.0.0-rc.3',
  113528. 3: '== 1.0.0-rc.4',
  113529. 4: '== 1.x.x',
  113530. 5: '== 2.0.0-alpha.x',
  113531. 6: '>= 2.0.0-beta.1',
  113532. 7: '>= 4.0.0'
  113533. };
  113534. exports.REVISION_CHANGES = REVISION_CHANGES;
  113535. var objectType = '[object Object]';
  113536. function HandlebarsEnvironment(helpers, partials, decorators) {
  113537. this.helpers = helpers || {};
  113538. this.partials = partials || {};
  113539. this.decorators = decorators || {};
  113540. _helpers.registerDefaultHelpers(this);
  113541. _decorators.registerDefaultDecorators(this);
  113542. }
  113543. HandlebarsEnvironment.prototype = {
  113544. constructor: HandlebarsEnvironment,
  113545. logger: _logger2['default'],
  113546. log: _logger2['default'].log,
  113547. registerHelper: function registerHelper(name, fn) {
  113548. if (_utils.toString.call(name) === objectType) {
  113549. if (fn) {
  113550. throw new _exception2['default']('Arg not supported with multiple helpers');
  113551. }
  113552. _utils.extend(this.helpers, name);
  113553. } else {
  113554. this.helpers[name] = fn;
  113555. }
  113556. },
  113557. unregisterHelper: function unregisterHelper(name) {
  113558. delete this.helpers[name];
  113559. },
  113560. registerPartial: function registerPartial(name, partial) {
  113561. if (_utils.toString.call(name) === objectType) {
  113562. _utils.extend(this.partials, name);
  113563. } else {
  113564. if (typeof partial === 'undefined') {
  113565. throw new _exception2['default']('Attempting to register a partial called "' + name + '" as undefined');
  113566. }
  113567. this.partials[name] = partial;
  113568. }
  113569. },
  113570. unregisterPartial: function unregisterPartial(name) {
  113571. delete this.partials[name];
  113572. },
  113573. registerDecorator: function registerDecorator(name, fn) {
  113574. if (_utils.toString.call(name) === objectType) {
  113575. if (fn) {
  113576. throw new _exception2['default']('Arg not supported with multiple decorators');
  113577. }
  113578. _utils.extend(this.decorators, name);
  113579. } else {
  113580. this.decorators[name] = fn;
  113581. }
  113582. },
  113583. unregisterDecorator: function unregisterDecorator(name) {
  113584. delete this.decorators[name];
  113585. }
  113586. };
  113587. var log = _logger2['default'].log;
  113588. exports.log = log;
  113589. exports.createFrame = _utils.createFrame;
  113590. exports.logger = _logger2['default'];
  113591. /***/ }),
  113592. /* 5 */
  113593. /***/ (function(module, exports) {
  113594. 'use strict';
  113595. exports.__esModule = true;
  113596. exports.extend = extend;
  113597. exports.indexOf = indexOf;
  113598. exports.escapeExpression = escapeExpression;
  113599. exports.isEmpty = isEmpty;
  113600. exports.createFrame = createFrame;
  113601. exports.blockParams = blockParams;
  113602. exports.appendContextPath = appendContextPath;
  113603. var escape = {
  113604. '&': '&amp;',
  113605. '<': '&lt;',
  113606. '>': '&gt;',
  113607. '"': '&quot;',
  113608. "'": '&#x27;',
  113609. '`': '&#x60;',
  113610. '=': '&#x3D;'
  113611. };
  113612. var badChars = /[&<>"'`=]/g,
  113613. possible = /[&<>"'`=]/;
  113614. function escapeChar(chr) {
  113615. return escape[chr];
  113616. }
  113617. function extend(obj /* , ...source */) {
  113618. for (var i = 1; i < arguments.length; i++) {
  113619. for (var key in arguments[i]) {
  113620. if (Object.prototype.hasOwnProperty.call(arguments[i], key)) {
  113621. obj[key] = arguments[i][key];
  113622. }
  113623. }
  113624. }
  113625. return obj;
  113626. }
  113627. var toString = Object.prototype.toString;
  113628. exports.toString = toString;
  113629. // Sourced from lodash
  113630. // https://github.com/bestiejs/lodash/blob/master/LICENSE.txt
  113631. /* eslint-disable func-style */
  113632. var isFunction = function isFunction(value) {
  113633. return typeof value === 'function';
  113634. };
  113635. // fallback for older versions of Chrome and Safari
  113636. /* istanbul ignore next */
  113637. if (isFunction(/x/)) {
  113638. exports.isFunction = isFunction = function (value) {
  113639. return typeof value === 'function' && toString.call(value) === '[object Function]';
  113640. };
  113641. }
  113642. exports.isFunction = isFunction;
  113643. /* eslint-enable func-style */
  113644. /* istanbul ignore next */
  113645. var isArray = Array.isArray || function (value) {
  113646. return value && typeof value === 'object' ? toString.call(value) === '[object Array]' : false;
  113647. };
  113648. exports.isArray = isArray;
  113649. // Older IE versions do not directly support indexOf so we must implement our own, sadly.
  113650. function indexOf(array, value) {
  113651. for (var i = 0, len = array.length; i < len; i++) {
  113652. if (array[i] === value) {
  113653. return i;
  113654. }
  113655. }
  113656. return -1;
  113657. }
  113658. function escapeExpression(string) {
  113659. if (typeof string !== 'string') {
  113660. // don't escape SafeStrings, since they're already safe
  113661. if (string && string.toHTML) {
  113662. return string.toHTML();
  113663. } else if (string == null) {
  113664. return '';
  113665. } else if (!string) {
  113666. return string + '';
  113667. }
  113668. // Force a string conversion as this will be done by the append regardless and
  113669. // the regex test will do this transparently behind the scenes, causing issues if
  113670. // an object's to string has escaped characters in it.
  113671. string = '' + string;
  113672. }
  113673. if (!possible.test(string)) {
  113674. return string;
  113675. }
  113676. return string.replace(badChars, escapeChar);
  113677. }
  113678. function isEmpty(value) {
  113679. if (!value && value !== 0) {
  113680. return true;
  113681. } else if (isArray(value) && value.length === 0) {
  113682. return true;
  113683. } else {
  113684. return false;
  113685. }
  113686. }
  113687. function createFrame(object) {
  113688. var frame = extend({}, object);
  113689. frame._parent = object;
  113690. return frame;
  113691. }
  113692. function blockParams(params, ids) {
  113693. params.path = ids;
  113694. return params;
  113695. }
  113696. function appendContextPath(contextPath, id) {
  113697. return (contextPath ? contextPath + '.' : '') + id;
  113698. }
  113699. /***/ }),
  113700. /* 6 */
  113701. /***/ (function(module, exports, __webpack_require__) {
  113702. 'use strict';
  113703. var _Object$defineProperty = __webpack_require__(7)['default'];
  113704. exports.__esModule = true;
  113705. var errorProps = ['description', 'fileName', 'lineNumber', 'message', 'name', 'number', 'stack'];
  113706. function Exception(message, node) {
  113707. var loc = node && node.loc,
  113708. line = undefined,
  113709. column = undefined;
  113710. if (loc) {
  113711. line = loc.start.line;
  113712. column = loc.start.column;
  113713. message += ' - ' + line + ':' + column;
  113714. }
  113715. var tmp = Error.prototype.constructor.call(this, message);
  113716. // Unfortunately errors are not enumerable in Chrome (at least), so `for prop in tmp` doesn't work.
  113717. for (var idx = 0; idx < errorProps.length; idx++) {
  113718. this[errorProps[idx]] = tmp[errorProps[idx]];
  113719. }
  113720. /* istanbul ignore else */
  113721. if (Error.captureStackTrace) {
  113722. Error.captureStackTrace(this, Exception);
  113723. }
  113724. try {
  113725. if (loc) {
  113726. this.lineNumber = line;
  113727. // Work around issue under safari where we can't directly set the column value
  113728. /* istanbul ignore next */
  113729. if (_Object$defineProperty) {
  113730. Object.defineProperty(this, 'column', {
  113731. value: column,
  113732. enumerable: true
  113733. });
  113734. } else {
  113735. this.column = column;
  113736. }
  113737. }
  113738. } catch (nop) {
  113739. /* Ignore if the browser is very particular */
  113740. }
  113741. }
  113742. Exception.prototype = new Error();
  113743. exports['default'] = Exception;
  113744. module.exports = exports['default'];
  113745. /***/ }),
  113746. /* 7 */
  113747. /***/ (function(module, exports, __webpack_require__) {
  113748. module.exports = { "default": __webpack_require__(8), __esModule: true };
  113749. /***/ }),
  113750. /* 8 */
  113751. /***/ (function(module, exports, __webpack_require__) {
  113752. var $ = __webpack_require__(9);
  113753. module.exports = function defineProperty(it, key, desc){
  113754. return $.setDesc(it, key, desc);
  113755. };
  113756. /***/ }),
  113757. /* 9 */
  113758. /***/ (function(module, exports) {
  113759. var $Object = Object;
  113760. module.exports = {
  113761. create: $Object.create,
  113762. getProto: $Object.getPrototypeOf,
  113763. isEnum: {}.propertyIsEnumerable,
  113764. getDesc: $Object.getOwnPropertyDescriptor,
  113765. setDesc: $Object.defineProperty,
  113766. setDescs: $Object.defineProperties,
  113767. getKeys: $Object.keys,
  113768. getNames: $Object.getOwnPropertyNames,
  113769. getSymbols: $Object.getOwnPropertySymbols,
  113770. each: [].forEach
  113771. };
  113772. /***/ }),
  113773. /* 10 */
  113774. /***/ (function(module, exports, __webpack_require__) {
  113775. 'use strict';
  113776. var _interopRequireDefault = __webpack_require__(1)['default'];
  113777. exports.__esModule = true;
  113778. exports.registerDefaultHelpers = registerDefaultHelpers;
  113779. var _helpersBlockHelperMissing = __webpack_require__(11);
  113780. var _helpersBlockHelperMissing2 = _interopRequireDefault(_helpersBlockHelperMissing);
  113781. var _helpersEach = __webpack_require__(12);
  113782. var _helpersEach2 = _interopRequireDefault(_helpersEach);
  113783. var _helpersHelperMissing = __webpack_require__(13);
  113784. var _helpersHelperMissing2 = _interopRequireDefault(_helpersHelperMissing);
  113785. var _helpersIf = __webpack_require__(14);
  113786. var _helpersIf2 = _interopRequireDefault(_helpersIf);
  113787. var _helpersLog = __webpack_require__(15);
  113788. var _helpersLog2 = _interopRequireDefault(_helpersLog);
  113789. var _helpersLookup = __webpack_require__(16);
  113790. var _helpersLookup2 = _interopRequireDefault(_helpersLookup);
  113791. var _helpersWith = __webpack_require__(17);
  113792. var _helpersWith2 = _interopRequireDefault(_helpersWith);
  113793. function registerDefaultHelpers(instance) {
  113794. _helpersBlockHelperMissing2['default'](instance);
  113795. _helpersEach2['default'](instance);
  113796. _helpersHelperMissing2['default'](instance);
  113797. _helpersIf2['default'](instance);
  113798. _helpersLog2['default'](instance);
  113799. _helpersLookup2['default'](instance);
  113800. _helpersWith2['default'](instance);
  113801. }
  113802. /***/ }),
  113803. /* 11 */
  113804. /***/ (function(module, exports, __webpack_require__) {
  113805. 'use strict';
  113806. exports.__esModule = true;
  113807. var _utils = __webpack_require__(5);
  113808. exports['default'] = function (instance) {
  113809. instance.registerHelper('blockHelperMissing', function (context, options) {
  113810. var inverse = options.inverse,
  113811. fn = options.fn;
  113812. if (context === true) {
  113813. return fn(this);
  113814. } else if (context === false || context == null) {
  113815. return inverse(this);
  113816. } else if (_utils.isArray(context)) {
  113817. if (context.length > 0) {
  113818. if (options.ids) {
  113819. options.ids = [options.name];
  113820. }
  113821. return instance.helpers.each(context, options);
  113822. } else {
  113823. return inverse(this);
  113824. }
  113825. } else {
  113826. if (options.data && options.ids) {
  113827. var data = _utils.createFrame(options.data);
  113828. data.contextPath = _utils.appendContextPath(options.data.contextPath, options.name);
  113829. options = { data: data };
  113830. }
  113831. return fn(context, options);
  113832. }
  113833. });
  113834. };
  113835. module.exports = exports['default'];
  113836. /***/ }),
  113837. /* 12 */
  113838. /***/ (function(module, exports, __webpack_require__) {
  113839. 'use strict';
  113840. var _interopRequireDefault = __webpack_require__(1)['default'];
  113841. exports.__esModule = true;
  113842. var _utils = __webpack_require__(5);
  113843. var _exception = __webpack_require__(6);
  113844. var _exception2 = _interopRequireDefault(_exception);
  113845. exports['default'] = function (instance) {
  113846. instance.registerHelper('each', function (context, options) {
  113847. if (!options) {
  113848. throw new _exception2['default']('Must pass iterator to #each');
  113849. }
  113850. var fn = options.fn,
  113851. inverse = options.inverse,
  113852. i = 0,
  113853. ret = '',
  113854. data = undefined,
  113855. contextPath = undefined;
  113856. if (options.data && options.ids) {
  113857. contextPath = _utils.appendContextPath(options.data.contextPath, options.ids[0]) + '.';
  113858. }
  113859. if (_utils.isFunction(context)) {
  113860. context = context.call(this);
  113861. }
  113862. if (options.data) {
  113863. data = _utils.createFrame(options.data);
  113864. }
  113865. function execIteration(field, index, last) {
  113866. if (data) {
  113867. data.key = field;
  113868. data.index = index;
  113869. data.first = index === 0;
  113870. data.last = !!last;
  113871. if (contextPath) {
  113872. data.contextPath = contextPath + field;
  113873. }
  113874. }
  113875. ret = ret + fn(context[field], {
  113876. data: data,
  113877. blockParams: _utils.blockParams([context[field], field], [contextPath + field, null])
  113878. });
  113879. }
  113880. if (context && typeof context === 'object') {
  113881. if (_utils.isArray(context)) {
  113882. for (var j = context.length; i < j; i++) {
  113883. if (i in context) {
  113884. execIteration(i, i, i === context.length - 1);
  113885. }
  113886. }
  113887. } else {
  113888. var priorKey = undefined;
  113889. for (var key in context) {
  113890. if (context.hasOwnProperty(key)) {
  113891. // We're running the iterations one step out of sync so we can detect
  113892. // the last iteration without have to scan the object twice and create
  113893. // an itermediate keys array.
  113894. if (priorKey !== undefined) {
  113895. execIteration(priorKey, i - 1);
  113896. }
  113897. priorKey = key;
  113898. i++;
  113899. }
  113900. }
  113901. if (priorKey !== undefined) {
  113902. execIteration(priorKey, i - 1, true);
  113903. }
  113904. }
  113905. }
  113906. if (i === 0) {
  113907. ret = inverse(this);
  113908. }
  113909. return ret;
  113910. });
  113911. };
  113912. module.exports = exports['default'];
  113913. /***/ }),
  113914. /* 13 */
  113915. /***/ (function(module, exports, __webpack_require__) {
  113916. 'use strict';
  113917. var _interopRequireDefault = __webpack_require__(1)['default'];
  113918. exports.__esModule = true;
  113919. var _exception = __webpack_require__(6);
  113920. var _exception2 = _interopRequireDefault(_exception);
  113921. exports['default'] = function (instance) {
  113922. instance.registerHelper('helperMissing', function () /* [args, ]options */{
  113923. if (arguments.length === 1) {
  113924. // A missing field in a {{foo}} construct.
  113925. return undefined;
  113926. } else {
  113927. // Someone is actually trying to call something, blow up.
  113928. throw new _exception2['default']('Missing helper: "' + arguments[arguments.length - 1].name + '"');
  113929. }
  113930. });
  113931. };
  113932. module.exports = exports['default'];
  113933. /***/ }),
  113934. /* 14 */
  113935. /***/ (function(module, exports, __webpack_require__) {
  113936. 'use strict';
  113937. exports.__esModule = true;
  113938. var _utils = __webpack_require__(5);
  113939. exports['default'] = function (instance) {
  113940. instance.registerHelper('if', function (conditional, options) {
  113941. if (_utils.isFunction(conditional)) {
  113942. conditional = conditional.call(this);
  113943. }
  113944. // Default behavior is to render the positive path if the value is truthy and not empty.
  113945. // The `includeZero` option may be set to treat the condtional as purely not empty based on the
  113946. // behavior of isEmpty. Effectively this determines if 0 is handled by the positive path or negative.
  113947. if (!options.hash.includeZero && !conditional || _utils.isEmpty(conditional)) {
  113948. return options.inverse(this);
  113949. } else {
  113950. return options.fn(this);
  113951. }
  113952. });
  113953. instance.registerHelper('unless', function (conditional, options) {
  113954. return instance.helpers['if'].call(this, conditional, { fn: options.inverse, inverse: options.fn, hash: options.hash });
  113955. });
  113956. };
  113957. module.exports = exports['default'];
  113958. /***/ }),
  113959. /* 15 */
  113960. /***/ (function(module, exports) {
  113961. 'use strict';
  113962. exports.__esModule = true;
  113963. exports['default'] = function (instance) {
  113964. instance.registerHelper('log', function () /* message, options */{
  113965. var args = [undefined],
  113966. options = arguments[arguments.length - 1];
  113967. for (var i = 0; i < arguments.length - 1; i++) {
  113968. args.push(arguments[i]);
  113969. }
  113970. var level = 1;
  113971. if (options.hash.level != null) {
  113972. level = options.hash.level;
  113973. } else if (options.data && options.data.level != null) {
  113974. level = options.data.level;
  113975. }
  113976. args[0] = level;
  113977. instance.log.apply(instance, args);
  113978. });
  113979. };
  113980. module.exports = exports['default'];
  113981. /***/ }),
  113982. /* 16 */
  113983. /***/ (function(module, exports) {
  113984. 'use strict';
  113985. exports.__esModule = true;
  113986. exports['default'] = function (instance) {
  113987. instance.registerHelper('lookup', function (obj, field) {
  113988. return obj && obj[field];
  113989. });
  113990. };
  113991. module.exports = exports['default'];
  113992. /***/ }),
  113993. /* 17 */
  113994. /***/ (function(module, exports, __webpack_require__) {
  113995. 'use strict';
  113996. exports.__esModule = true;
  113997. var _utils = __webpack_require__(5);
  113998. exports['default'] = function (instance) {
  113999. instance.registerHelper('with', function (context, options) {
  114000. if (_utils.isFunction(context)) {
  114001. context = context.call(this);
  114002. }
  114003. var fn = options.fn;
  114004. if (!_utils.isEmpty(context)) {
  114005. var data = options.data;
  114006. if (options.data && options.ids) {
  114007. data = _utils.createFrame(options.data);
  114008. data.contextPath = _utils.appendContextPath(options.data.contextPath, options.ids[0]);
  114009. }
  114010. return fn(context, {
  114011. data: data,
  114012. blockParams: _utils.blockParams([context], [data && data.contextPath])
  114013. });
  114014. } else {
  114015. return options.inverse(this);
  114016. }
  114017. });
  114018. };
  114019. module.exports = exports['default'];
  114020. /***/ }),
  114021. /* 18 */
  114022. /***/ (function(module, exports, __webpack_require__) {
  114023. 'use strict';
  114024. var _interopRequireDefault = __webpack_require__(1)['default'];
  114025. exports.__esModule = true;
  114026. exports.registerDefaultDecorators = registerDefaultDecorators;
  114027. var _decoratorsInline = __webpack_require__(19);
  114028. var _decoratorsInline2 = _interopRequireDefault(_decoratorsInline);
  114029. function registerDefaultDecorators(instance) {
  114030. _decoratorsInline2['default'](instance);
  114031. }
  114032. /***/ }),
  114033. /* 19 */
  114034. /***/ (function(module, exports, __webpack_require__) {
  114035. 'use strict';
  114036. exports.__esModule = true;
  114037. var _utils = __webpack_require__(5);
  114038. exports['default'] = function (instance) {
  114039. instance.registerDecorator('inline', function (fn, props, container, options) {
  114040. var ret = fn;
  114041. if (!props.partials) {
  114042. props.partials = {};
  114043. ret = function (context, options) {
  114044. // Create a new partials stack frame prior to exec.
  114045. var original = container.partials;
  114046. container.partials = _utils.extend({}, original, props.partials);
  114047. var ret = fn(context, options);
  114048. container.partials = original;
  114049. return ret;
  114050. };
  114051. }
  114052. props.partials[options.args[0]] = options.fn;
  114053. return ret;
  114054. });
  114055. };
  114056. module.exports = exports['default'];
  114057. /***/ }),
  114058. /* 20 */
  114059. /***/ (function(module, exports, __webpack_require__) {
  114060. 'use strict';
  114061. exports.__esModule = true;
  114062. var _utils = __webpack_require__(5);
  114063. var logger = {
  114064. methodMap: ['debug', 'info', 'warn', 'error'],
  114065. level: 'info',
  114066. // Maps a given level value to the `methodMap` indexes above.
  114067. lookupLevel: function lookupLevel(level) {
  114068. if (typeof level === 'string') {
  114069. var levelMap = _utils.indexOf(logger.methodMap, level.toLowerCase());
  114070. if (levelMap >= 0) {
  114071. level = levelMap;
  114072. } else {
  114073. level = parseInt(level, 10);
  114074. }
  114075. }
  114076. return level;
  114077. },
  114078. // Can be overridden in the host environment
  114079. log: function log(level) {
  114080. level = logger.lookupLevel(level);
  114081. if (typeof console !== 'undefined' && logger.lookupLevel(logger.level) <= level) {
  114082. var method = logger.methodMap[level];
  114083. if (!console[method]) {
  114084. // eslint-disable-line no-console
  114085. method = 'log';
  114086. }
  114087. for (var _len = arguments.length, message = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  114088. message[_key - 1] = arguments[_key];
  114089. }
  114090. console[method].apply(console, message); // eslint-disable-line no-console
  114091. }
  114092. }
  114093. };
  114094. exports['default'] = logger;
  114095. module.exports = exports['default'];
  114096. /***/ }),
  114097. /* 21 */
  114098. /***/ (function(module, exports) {
  114099. // Build out our basic SafeString type
  114100. 'use strict';
  114101. exports.__esModule = true;
  114102. function SafeString(string) {
  114103. this.string = string;
  114104. }
  114105. SafeString.prototype.toString = SafeString.prototype.toHTML = function () {
  114106. return '' + this.string;
  114107. };
  114108. exports['default'] = SafeString;
  114109. module.exports = exports['default'];
  114110. /***/ }),
  114111. /* 22 */
  114112. /***/ (function(module, exports, __webpack_require__) {
  114113. 'use strict';
  114114. var _Object$seal = __webpack_require__(23)['default'];
  114115. var _interopRequireWildcard = __webpack_require__(3)['default'];
  114116. var _interopRequireDefault = __webpack_require__(1)['default'];
  114117. exports.__esModule = true;
  114118. exports.checkRevision = checkRevision;
  114119. exports.template = template;
  114120. exports.wrapProgram = wrapProgram;
  114121. exports.resolvePartial = resolvePartial;
  114122. exports.invokePartial = invokePartial;
  114123. exports.noop = noop;
  114124. var _utils = __webpack_require__(5);
  114125. var Utils = _interopRequireWildcard(_utils);
  114126. var _exception = __webpack_require__(6);
  114127. var _exception2 = _interopRequireDefault(_exception);
  114128. var _base = __webpack_require__(4);
  114129. function checkRevision(compilerInfo) {
  114130. var compilerRevision = compilerInfo && compilerInfo[0] || 1,
  114131. currentRevision = _base.COMPILER_REVISION;
  114132. if (compilerRevision !== currentRevision) {
  114133. if (compilerRevision < currentRevision) {
  114134. var runtimeVersions = _base.REVISION_CHANGES[currentRevision],
  114135. compilerVersions = _base.REVISION_CHANGES[compilerRevision];
  114136. 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 + ').');
  114137. } else {
  114138. // Use the embedded version info since the runtime doesn't know about this revision yet
  114139. 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] + ').');
  114140. }
  114141. }
  114142. }
  114143. function template(templateSpec, env) {
  114144. /* istanbul ignore next */
  114145. if (!env) {
  114146. throw new _exception2['default']('No environment passed to template');
  114147. }
  114148. if (!templateSpec || !templateSpec.main) {
  114149. throw new _exception2['default']('Unknown template object: ' + typeof templateSpec);
  114150. }
  114151. templateSpec.main.decorator = templateSpec.main_d;
  114152. // Note: Using env.VM references rather than local var references throughout this section to allow
  114153. // for external users to override these as psuedo-supported APIs.
  114154. env.VM.checkRevision(templateSpec.compiler);
  114155. function invokePartialWrapper(partial, context, options) {
  114156. if (options.hash) {
  114157. context = Utils.extend({}, context, options.hash);
  114158. if (options.ids) {
  114159. options.ids[0] = true;
  114160. }
  114161. }
  114162. partial = env.VM.resolvePartial.call(this, partial, context, options);
  114163. var result = env.VM.invokePartial.call(this, partial, context, options);
  114164. if (result == null && env.compile) {
  114165. options.partials[options.name] = env.compile(partial, templateSpec.compilerOptions, env);
  114166. result = options.partials[options.name](context, options);
  114167. }
  114168. if (result != null) {
  114169. if (options.indent) {
  114170. var lines = result.split('\n');
  114171. for (var i = 0, l = lines.length; i < l; i++) {
  114172. if (!lines[i] && i + 1 === l) {
  114173. break;
  114174. }
  114175. lines[i] = options.indent + lines[i];
  114176. }
  114177. result = lines.join('\n');
  114178. }
  114179. return result;
  114180. } else {
  114181. throw new _exception2['default']('The partial ' + options.name + ' could not be compiled when running in runtime-only mode');
  114182. }
  114183. }
  114184. // Just add water
  114185. var container = {
  114186. strict: function strict(obj, name) {
  114187. if (!(name in obj)) {
  114188. throw new _exception2['default']('"' + name + '" not defined in ' + obj);
  114189. }
  114190. return obj[name];
  114191. },
  114192. lookup: function lookup(depths, name) {
  114193. var len = depths.length;
  114194. for (var i = 0; i < len; i++) {
  114195. if (depths[i] && depths[i][name] != null) {
  114196. return depths[i][name];
  114197. }
  114198. }
  114199. },
  114200. lambda: function lambda(current, context) {
  114201. return typeof current === 'function' ? current.call(context) : current;
  114202. },
  114203. escapeExpression: Utils.escapeExpression,
  114204. invokePartial: invokePartialWrapper,
  114205. fn: function fn(i) {
  114206. var ret = templateSpec[i];
  114207. ret.decorator = templateSpec[i + '_d'];
  114208. return ret;
  114209. },
  114210. programs: [],
  114211. program: function program(i, data, declaredBlockParams, blockParams, depths) {
  114212. var programWrapper = this.programs[i],
  114213. fn = this.fn(i);
  114214. if (data || depths || blockParams || declaredBlockParams) {
  114215. programWrapper = wrapProgram(this, i, fn, data, declaredBlockParams, blockParams, depths);
  114216. } else if (!programWrapper) {
  114217. programWrapper = this.programs[i] = wrapProgram(this, i, fn);
  114218. }
  114219. return programWrapper;
  114220. },
  114221. data: function data(value, depth) {
  114222. while (value && depth--) {
  114223. value = value._parent;
  114224. }
  114225. return value;
  114226. },
  114227. merge: function merge(param, common) {
  114228. var obj = param || common;
  114229. if (param && common && param !== common) {
  114230. obj = Utils.extend({}, common, param);
  114231. }
  114232. return obj;
  114233. },
  114234. // An empty object to use as replacement for null-contexts
  114235. nullContext: _Object$seal({}),
  114236. noop: env.VM.noop,
  114237. compilerInfo: templateSpec.compiler
  114238. };
  114239. function ret(context) {
  114240. var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
  114241. var data = options.data;
  114242. ret._setup(options);
  114243. if (!options.partial && templateSpec.useData) {
  114244. data = initData(context, data);
  114245. }
  114246. var depths = undefined,
  114247. blockParams = templateSpec.useBlockParams ? [] : undefined;
  114248. if (templateSpec.useDepths) {
  114249. if (options.depths) {
  114250. depths = context != options.depths[0] ? [context].concat(options.depths) : options.depths;
  114251. } else {
  114252. depths = [context];
  114253. }
  114254. }
  114255. function main(context /*, options*/) {
  114256. return '' + templateSpec.main(container, context, container.helpers, container.partials, data, blockParams, depths);
  114257. }
  114258. main = executeDecorators(templateSpec.main, main, container, options.depths || [], data, blockParams);
  114259. return main(context, options);
  114260. }
  114261. ret.isTop = true;
  114262. ret._setup = function (options) {
  114263. if (!options.partial) {
  114264. container.helpers = container.merge(options.helpers, env.helpers);
  114265. if (templateSpec.usePartial) {
  114266. container.partials = container.merge(options.partials, env.partials);
  114267. }
  114268. if (templateSpec.usePartial || templateSpec.useDecorators) {
  114269. container.decorators = container.merge(options.decorators, env.decorators);
  114270. }
  114271. } else {
  114272. container.helpers = options.helpers;
  114273. container.partials = options.partials;
  114274. container.decorators = options.decorators;
  114275. }
  114276. };
  114277. ret._child = function (i, data, blockParams, depths) {
  114278. if (templateSpec.useBlockParams && !blockParams) {
  114279. throw new _exception2['default']('must pass block params');
  114280. }
  114281. if (templateSpec.useDepths && !depths) {
  114282. throw new _exception2['default']('must pass parent depths');
  114283. }
  114284. return wrapProgram(container, i, templateSpec[i], data, 0, blockParams, depths);
  114285. };
  114286. return ret;
  114287. }
  114288. function wrapProgram(container, i, fn, data, declaredBlockParams, blockParams, depths) {
  114289. function prog(context) {
  114290. var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
  114291. var currentDepths = depths;
  114292. if (depths && context != depths[0] && !(context === container.nullContext && depths[0] === null)) {
  114293. currentDepths = [context].concat(depths);
  114294. }
  114295. return fn(container, context, container.helpers, container.partials, options.data || data, blockParams && [options.blockParams].concat(blockParams), currentDepths);
  114296. }
  114297. prog = executeDecorators(fn, prog, container, depths, data, blockParams);
  114298. prog.program = i;
  114299. prog.depth = depths ? depths.length : 0;
  114300. prog.blockParams = declaredBlockParams || 0;
  114301. return prog;
  114302. }
  114303. function resolvePartial(partial, context, options) {
  114304. if (!partial) {
  114305. if (options.name === '@partial-block') {
  114306. partial = options.data['partial-block'];
  114307. } else {
  114308. partial = options.partials[options.name];
  114309. }
  114310. } else if (!partial.call && !options.name) {
  114311. // This is a dynamic partial that returned a string
  114312. options.name = partial;
  114313. partial = options.partials[partial];
  114314. }
  114315. return partial;
  114316. }
  114317. function invokePartial(partial, context, options) {
  114318. // Use the current closure context to save the partial-block if this partial
  114319. var currentPartialBlock = options.data && options.data['partial-block'];
  114320. options.partial = true;
  114321. if (options.ids) {
  114322. options.data.contextPath = options.ids[0] || options.data.contextPath;
  114323. }
  114324. var partialBlock = undefined;
  114325. if (options.fn && options.fn !== noop) {
  114326. (function () {
  114327. options.data = _base.createFrame(options.data);
  114328. // Wrapper function to get access to currentPartialBlock from the closure
  114329. var fn = options.fn;
  114330. partialBlock = options.data['partial-block'] = function partialBlockWrapper(context) {
  114331. var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
  114332. // Restore the partial-block from the closure for the execution of the block
  114333. // i.e. the part inside the block of the partial call.
  114334. options.data = _base.createFrame(options.data);
  114335. options.data['partial-block'] = currentPartialBlock;
  114336. return fn(context, options);
  114337. };
  114338. if (fn.partials) {
  114339. options.partials = Utils.extend({}, options.partials, fn.partials);
  114340. }
  114341. })();
  114342. }
  114343. if (partial === undefined && partialBlock) {
  114344. partial = partialBlock;
  114345. }
  114346. if (partial === undefined) {
  114347. throw new _exception2['default']('The partial ' + options.name + ' could not be found');
  114348. } else if (partial instanceof Function) {
  114349. return partial(context, options);
  114350. }
  114351. }
  114352. function noop() {
  114353. return '';
  114354. }
  114355. function initData(context, data) {
  114356. if (!data || !('root' in data)) {
  114357. data = data ? _base.createFrame(data) : {};
  114358. data.root = context;
  114359. }
  114360. return data;
  114361. }
  114362. function executeDecorators(fn, prog, container, depths, data, blockParams) {
  114363. if (fn.decorator) {
  114364. var props = {};
  114365. prog = fn.decorator(prog, props, container, depths && depths[0], data, blockParams, depths);
  114366. Utils.extend(prog, props);
  114367. }
  114368. return prog;
  114369. }
  114370. /***/ }),
  114371. /* 23 */
  114372. /***/ (function(module, exports, __webpack_require__) {
  114373. module.exports = { "default": __webpack_require__(24), __esModule: true };
  114374. /***/ }),
  114375. /* 24 */
  114376. /***/ (function(module, exports, __webpack_require__) {
  114377. __webpack_require__(25);
  114378. module.exports = __webpack_require__(30).Object.seal;
  114379. /***/ }),
  114380. /* 25 */
  114381. /***/ (function(module, exports, __webpack_require__) {
  114382. // 19.1.2.17 Object.seal(O)
  114383. var isObject = __webpack_require__(26);
  114384. __webpack_require__(27)('seal', function($seal){
  114385. return function seal(it){
  114386. return $seal && isObject(it) ? $seal(it) : it;
  114387. };
  114388. });
  114389. /***/ }),
  114390. /* 26 */
  114391. /***/ (function(module, exports) {
  114392. module.exports = function(it){
  114393. return typeof it === 'object' ? it !== null : typeof it === 'function';
  114394. };
  114395. /***/ }),
  114396. /* 27 */
  114397. /***/ (function(module, exports, __webpack_require__) {
  114398. // most Object methods by ES6 should accept primitives
  114399. var $export = __webpack_require__(28)
  114400. , core = __webpack_require__(30)
  114401. , fails = __webpack_require__(33);
  114402. module.exports = function(KEY, exec){
  114403. var fn = (core.Object || {})[KEY] || Object[KEY]
  114404. , exp = {};
  114405. exp[KEY] = exec(fn);
  114406. $export($export.S + $export.F * fails(function(){ fn(1); }), 'Object', exp);
  114407. };
  114408. /***/ }),
  114409. /* 28 */
  114410. /***/ (function(module, exports, __webpack_require__) {
  114411. var global = __webpack_require__(29)
  114412. , core = __webpack_require__(30)
  114413. , ctx = __webpack_require__(31)
  114414. , PROTOTYPE = 'prototype';
  114415. var $export = function(type, name, source){
  114416. var IS_FORCED = type & $export.F
  114417. , IS_GLOBAL = type & $export.G
  114418. , IS_STATIC = type & $export.S
  114419. , IS_PROTO = type & $export.P
  114420. , IS_BIND = type & $export.B
  114421. , IS_WRAP = type & $export.W
  114422. , exports = IS_GLOBAL ? core : core[name] || (core[name] = {})
  114423. , target = IS_GLOBAL ? global : IS_STATIC ? global[name] : (global[name] || {})[PROTOTYPE]
  114424. , key, own, out;
  114425. if(IS_GLOBAL)source = name;
  114426. for(key in source){
  114427. // contains in native
  114428. own = !IS_FORCED && target && key in target;
  114429. if(own && key in exports)continue;
  114430. // export native or passed
  114431. out = own ? target[key] : source[key];
  114432. // prevent global pollution for namespaces
  114433. exports[key] = IS_GLOBAL && typeof target[key] != 'function' ? source[key]
  114434. // bind timers to global for call from export context
  114435. : IS_BIND && own ? ctx(out, global)
  114436. // wrap global constructors for prevent change them in library
  114437. : IS_WRAP && target[key] == out ? (function(C){
  114438. var F = function(param){
  114439. return this instanceof C ? new C(param) : C(param);
  114440. };
  114441. F[PROTOTYPE] = C[PROTOTYPE];
  114442. return F;
  114443. // make static versions for prototype methods
  114444. })(out) : IS_PROTO && typeof out == 'function' ? ctx(Function.call, out) : out;
  114445. if(IS_PROTO)(exports[PROTOTYPE] || (exports[PROTOTYPE] = {}))[key] = out;
  114446. }
  114447. };
  114448. // type bitmap
  114449. $export.F = 1; // forced
  114450. $export.G = 2; // global
  114451. $export.S = 4; // static
  114452. $export.P = 8; // proto
  114453. $export.B = 16; // bind
  114454. $export.W = 32; // wrap
  114455. module.exports = $export;
  114456. /***/ }),
  114457. /* 29 */
  114458. /***/ (function(module, exports) {
  114459. // https://github.com/zloirock/core-js/issues/86#issuecomment-115759028
  114460. var global = module.exports = typeof window != 'undefined' && window.Math == Math
  114461. ? window : typeof self != 'undefined' && self.Math == Math ? self : Function('return this')();
  114462. if(typeof __g == 'number')__g = global; // eslint-disable-line no-undef
  114463. /***/ }),
  114464. /* 30 */
  114465. /***/ (function(module, exports) {
  114466. var core = module.exports = {version: '1.2.6'};
  114467. if(typeof __e == 'number')__e = core; // eslint-disable-line no-undef
  114468. /***/ }),
  114469. /* 31 */
  114470. /***/ (function(module, exports, __webpack_require__) {
  114471. // optional / simple context binding
  114472. var aFunction = __webpack_require__(32);
  114473. module.exports = function(fn, that, length){
  114474. aFunction(fn);
  114475. if(that === undefined)return fn;
  114476. switch(length){
  114477. case 1: return function(a){
  114478. return fn.call(that, a);
  114479. };
  114480. case 2: return function(a, b){
  114481. return fn.call(that, a, b);
  114482. };
  114483. case 3: return function(a, b, c){
  114484. return fn.call(that, a, b, c);
  114485. };
  114486. }
  114487. return function(/* ...args */){
  114488. return fn.apply(that, arguments);
  114489. };
  114490. };
  114491. /***/ }),
  114492. /* 32 */
  114493. /***/ (function(module, exports) {
  114494. module.exports = function(it){
  114495. if(typeof it != 'function')throw TypeError(it + ' is not a function!');
  114496. return it;
  114497. };
  114498. /***/ }),
  114499. /* 33 */
  114500. /***/ (function(module, exports) {
  114501. module.exports = function(exec){
  114502. try {
  114503. return !!exec();
  114504. } catch(e){
  114505. return true;
  114506. }
  114507. };
  114508. /***/ }),
  114509. /* 34 */
  114510. /***/ (function(module, exports) {
  114511. /* WEBPACK VAR INJECTION */(function(global) {/* global window */
  114512. 'use strict';
  114513. exports.__esModule = true;
  114514. exports['default'] = function (Handlebars) {
  114515. /* istanbul ignore next */
  114516. var root = typeof global !== 'undefined' ? global : window,
  114517. $Handlebars = root.Handlebars;
  114518. /* istanbul ignore next */
  114519. Handlebars.noConflict = function () {
  114520. if (root.Handlebars === Handlebars) {
  114521. root.Handlebars = $Handlebars;
  114522. }
  114523. return Handlebars;
  114524. };
  114525. };
  114526. module.exports = exports['default'];
  114527. /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }())))
  114528. /***/ }),
  114529. /* 35 */
  114530. /***/ (function(module, exports) {
  114531. 'use strict';
  114532. exports.__esModule = true;
  114533. var AST = {
  114534. // Public API used to evaluate derived attributes regarding AST nodes
  114535. helpers: {
  114536. // a mustache is definitely a helper if:
  114537. // * it is an eligible helper, and
  114538. // * it has at least one parameter or hash segment
  114539. helperExpression: function helperExpression(node) {
  114540. return node.type === 'SubExpression' || (node.type === 'MustacheStatement' || node.type === 'BlockStatement') && !!(node.params && node.params.length || node.hash);
  114541. },
  114542. scopedId: function scopedId(path) {
  114543. return (/^\.|this\b/.test(path.original)
  114544. );
  114545. },
  114546. // an ID is simple if it only has one part, and that part is not
  114547. // `..` or `this`.
  114548. simpleId: function simpleId(path) {
  114549. return path.parts.length === 1 && !AST.helpers.scopedId(path) && !path.depth;
  114550. }
  114551. }
  114552. };
  114553. // Must be exported as an object rather than the root of the module as the jison lexer
  114554. // must modify the object to operate properly.
  114555. exports['default'] = AST;
  114556. module.exports = exports['default'];
  114557. /***/ }),
  114558. /* 36 */
  114559. /***/ (function(module, exports, __webpack_require__) {
  114560. 'use strict';
  114561. var _interopRequireDefault = __webpack_require__(1)['default'];
  114562. var _interopRequireWildcard = __webpack_require__(3)['default'];
  114563. exports.__esModule = true;
  114564. exports.parse = parse;
  114565. var _parser = __webpack_require__(37);
  114566. var _parser2 = _interopRequireDefault(_parser);
  114567. var _whitespaceControl = __webpack_require__(38);
  114568. var _whitespaceControl2 = _interopRequireDefault(_whitespaceControl);
  114569. var _helpers = __webpack_require__(40);
  114570. var Helpers = _interopRequireWildcard(_helpers);
  114571. var _utils = __webpack_require__(5);
  114572. exports.parser = _parser2['default'];
  114573. var yy = {};
  114574. _utils.extend(yy, Helpers);
  114575. function parse(input, options) {
  114576. // Just return if an already-compiled AST was passed in.
  114577. if (input.type === 'Program') {
  114578. return input;
  114579. }
  114580. _parser2['default'].yy = yy;
  114581. // Altering the shared object here, but this is ok as parser is a sync operation
  114582. yy.locInfo = function (locInfo) {
  114583. return new yy.SourceLocation(options && options.srcName, locInfo);
  114584. };
  114585. var strip = new _whitespaceControl2['default'](options);
  114586. return strip.accept(_parser2['default'].parse(input));
  114587. }
  114588. /***/ }),
  114589. /* 37 */
  114590. /***/ (function(module, exports) {
  114591. // File ignored in coverage tests via setting in .istanbul.yml
  114592. /* Jison generated parser */
  114593. "use strict";
  114594. exports.__esModule = true;
  114595. var handlebars = (function () {
  114596. var parser = { trace: function trace() {},
  114597. yy: {},
  114598. 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 },
  114599. 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" },
  114600. 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]],
  114601. performAction: function anonymous(yytext, yyleng, yylineno, yy, yystate, $$, _$
  114602. /**/) {
  114603. var $0 = $$.length - 1;
  114604. switch (yystate) {
  114605. case 1:
  114606. return $$[$0 - 1];
  114607. break;
  114608. case 2:
  114609. this.$ = yy.prepareProgram($$[$0]);
  114610. break;
  114611. case 3:
  114612. this.$ = $$[$0];
  114613. break;
  114614. case 4:
  114615. this.$ = $$[$0];
  114616. break;
  114617. case 5:
  114618. this.$ = $$[$0];
  114619. break;
  114620. case 6:
  114621. this.$ = $$[$0];
  114622. break;
  114623. case 7:
  114624. this.$ = $$[$0];
  114625. break;
  114626. case 8:
  114627. this.$ = $$[$0];
  114628. break;
  114629. case 9:
  114630. this.$ = {
  114631. type: 'CommentStatement',
  114632. value: yy.stripComment($$[$0]),
  114633. strip: yy.stripFlags($$[$0], $$[$0]),
  114634. loc: yy.locInfo(this._$)
  114635. };
  114636. break;
  114637. case 10:
  114638. this.$ = {
  114639. type: 'ContentStatement',
  114640. original: $$[$0],
  114641. value: $$[$0],
  114642. loc: yy.locInfo(this._$)
  114643. };
  114644. break;
  114645. case 11:
  114646. this.$ = yy.prepareRawBlock($$[$0 - 2], $$[$0 - 1], $$[$0], this._$);
  114647. break;
  114648. case 12:
  114649. this.$ = { path: $$[$0 - 3], params: $$[$0 - 2], hash: $$[$0 - 1] };
  114650. break;
  114651. case 13:
  114652. this.$ = yy.prepareBlock($$[$0 - 3], $$[$0 - 2], $$[$0 - 1], $$[$0], false, this._$);
  114653. break;
  114654. case 14:
  114655. this.$ = yy.prepareBlock($$[$0 - 3], $$[$0 - 2], $$[$0 - 1], $$[$0], true, this._$);
  114656. break;
  114657. case 15:
  114658. this.$ = { open: $$[$0 - 5], path: $$[$0 - 4], params: $$[$0 - 3], hash: $$[$0 - 2], blockParams: $$[$0 - 1], strip: yy.stripFlags($$[$0 - 5], $$[$0]) };
  114659. break;
  114660. case 16:
  114661. this.$ = { path: $$[$0 - 4], params: $$[$0 - 3], hash: $$[$0 - 2], blockParams: $$[$0 - 1], strip: yy.stripFlags($$[$0 - 5], $$[$0]) };
  114662. break;
  114663. case 17:
  114664. this.$ = { path: $$[$0 - 4], params: $$[$0 - 3], hash: $$[$0 - 2], blockParams: $$[$0 - 1], strip: yy.stripFlags($$[$0 - 5], $$[$0]) };
  114665. break;
  114666. case 18:
  114667. this.$ = { strip: yy.stripFlags($$[$0 - 1], $$[$0 - 1]), program: $$[$0] };
  114668. break;
  114669. case 19:
  114670. var inverse = yy.prepareBlock($$[$0 - 2], $$[$0 - 1], $$[$0], $$[$0], false, this._$),
  114671. program = yy.prepareProgram([inverse], $$[$0 - 1].loc);
  114672. program.chained = true;
  114673. this.$ = { strip: $$[$0 - 2].strip, program: program, chain: true };
  114674. break;
  114675. case 20:
  114676. this.$ = $$[$0];
  114677. break;
  114678. case 21:
  114679. this.$ = { path: $$[$0 - 1], strip: yy.stripFlags($$[$0 - 2], $$[$0]) };
  114680. break;
  114681. case 22:
  114682. this.$ = yy.prepareMustache($$[$0 - 3], $$[$0 - 2], $$[$0 - 1], $$[$0 - 4], yy.stripFlags($$[$0 - 4], $$[$0]), this._$);
  114683. break;
  114684. case 23:
  114685. this.$ = yy.prepareMustache($$[$0 - 3], $$[$0 - 2], $$[$0 - 1], $$[$0 - 4], yy.stripFlags($$[$0 - 4], $$[$0]), this._$);
  114686. break;
  114687. case 24:
  114688. this.$ = {
  114689. type: 'PartialStatement',
  114690. name: $$[$0 - 3],
  114691. params: $$[$0 - 2],
  114692. hash: $$[$0 - 1],
  114693. indent: '',
  114694. strip: yy.stripFlags($$[$0 - 4], $$[$0]),
  114695. loc: yy.locInfo(this._$)
  114696. };
  114697. break;
  114698. case 25:
  114699. this.$ = yy.preparePartialBlock($$[$0 - 2], $$[$0 - 1], $$[$0], this._$);
  114700. break;
  114701. case 26:
  114702. this.$ = { path: $$[$0 - 3], params: $$[$0 - 2], hash: $$[$0 - 1], strip: yy.stripFlags($$[$0 - 4], $$[$0]) };
  114703. break;
  114704. case 27:
  114705. this.$ = $$[$0];
  114706. break;
  114707. case 28:
  114708. this.$ = $$[$0];
  114709. break;
  114710. case 29:
  114711. this.$ = {
  114712. type: 'SubExpression',
  114713. path: $$[$0 - 3],
  114714. params: $$[$0 - 2],
  114715. hash: $$[$0 - 1],
  114716. loc: yy.locInfo(this._$)
  114717. };
  114718. break;
  114719. case 30:
  114720. this.$ = { type: 'Hash', pairs: $$[$0], loc: yy.locInfo(this._$) };
  114721. break;
  114722. case 31:
  114723. this.$ = { type: 'HashPair', key: yy.id($$[$0 - 2]), value: $$[$0], loc: yy.locInfo(this._$) };
  114724. break;
  114725. case 32:
  114726. this.$ = yy.id($$[$0 - 1]);
  114727. break;
  114728. case 33:
  114729. this.$ = $$[$0];
  114730. break;
  114731. case 34:
  114732. this.$ = $$[$0];
  114733. break;
  114734. case 35:
  114735. this.$ = { type: 'StringLiteral', value: $$[$0], original: $$[$0], loc: yy.locInfo(this._$) };
  114736. break;
  114737. case 36:
  114738. this.$ = { type: 'NumberLiteral', value: Number($$[$0]), original: Number($$[$0]), loc: yy.locInfo(this._$) };
  114739. break;
  114740. case 37:
  114741. this.$ = { type: 'BooleanLiteral', value: $$[$0] === 'true', original: $$[$0] === 'true', loc: yy.locInfo(this._$) };
  114742. break;
  114743. case 38:
  114744. this.$ = { type: 'UndefinedLiteral', original: undefined, value: undefined, loc: yy.locInfo(this._$) };
  114745. break;
  114746. case 39:
  114747. this.$ = { type: 'NullLiteral', original: null, value: null, loc: yy.locInfo(this._$) };
  114748. break;
  114749. case 40:
  114750. this.$ = $$[$0];
  114751. break;
  114752. case 41:
  114753. this.$ = $$[$0];
  114754. break;
  114755. case 42:
  114756. this.$ = yy.preparePath(true, $$[$0], this._$);
  114757. break;
  114758. case 43:
  114759. this.$ = yy.preparePath(false, $$[$0], this._$);
  114760. break;
  114761. case 44:
  114762. $$[$0 - 2].push({ part: yy.id($$[$0]), original: $$[$0], separator: $$[$0 - 1] });this.$ = $$[$0 - 2];
  114763. break;
  114764. case 45:
  114765. this.$ = [{ part: yy.id($$[$0]), original: $$[$0] }];
  114766. break;
  114767. case 46:
  114768. this.$ = [];
  114769. break;
  114770. case 47:
  114771. $$[$0 - 1].push($$[$0]);
  114772. break;
  114773. case 48:
  114774. this.$ = [$$[$0]];
  114775. break;
  114776. case 49:
  114777. $$[$0 - 1].push($$[$0]);
  114778. break;
  114779. case 50:
  114780. this.$ = [];
  114781. break;
  114782. case 51:
  114783. $$[$0 - 1].push($$[$0]);
  114784. break;
  114785. case 58:
  114786. this.$ = [];
  114787. break;
  114788. case 59:
  114789. $$[$0 - 1].push($$[$0]);
  114790. break;
  114791. case 64:
  114792. this.$ = [];
  114793. break;
  114794. case 65:
  114795. $$[$0 - 1].push($$[$0]);
  114796. break;
  114797. case 70:
  114798. this.$ = [];
  114799. break;
  114800. case 71:
  114801. $$[$0 - 1].push($$[$0]);
  114802. break;
  114803. case 78:
  114804. this.$ = [];
  114805. break;
  114806. case 79:
  114807. $$[$0 - 1].push($$[$0]);
  114808. break;
  114809. case 82:
  114810. this.$ = [];
  114811. break;
  114812. case 83:
  114813. $$[$0 - 1].push($$[$0]);
  114814. break;
  114815. case 86:
  114816. this.$ = [];
  114817. break;
  114818. case 87:
  114819. $$[$0 - 1].push($$[$0]);
  114820. break;
  114821. case 90:
  114822. this.$ = [];
  114823. break;
  114824. case 91:
  114825. $$[$0 - 1].push($$[$0]);
  114826. break;
  114827. case 94:
  114828. this.$ = [];
  114829. break;
  114830. case 95:
  114831. $$[$0 - 1].push($$[$0]);
  114832. break;
  114833. case 98:
  114834. this.$ = [$$[$0]];
  114835. break;
  114836. case 99:
  114837. $$[$0 - 1].push($$[$0]);
  114838. break;
  114839. case 100:
  114840. this.$ = [$$[$0]];
  114841. break;
  114842. case 101:
  114843. $$[$0 - 1].push($$[$0]);
  114844. break;
  114845. }
  114846. },
  114847. 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] }],
  114848. 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] },
  114849. parseError: function parseError(str, hash) {
  114850. throw new Error(str);
  114851. },
  114852. parse: function parse(input) {
  114853. var self = this,
  114854. stack = [0],
  114855. vstack = [null],
  114856. lstack = [],
  114857. table = this.table,
  114858. yytext = "",
  114859. yylineno = 0,
  114860. yyleng = 0,
  114861. recovering = 0,
  114862. TERROR = 2,
  114863. EOF = 1;
  114864. this.lexer.setInput(input);
  114865. this.lexer.yy = this.yy;
  114866. this.yy.lexer = this.lexer;
  114867. this.yy.parser = this;
  114868. if (typeof this.lexer.yylloc == "undefined") this.lexer.yylloc = {};
  114869. var yyloc = this.lexer.yylloc;
  114870. lstack.push(yyloc);
  114871. var ranges = this.lexer.options && this.lexer.options.ranges;
  114872. if (typeof this.yy.parseError === "function") this.parseError = this.yy.parseError;
  114873. function popStack(n) {
  114874. stack.length = stack.length - 2 * n;
  114875. vstack.length = vstack.length - n;
  114876. lstack.length = lstack.length - n;
  114877. }
  114878. function lex() {
  114879. var token;
  114880. token = self.lexer.lex() || 1;
  114881. if (typeof token !== "number") {
  114882. token = self.symbols_[token] || token;
  114883. }
  114884. return token;
  114885. }
  114886. var symbol,
  114887. preErrorSymbol,
  114888. state,
  114889. action,
  114890. a,
  114891. r,
  114892. yyval = {},
  114893. p,
  114894. len,
  114895. newState,
  114896. expected;
  114897. while (true) {
  114898. state = stack[stack.length - 1];
  114899. if (this.defaultActions[state]) {
  114900. action = this.defaultActions[state];
  114901. } else {
  114902. if (symbol === null || typeof symbol == "undefined") {
  114903. symbol = lex();
  114904. }
  114905. action = table[state] && table[state][symbol];
  114906. }
  114907. if (typeof action === "undefined" || !action.length || !action[0]) {
  114908. var errStr = "";
  114909. if (!recovering) {
  114910. expected = [];
  114911. for (p in table[state]) if (this.terminals_[p] && p > 2) {
  114912. expected.push("'" + this.terminals_[p] + "'");
  114913. }
  114914. if (this.lexer.showPosition) {
  114915. errStr = "Parse error on line " + (yylineno + 1) + ":\n" + this.lexer.showPosition() + "\nExpecting " + expected.join(", ") + ", got '" + (this.terminals_[symbol] || symbol) + "'";
  114916. } else {
  114917. errStr = "Parse error on line " + (yylineno + 1) + ": Unexpected " + (symbol == 1 ? "end of input" : "'" + (this.terminals_[symbol] || symbol) + "'");
  114918. }
  114919. this.parseError(errStr, { text: this.lexer.match, token: this.terminals_[symbol] || symbol, line: this.lexer.yylineno, loc: yyloc, expected: expected });
  114920. }
  114921. }
  114922. if (action[0] instanceof Array && action.length > 1) {
  114923. throw new Error("Parse Error: multiple actions possible at state: " + state + ", token: " + symbol);
  114924. }
  114925. switch (action[0]) {
  114926. case 1:
  114927. stack.push(symbol);
  114928. vstack.push(this.lexer.yytext);
  114929. lstack.push(this.lexer.yylloc);
  114930. stack.push(action[1]);
  114931. symbol = null;
  114932. if (!preErrorSymbol) {
  114933. yyleng = this.lexer.yyleng;
  114934. yytext = this.lexer.yytext;
  114935. yylineno = this.lexer.yylineno;
  114936. yyloc = this.lexer.yylloc;
  114937. if (recovering > 0) recovering--;
  114938. } else {
  114939. symbol = preErrorSymbol;
  114940. preErrorSymbol = null;
  114941. }
  114942. break;
  114943. case 2:
  114944. len = this.productions_[action[1]][1];
  114945. yyval.$ = vstack[vstack.length - len];
  114946. 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 };
  114947. if (ranges) {
  114948. yyval._$.range = [lstack[lstack.length - (len || 1)].range[0], lstack[lstack.length - 1].range[1]];
  114949. }
  114950. r = this.performAction.call(yyval, yytext, yyleng, yylineno, this.yy, action[1], vstack, lstack);
  114951. if (typeof r !== "undefined") {
  114952. return r;
  114953. }
  114954. if (len) {
  114955. stack = stack.slice(0, -1 * len * 2);
  114956. vstack = vstack.slice(0, -1 * len);
  114957. lstack = lstack.slice(0, -1 * len);
  114958. }
  114959. stack.push(this.productions_[action[1]][0]);
  114960. vstack.push(yyval.$);
  114961. lstack.push(yyval._$);
  114962. newState = table[stack[stack.length - 2]][stack[stack.length - 1]];
  114963. stack.push(newState);
  114964. break;
  114965. case 3:
  114966. return true;
  114967. }
  114968. }
  114969. return true;
  114970. }
  114971. };
  114972. /* Jison generated lexer */
  114973. var lexer = (function () {
  114974. var lexer = { EOF: 1,
  114975. parseError: function parseError(str, hash) {
  114976. if (this.yy.parser) {
  114977. this.yy.parser.parseError(str, hash);
  114978. } else {
  114979. throw new Error(str);
  114980. }
  114981. },
  114982. setInput: function setInput(input) {
  114983. this._input = input;
  114984. this._more = this._less = this.done = false;
  114985. this.yylineno = this.yyleng = 0;
  114986. this.yytext = this.matched = this.match = '';
  114987. this.conditionStack = ['INITIAL'];
  114988. this.yylloc = { first_line: 1, first_column: 0, last_line: 1, last_column: 0 };
  114989. if (this.options.ranges) this.yylloc.range = [0, 0];
  114990. this.offset = 0;
  114991. return this;
  114992. },
  114993. input: function input() {
  114994. var ch = this._input[0];
  114995. this.yytext += ch;
  114996. this.yyleng++;
  114997. this.offset++;
  114998. this.match += ch;
  114999. this.matched += ch;
  115000. var lines = ch.match(/(?:\r\n?|\n).*/g);
  115001. if (lines) {
  115002. this.yylineno++;
  115003. this.yylloc.last_line++;
  115004. } else {
  115005. this.yylloc.last_column++;
  115006. }
  115007. if (this.options.ranges) this.yylloc.range[1]++;
  115008. this._input = this._input.slice(1);
  115009. return ch;
  115010. },
  115011. unput: function unput(ch) {
  115012. var len = ch.length;
  115013. var lines = ch.split(/(?:\r\n?|\n)/g);
  115014. this._input = ch + this._input;
  115015. this.yytext = this.yytext.substr(0, this.yytext.length - len - 1);
  115016. //this.yyleng -= len;
  115017. this.offset -= len;
  115018. var oldLines = this.match.split(/(?:\r\n?|\n)/g);
  115019. this.match = this.match.substr(0, this.match.length - 1);
  115020. this.matched = this.matched.substr(0, this.matched.length - 1);
  115021. if (lines.length - 1) this.yylineno -= lines.length - 1;
  115022. var r = this.yylloc.range;
  115023. this.yylloc = { first_line: this.yylloc.first_line,
  115024. last_line: this.yylineno + 1,
  115025. first_column: this.yylloc.first_column,
  115026. 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
  115027. };
  115028. if (this.options.ranges) {
  115029. this.yylloc.range = [r[0], r[0] + this.yyleng - len];
  115030. }
  115031. return this;
  115032. },
  115033. more: function more() {
  115034. this._more = true;
  115035. return this;
  115036. },
  115037. less: function less(n) {
  115038. this.unput(this.match.slice(n));
  115039. },
  115040. pastInput: function pastInput() {
  115041. var past = this.matched.substr(0, this.matched.length - this.match.length);
  115042. return (past.length > 20 ? '...' : '') + past.substr(-20).replace(/\n/g, "");
  115043. },
  115044. upcomingInput: function upcomingInput() {
  115045. var next = this.match;
  115046. if (next.length < 20) {
  115047. next += this._input.substr(0, 20 - next.length);
  115048. }
  115049. return (next.substr(0, 20) + (next.length > 20 ? '...' : '')).replace(/\n/g, "");
  115050. },
  115051. showPosition: function showPosition() {
  115052. var pre = this.pastInput();
  115053. var c = new Array(pre.length + 1).join("-");
  115054. return pre + this.upcomingInput() + "\n" + c + "^";
  115055. },
  115056. next: function next() {
  115057. if (this.done) {
  115058. return this.EOF;
  115059. }
  115060. if (!this._input) this.done = true;
  115061. var token, match, tempMatch, index, col, lines;
  115062. if (!this._more) {
  115063. this.yytext = '';
  115064. this.match = '';
  115065. }
  115066. var rules = this._currentRules();
  115067. for (var i = 0; i < rules.length; i++) {
  115068. tempMatch = this._input.match(this.rules[rules[i]]);
  115069. if (tempMatch && (!match || tempMatch[0].length > match[0].length)) {
  115070. match = tempMatch;
  115071. index = i;
  115072. if (!this.options.flex) break;
  115073. }
  115074. }
  115075. if (match) {
  115076. lines = match[0].match(/(?:\r\n?|\n).*/g);
  115077. if (lines) this.yylineno += lines.length;
  115078. this.yylloc = { first_line: this.yylloc.last_line,
  115079. last_line: this.yylineno + 1,
  115080. first_column: this.yylloc.last_column,
  115081. last_column: lines ? lines[lines.length - 1].length - lines[lines.length - 1].match(/\r?\n?/)[0].length : this.yylloc.last_column + match[0].length };
  115082. this.yytext += match[0];
  115083. this.match += match[0];
  115084. this.matches = match;
  115085. this.yyleng = this.yytext.length;
  115086. if (this.options.ranges) {
  115087. this.yylloc.range = [this.offset, this.offset += this.yyleng];
  115088. }
  115089. this._more = false;
  115090. this._input = this._input.slice(match[0].length);
  115091. this.matched += match[0];
  115092. token = this.performAction.call(this, this.yy, this, rules[index], this.conditionStack[this.conditionStack.length - 1]);
  115093. if (this.done && this._input) this.done = false;
  115094. if (token) return token;else return;
  115095. }
  115096. if (this._input === "") {
  115097. return this.EOF;
  115098. } else {
  115099. return this.parseError('Lexical error on line ' + (this.yylineno + 1) + '. Unrecognized text.\n' + this.showPosition(), { text: "", token: null, line: this.yylineno });
  115100. }
  115101. },
  115102. lex: function lex() {
  115103. var r = this.next();
  115104. if (typeof r !== 'undefined') {
  115105. return r;
  115106. } else {
  115107. return this.lex();
  115108. }
  115109. },
  115110. begin: function begin(condition) {
  115111. this.conditionStack.push(condition);
  115112. },
  115113. popState: function popState() {
  115114. return this.conditionStack.pop();
  115115. },
  115116. _currentRules: function _currentRules() {
  115117. return this.conditions[this.conditionStack[this.conditionStack.length - 1]].rules;
  115118. },
  115119. topState: function topState() {
  115120. return this.conditionStack[this.conditionStack.length - 2];
  115121. },
  115122. pushState: function begin(condition) {
  115123. this.begin(condition);
  115124. } };
  115125. lexer.options = {};
  115126. lexer.performAction = function anonymous(yy, yy_, $avoiding_name_collisions, YY_START
  115127. /**/) {
  115128. function strip(start, end) {
  115129. return yy_.yytext = yy_.yytext.substr(start, yy_.yyleng - end);
  115130. }
  115131. var YYSTATE = YY_START;
  115132. switch ($avoiding_name_collisions) {
  115133. case 0:
  115134. if (yy_.yytext.slice(-2) === "\\\\") {
  115135. strip(0, 1);
  115136. this.begin("mu");
  115137. } else if (yy_.yytext.slice(-1) === "\\") {
  115138. strip(0, 1);
  115139. this.begin("emu");
  115140. } else {
  115141. this.begin("mu");
  115142. }
  115143. if (yy_.yytext) return 15;
  115144. break;
  115145. case 1:
  115146. return 15;
  115147. break;
  115148. case 2:
  115149. this.popState();
  115150. return 15;
  115151. break;
  115152. case 3:
  115153. this.begin('raw');return 15;
  115154. break;
  115155. case 4:
  115156. this.popState();
  115157. // Should be using `this.topState()` below, but it currently
  115158. // returns the second top instead of the first top. Opened an
  115159. // issue about it at https://github.com/zaach/jison/issues/291
  115160. if (this.conditionStack[this.conditionStack.length - 1] === 'raw') {
  115161. return 15;
  115162. } else {
  115163. yy_.yytext = yy_.yytext.substr(5, yy_.yyleng - 9);
  115164. return 'END_RAW_BLOCK';
  115165. }
  115166. break;
  115167. case 5:
  115168. return 15;
  115169. break;
  115170. case 6:
  115171. this.popState();
  115172. return 14;
  115173. break;
  115174. case 7:
  115175. return 65;
  115176. break;
  115177. case 8:
  115178. return 68;
  115179. break;
  115180. case 9:
  115181. return 19;
  115182. break;
  115183. case 10:
  115184. this.popState();
  115185. this.begin('raw');
  115186. return 23;
  115187. break;
  115188. case 11:
  115189. return 55;
  115190. break;
  115191. case 12:
  115192. return 60;
  115193. break;
  115194. case 13:
  115195. return 29;
  115196. break;
  115197. case 14:
  115198. return 47;
  115199. break;
  115200. case 15:
  115201. this.popState();return 44;
  115202. break;
  115203. case 16:
  115204. this.popState();return 44;
  115205. break;
  115206. case 17:
  115207. return 34;
  115208. break;
  115209. case 18:
  115210. return 39;
  115211. break;
  115212. case 19:
  115213. return 51;
  115214. break;
  115215. case 20:
  115216. return 48;
  115217. break;
  115218. case 21:
  115219. this.unput(yy_.yytext);
  115220. this.popState();
  115221. this.begin('com');
  115222. break;
  115223. case 22:
  115224. this.popState();
  115225. return 14;
  115226. break;
  115227. case 23:
  115228. return 48;
  115229. break;
  115230. case 24:
  115231. return 73;
  115232. break;
  115233. case 25:
  115234. return 72;
  115235. break;
  115236. case 26:
  115237. return 72;
  115238. break;
  115239. case 27:
  115240. return 87;
  115241. break;
  115242. case 28:
  115243. // ignore whitespace
  115244. break;
  115245. case 29:
  115246. this.popState();return 54;
  115247. break;
  115248. case 30:
  115249. this.popState();return 33;
  115250. break;
  115251. case 31:
  115252. yy_.yytext = strip(1, 2).replace(/\\"/g, '"');return 80;
  115253. break;
  115254. case 32:
  115255. yy_.yytext = strip(1, 2).replace(/\\'/g, "'");return 80;
  115256. break;
  115257. case 33:
  115258. return 85;
  115259. break;
  115260. case 34:
  115261. return 82;
  115262. break;
  115263. case 35:
  115264. return 82;
  115265. break;
  115266. case 36:
  115267. return 83;
  115268. break;
  115269. case 37:
  115270. return 84;
  115271. break;
  115272. case 38:
  115273. return 81;
  115274. break;
  115275. case 39:
  115276. return 75;
  115277. break;
  115278. case 40:
  115279. return 77;
  115280. break;
  115281. case 41:
  115282. return 72;
  115283. break;
  115284. case 42:
  115285. yy_.yytext = yy_.yytext.replace(/\\([\\\]])/g, '$1');return 72;
  115286. break;
  115287. case 43:
  115288. return 'INVALID';
  115289. break;
  115290. case 44:
  115291. return 5;
  115292. break;
  115293. }
  115294. };
  115295. 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\/.)|]))))/, /^(?:\[(\\\]|[^\]])*\])/, /^(?:.)/, /^(?:$)/];
  115296. 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 } };
  115297. return lexer;
  115298. })();
  115299. parser.lexer = lexer;
  115300. function Parser() {
  115301. this.yy = {};
  115302. }Parser.prototype = parser;parser.Parser = Parser;
  115303. return new Parser();
  115304. })();exports["default"] = handlebars;
  115305. module.exports = exports["default"];
  115306. /***/ }),
  115307. /* 38 */
  115308. /***/ (function(module, exports, __webpack_require__) {
  115309. 'use strict';
  115310. var _interopRequireDefault = __webpack_require__(1)['default'];
  115311. exports.__esModule = true;
  115312. var _visitor = __webpack_require__(39);
  115313. var _visitor2 = _interopRequireDefault(_visitor);
  115314. function WhitespaceControl() {
  115315. var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
  115316. this.options = options;
  115317. }
  115318. WhitespaceControl.prototype = new _visitor2['default']();
  115319. WhitespaceControl.prototype.Program = function (program) {
  115320. var doStandalone = !this.options.ignoreStandalone;
  115321. var isRoot = !this.isRootSeen;
  115322. this.isRootSeen = true;
  115323. var body = program.body;
  115324. for (var i = 0, l = body.length; i < l; i++) {
  115325. var current = body[i],
  115326. strip = this.accept(current);
  115327. if (!strip) {
  115328. continue;
  115329. }
  115330. var _isPrevWhitespace = isPrevWhitespace(body, i, isRoot),
  115331. _isNextWhitespace = isNextWhitespace(body, i, isRoot),
  115332. openStandalone = strip.openStandalone && _isPrevWhitespace,
  115333. closeStandalone = strip.closeStandalone && _isNextWhitespace,
  115334. inlineStandalone = strip.inlineStandalone && _isPrevWhitespace && _isNextWhitespace;
  115335. if (strip.close) {
  115336. omitRight(body, i, true);
  115337. }
  115338. if (strip.open) {
  115339. omitLeft(body, i, true);
  115340. }
  115341. if (doStandalone && inlineStandalone) {
  115342. omitRight(body, i);
  115343. if (omitLeft(body, i)) {
  115344. // If we are on a standalone node, save the indent info for partials
  115345. if (current.type === 'PartialStatement') {
  115346. // Pull out the whitespace from the final line
  115347. current.indent = /([ \t]+$)/.exec(body[i - 1].original)[1];
  115348. }
  115349. }
  115350. }
  115351. if (doStandalone && openStandalone) {
  115352. omitRight((current.program || current.inverse).body);
  115353. // Strip out the previous content node if it's whitespace only
  115354. omitLeft(body, i);
  115355. }
  115356. if (doStandalone && closeStandalone) {
  115357. // Always strip the next node
  115358. omitRight(body, i);
  115359. omitLeft((current.inverse || current.program).body);
  115360. }
  115361. }
  115362. return program;
  115363. };
  115364. WhitespaceControl.prototype.BlockStatement = WhitespaceControl.prototype.DecoratorBlock = WhitespaceControl.prototype.PartialBlockStatement = function (block) {
  115365. this.accept(block.program);
  115366. this.accept(block.inverse);
  115367. // Find the inverse program that is involed with whitespace stripping.
  115368. var program = block.program || block.inverse,
  115369. inverse = block.program && block.inverse,
  115370. firstInverse = inverse,
  115371. lastInverse = inverse;
  115372. if (inverse && inverse.chained) {
  115373. firstInverse = inverse.body[0].program;
  115374. // Walk the inverse chain to find the last inverse that is actually in the chain.
  115375. while (lastInverse.chained) {
  115376. lastInverse = lastInverse.body[lastInverse.body.length - 1].program;
  115377. }
  115378. }
  115379. var strip = {
  115380. open: block.openStrip.open,
  115381. close: block.closeStrip.close,
  115382. // Determine the standalone candiacy. Basically flag our content as being possibly standalone
  115383. // so our parent can determine if we actually are standalone
  115384. openStandalone: isNextWhitespace(program.body),
  115385. closeStandalone: isPrevWhitespace((firstInverse || program).body)
  115386. };
  115387. if (block.openStrip.close) {
  115388. omitRight(program.body, null, true);
  115389. }
  115390. if (inverse) {
  115391. var inverseStrip = block.inverseStrip;
  115392. if (inverseStrip.open) {
  115393. omitLeft(program.body, null, true);
  115394. }
  115395. if (inverseStrip.close) {
  115396. omitRight(firstInverse.body, null, true);
  115397. }
  115398. if (block.closeStrip.open) {
  115399. omitLeft(lastInverse.body, null, true);
  115400. }
  115401. // Find standalone else statments
  115402. if (!this.options.ignoreStandalone && isPrevWhitespace(program.body) && isNextWhitespace(firstInverse.body)) {
  115403. omitLeft(program.body);
  115404. omitRight(firstInverse.body);
  115405. }
  115406. } else if (block.closeStrip.open) {
  115407. omitLeft(program.body, null, true);
  115408. }
  115409. return strip;
  115410. };
  115411. WhitespaceControl.prototype.Decorator = WhitespaceControl.prototype.MustacheStatement = function (mustache) {
  115412. return mustache.strip;
  115413. };
  115414. WhitespaceControl.prototype.PartialStatement = WhitespaceControl.prototype.CommentStatement = function (node) {
  115415. /* istanbul ignore next */
  115416. var strip = node.strip || {};
  115417. return {
  115418. inlineStandalone: true,
  115419. open: strip.open,
  115420. close: strip.close
  115421. };
  115422. };
  115423. function isPrevWhitespace(body, i, isRoot) {
  115424. if (i === undefined) {
  115425. i = body.length;
  115426. }
  115427. // Nodes that end with newlines are considered whitespace (but are special
  115428. // cased for strip operations)
  115429. var prev = body[i - 1],
  115430. sibling = body[i - 2];
  115431. if (!prev) {
  115432. return isRoot;
  115433. }
  115434. if (prev.type === 'ContentStatement') {
  115435. return (sibling || !isRoot ? /\r?\n\s*?$/ : /(^|\r?\n)\s*?$/).test(prev.original);
  115436. }
  115437. }
  115438. function isNextWhitespace(body, i, isRoot) {
  115439. if (i === undefined) {
  115440. i = -1;
  115441. }
  115442. var next = body[i + 1],
  115443. sibling = body[i + 2];
  115444. if (!next) {
  115445. return isRoot;
  115446. }
  115447. if (next.type === 'ContentStatement') {
  115448. return (sibling || !isRoot ? /^\s*?\r?\n/ : /^\s*?(\r?\n|$)/).test(next.original);
  115449. }
  115450. }
  115451. // Marks the node to the right of the position as omitted.
  115452. // I.e. {{foo}}' ' will mark the ' ' node as omitted.
  115453. //
  115454. // If i is undefined, then the first child will be marked as such.
  115455. //
  115456. // If mulitple is truthy then all whitespace will be stripped out until non-whitespace
  115457. // content is met.
  115458. function omitRight(body, i, multiple) {
  115459. var current = body[i == null ? 0 : i + 1];
  115460. if (!current || current.type !== 'ContentStatement' || !multiple && current.rightStripped) {
  115461. return;
  115462. }
  115463. var original = current.value;
  115464. current.value = current.value.replace(multiple ? /^\s+/ : /^[ \t]*\r?\n?/, '');
  115465. current.rightStripped = current.value !== original;
  115466. }
  115467. // Marks the node to the left of the position as omitted.
  115468. // I.e. ' '{{foo}} will mark the ' ' node as omitted.
  115469. //
  115470. // If i is undefined then the last child will be marked as such.
  115471. //
  115472. // If mulitple is truthy then all whitespace will be stripped out until non-whitespace
  115473. // content is met.
  115474. function omitLeft(body, i, multiple) {
  115475. var current = body[i == null ? body.length - 1 : i - 1];
  115476. if (!current || current.type !== 'ContentStatement' || !multiple && current.leftStripped) {
  115477. return;
  115478. }
  115479. // We omit the last node if it's whitespace only and not preceeded by a non-content node.
  115480. var original = current.value;
  115481. current.value = current.value.replace(multiple ? /\s+$/ : /[ \t]+$/, '');
  115482. current.leftStripped = current.value !== original;
  115483. return current.leftStripped;
  115484. }
  115485. exports['default'] = WhitespaceControl;
  115486. module.exports = exports['default'];
  115487. /***/ }),
  115488. /* 39 */
  115489. /***/ (function(module, exports, __webpack_require__) {
  115490. 'use strict';
  115491. var _interopRequireDefault = __webpack_require__(1)['default'];
  115492. exports.__esModule = true;
  115493. var _exception = __webpack_require__(6);
  115494. var _exception2 = _interopRequireDefault(_exception);
  115495. function Visitor() {
  115496. this.parents = [];
  115497. }
  115498. Visitor.prototype = {
  115499. constructor: Visitor,
  115500. mutating: false,
  115501. // Visits a given value. If mutating, will replace the value if necessary.
  115502. acceptKey: function acceptKey(node, name) {
  115503. var value = this.accept(node[name]);
  115504. if (this.mutating) {
  115505. // Hacky sanity check: This may have a few false positives for type for the helper
  115506. // methods but will generally do the right thing without a lot of overhead.
  115507. if (value && !Visitor.prototype[value.type]) {
  115508. throw new _exception2['default']('Unexpected node type "' + value.type + '" found when accepting ' + name + ' on ' + node.type);
  115509. }
  115510. node[name] = value;
  115511. }
  115512. },
  115513. // Performs an accept operation with added sanity check to ensure
  115514. // required keys are not removed.
  115515. acceptRequired: function acceptRequired(node, name) {
  115516. this.acceptKey(node, name);
  115517. if (!node[name]) {
  115518. throw new _exception2['default'](node.type + ' requires ' + name);
  115519. }
  115520. },
  115521. // Traverses a given array. If mutating, empty respnses will be removed
  115522. // for child elements.
  115523. acceptArray: function acceptArray(array) {
  115524. for (var i = 0, l = array.length; i < l; i++) {
  115525. this.acceptKey(array, i);
  115526. if (!array[i]) {
  115527. array.splice(i, 1);
  115528. i--;
  115529. l--;
  115530. }
  115531. }
  115532. },
  115533. accept: function accept(object) {
  115534. if (!object) {
  115535. return;
  115536. }
  115537. /* istanbul ignore next: Sanity code */
  115538. if (!this[object.type]) {
  115539. throw new _exception2['default']('Unknown type: ' + object.type, object);
  115540. }
  115541. if (this.current) {
  115542. this.parents.unshift(this.current);
  115543. }
  115544. this.current = object;
  115545. var ret = this[object.type](object);
  115546. this.current = this.parents.shift();
  115547. if (!this.mutating || ret) {
  115548. return ret;
  115549. } else if (ret !== false) {
  115550. return object;
  115551. }
  115552. },
  115553. Program: function Program(program) {
  115554. this.acceptArray(program.body);
  115555. },
  115556. MustacheStatement: visitSubExpression,
  115557. Decorator: visitSubExpression,
  115558. BlockStatement: visitBlock,
  115559. DecoratorBlock: visitBlock,
  115560. PartialStatement: visitPartial,
  115561. PartialBlockStatement: function PartialBlockStatement(partial) {
  115562. visitPartial.call(this, partial);
  115563. this.acceptKey(partial, 'program');
  115564. },
  115565. ContentStatement: function ContentStatement() /* content */{},
  115566. CommentStatement: function CommentStatement() /* comment */{},
  115567. SubExpression: visitSubExpression,
  115568. PathExpression: function PathExpression() /* path */{},
  115569. StringLiteral: function StringLiteral() /* string */{},
  115570. NumberLiteral: function NumberLiteral() /* number */{},
  115571. BooleanLiteral: function BooleanLiteral() /* bool */{},
  115572. UndefinedLiteral: function UndefinedLiteral() /* literal */{},
  115573. NullLiteral: function NullLiteral() /* literal */{},
  115574. Hash: function Hash(hash) {
  115575. this.acceptArray(hash.pairs);
  115576. },
  115577. HashPair: function HashPair(pair) {
  115578. this.acceptRequired(pair, 'value');
  115579. }
  115580. };
  115581. function visitSubExpression(mustache) {
  115582. this.acceptRequired(mustache, 'path');
  115583. this.acceptArray(mustache.params);
  115584. this.acceptKey(mustache, 'hash');
  115585. }
  115586. function visitBlock(block) {
  115587. visitSubExpression.call(this, block);
  115588. this.acceptKey(block, 'program');
  115589. this.acceptKey(block, 'inverse');
  115590. }
  115591. function visitPartial(partial) {
  115592. this.acceptRequired(partial, 'name');
  115593. this.acceptArray(partial.params);
  115594. this.acceptKey(partial, 'hash');
  115595. }
  115596. exports['default'] = Visitor;
  115597. module.exports = exports['default'];
  115598. /***/ }),
  115599. /* 40 */
  115600. /***/ (function(module, exports, __webpack_require__) {
  115601. 'use strict';
  115602. var _interopRequireDefault = __webpack_require__(1)['default'];
  115603. exports.__esModule = true;
  115604. exports.SourceLocation = SourceLocation;
  115605. exports.id = id;
  115606. exports.stripFlags = stripFlags;
  115607. exports.stripComment = stripComment;
  115608. exports.preparePath = preparePath;
  115609. exports.prepareMustache = prepareMustache;
  115610. exports.prepareRawBlock = prepareRawBlock;
  115611. exports.prepareBlock = prepareBlock;
  115612. exports.prepareProgram = prepareProgram;
  115613. exports.preparePartialBlock = preparePartialBlock;
  115614. var _exception = __webpack_require__(6);
  115615. var _exception2 = _interopRequireDefault(_exception);
  115616. function validateClose(open, close) {
  115617. close = close.path ? close.path.original : close;
  115618. if (open.path.original !== close) {
  115619. var errorNode = { loc: open.path.loc };
  115620. throw new _exception2['default'](open.path.original + " doesn't match " + close, errorNode);
  115621. }
  115622. }
  115623. function SourceLocation(source, locInfo) {
  115624. this.source = source;
  115625. this.start = {
  115626. line: locInfo.first_line,
  115627. column: locInfo.first_column
  115628. };
  115629. this.end = {
  115630. line: locInfo.last_line,
  115631. column: locInfo.last_column
  115632. };
  115633. }
  115634. function id(token) {
  115635. if (/^\[.*\]$/.test(token)) {
  115636. return token.substr(1, token.length - 2);
  115637. } else {
  115638. return token;
  115639. }
  115640. }
  115641. function stripFlags(open, close) {
  115642. return {
  115643. open: open.charAt(2) === '~',
  115644. close: close.charAt(close.length - 3) === '~'
  115645. };
  115646. }
  115647. function stripComment(comment) {
  115648. return comment.replace(/^\{\{~?\!-?-?/, '').replace(/-?-?~?\}\}$/, '');
  115649. }
  115650. function preparePath(data, parts, loc) {
  115651. loc = this.locInfo(loc);
  115652. var original = data ? '@' : '',
  115653. dig = [],
  115654. depth = 0,
  115655. depthString = '';
  115656. for (var i = 0, l = parts.length; i < l; i++) {
  115657. var part = parts[i].part,
  115658. // If we have [] syntax then we do not treat path references as operators,
  115659. // i.e. foo.[this] resolves to approximately context.foo['this']
  115660. isLiteral = parts[i].original !== part;
  115661. original += (parts[i].separator || '') + part;
  115662. if (!isLiteral && (part === '..' || part === '.' || part === 'this')) {
  115663. if (dig.length > 0) {
  115664. throw new _exception2['default']('Invalid path: ' + original, { loc: loc });
  115665. } else if (part === '..') {
  115666. depth++;
  115667. depthString += '../';
  115668. }
  115669. } else {
  115670. dig.push(part);
  115671. }
  115672. }
  115673. return {
  115674. type: 'PathExpression',
  115675. data: data,
  115676. depth: depth,
  115677. parts: dig,
  115678. original: original,
  115679. loc: loc
  115680. };
  115681. }
  115682. function prepareMustache(path, params, hash, open, strip, locInfo) {
  115683. // Must use charAt to support IE pre-10
  115684. var escapeFlag = open.charAt(3) || open.charAt(2),
  115685. escaped = escapeFlag !== '{' && escapeFlag !== '&';
  115686. var decorator = /\*/.test(open);
  115687. return {
  115688. type: decorator ? 'Decorator' : 'MustacheStatement',
  115689. path: path,
  115690. params: params,
  115691. hash: hash,
  115692. escaped: escaped,
  115693. strip: strip,
  115694. loc: this.locInfo(locInfo)
  115695. };
  115696. }
  115697. function prepareRawBlock(openRawBlock, contents, close, locInfo) {
  115698. validateClose(openRawBlock, close);
  115699. locInfo = this.locInfo(locInfo);
  115700. var program = {
  115701. type: 'Program',
  115702. body: contents,
  115703. strip: {},
  115704. loc: locInfo
  115705. };
  115706. return {
  115707. type: 'BlockStatement',
  115708. path: openRawBlock.path,
  115709. params: openRawBlock.params,
  115710. hash: openRawBlock.hash,
  115711. program: program,
  115712. openStrip: {},
  115713. inverseStrip: {},
  115714. closeStrip: {},
  115715. loc: locInfo
  115716. };
  115717. }
  115718. function prepareBlock(openBlock, program, inverseAndProgram, close, inverted, locInfo) {
  115719. if (close && close.path) {
  115720. validateClose(openBlock, close);
  115721. }
  115722. var decorator = /\*/.test(openBlock.open);
  115723. program.blockParams = openBlock.blockParams;
  115724. var inverse = undefined,
  115725. inverseStrip = undefined;
  115726. if (inverseAndProgram) {
  115727. if (decorator) {
  115728. throw new _exception2['default']('Unexpected inverse block on decorator', inverseAndProgram);
  115729. }
  115730. if (inverseAndProgram.chain) {
  115731. inverseAndProgram.program.body[0].closeStrip = close.strip;
  115732. }
  115733. inverseStrip = inverseAndProgram.strip;
  115734. inverse = inverseAndProgram.program;
  115735. }
  115736. if (inverted) {
  115737. inverted = inverse;
  115738. inverse = program;
  115739. program = inverted;
  115740. }
  115741. return {
  115742. type: decorator ? 'DecoratorBlock' : 'BlockStatement',
  115743. path: openBlock.path,
  115744. params: openBlock.params,
  115745. hash: openBlock.hash,
  115746. program: program,
  115747. inverse: inverse,
  115748. openStrip: openBlock.strip,
  115749. inverseStrip: inverseStrip,
  115750. closeStrip: close && close.strip,
  115751. loc: this.locInfo(locInfo)
  115752. };
  115753. }
  115754. function prepareProgram(statements, loc) {
  115755. if (!loc && statements.length) {
  115756. var firstLoc = statements[0].loc,
  115757. lastLoc = statements[statements.length - 1].loc;
  115758. /* istanbul ignore else */
  115759. if (firstLoc && lastLoc) {
  115760. loc = {
  115761. source: firstLoc.source,
  115762. start: {
  115763. line: firstLoc.start.line,
  115764. column: firstLoc.start.column
  115765. },
  115766. end: {
  115767. line: lastLoc.end.line,
  115768. column: lastLoc.end.column
  115769. }
  115770. };
  115771. }
  115772. }
  115773. return {
  115774. type: 'Program',
  115775. body: statements,
  115776. strip: {},
  115777. loc: loc
  115778. };
  115779. }
  115780. function preparePartialBlock(open, program, close, locInfo) {
  115781. validateClose(open, close);
  115782. return {
  115783. type: 'PartialBlockStatement',
  115784. name: open.path,
  115785. params: open.params,
  115786. hash: open.hash,
  115787. program: program,
  115788. openStrip: open.strip,
  115789. closeStrip: close && close.strip,
  115790. loc: this.locInfo(locInfo)
  115791. };
  115792. }
  115793. /***/ }),
  115794. /* 41 */
  115795. /***/ (function(module, exports, __webpack_require__) {
  115796. /* eslint-disable new-cap */
  115797. 'use strict';
  115798. var _interopRequireDefault = __webpack_require__(1)['default'];
  115799. exports.__esModule = true;
  115800. exports.Compiler = Compiler;
  115801. exports.precompile = precompile;
  115802. exports.compile = compile;
  115803. var _exception = __webpack_require__(6);
  115804. var _exception2 = _interopRequireDefault(_exception);
  115805. var _utils = __webpack_require__(5);
  115806. var _ast = __webpack_require__(35);
  115807. var _ast2 = _interopRequireDefault(_ast);
  115808. var slice = [].slice;
  115809. function Compiler() {}
  115810. // the foundHelper register will disambiguate helper lookup from finding a
  115811. // function in a context. This is necessary for mustache compatibility, which
  115812. // requires that context functions in blocks are evaluated by blockHelperMissing,
  115813. // and then proceed as if the resulting value was provided to blockHelperMissing.
  115814. Compiler.prototype = {
  115815. compiler: Compiler,
  115816. equals: function equals(other) {
  115817. var len = this.opcodes.length;
  115818. if (other.opcodes.length !== len) {
  115819. return false;
  115820. }
  115821. for (var i = 0; i < len; i++) {
  115822. var opcode = this.opcodes[i],
  115823. otherOpcode = other.opcodes[i];
  115824. if (opcode.opcode !== otherOpcode.opcode || !argEquals(opcode.args, otherOpcode.args)) {
  115825. return false;
  115826. }
  115827. }
  115828. // We know that length is the same between the two arrays because they are directly tied
  115829. // to the opcode behavior above.
  115830. len = this.children.length;
  115831. for (var i = 0; i < len; i++) {
  115832. if (!this.children[i].equals(other.children[i])) {
  115833. return false;
  115834. }
  115835. }
  115836. return true;
  115837. },
  115838. guid: 0,
  115839. compile: function compile(program, options) {
  115840. this.sourceNode = [];
  115841. this.opcodes = [];
  115842. this.children = [];
  115843. this.options = options;
  115844. this.stringParams = options.stringParams;
  115845. this.trackIds = options.trackIds;
  115846. options.blockParams = options.blockParams || [];
  115847. // These changes will propagate to the other compiler components
  115848. var knownHelpers = options.knownHelpers;
  115849. options.knownHelpers = {
  115850. 'helperMissing': true,
  115851. 'blockHelperMissing': true,
  115852. 'each': true,
  115853. 'if': true,
  115854. 'unless': true,
  115855. 'with': true,
  115856. 'log': true,
  115857. 'lookup': true
  115858. };
  115859. if (knownHelpers) {
  115860. for (var _name in knownHelpers) {
  115861. /* istanbul ignore else */
  115862. if (_name in knownHelpers) {
  115863. this.options.knownHelpers[_name] = knownHelpers[_name];
  115864. }
  115865. }
  115866. }
  115867. return this.accept(program);
  115868. },
  115869. compileProgram: function compileProgram(program) {
  115870. var childCompiler = new this.compiler(),
  115871. // eslint-disable-line new-cap
  115872. result = childCompiler.compile(program, this.options),
  115873. guid = this.guid++;
  115874. this.usePartial = this.usePartial || result.usePartial;
  115875. this.children[guid] = result;
  115876. this.useDepths = this.useDepths || result.useDepths;
  115877. return guid;
  115878. },
  115879. accept: function accept(node) {
  115880. /* istanbul ignore next: Sanity code */
  115881. if (!this[node.type]) {
  115882. throw new _exception2['default']('Unknown type: ' + node.type, node);
  115883. }
  115884. this.sourceNode.unshift(node);
  115885. var ret = this[node.type](node);
  115886. this.sourceNode.shift();
  115887. return ret;
  115888. },
  115889. Program: function Program(program) {
  115890. this.options.blockParams.unshift(program.blockParams);
  115891. var body = program.body,
  115892. bodyLength = body.length;
  115893. for (var i = 0; i < bodyLength; i++) {
  115894. this.accept(body[i]);
  115895. }
  115896. this.options.blockParams.shift();
  115897. this.isSimple = bodyLength === 1;
  115898. this.blockParams = program.blockParams ? program.blockParams.length : 0;
  115899. return this;
  115900. },
  115901. BlockStatement: function BlockStatement(block) {
  115902. transformLiteralToPath(block);
  115903. var program = block.program,
  115904. inverse = block.inverse;
  115905. program = program && this.compileProgram(program);
  115906. inverse = inverse && this.compileProgram(inverse);
  115907. var type = this.classifySexpr(block);
  115908. if (type === 'helper') {
  115909. this.helperSexpr(block, program, inverse);
  115910. } else if (type === 'simple') {
  115911. this.simpleSexpr(block);
  115912. // now that the simple mustache is resolved, we need to
  115913. // evaluate it by executing `blockHelperMissing`
  115914. this.opcode('pushProgram', program);
  115915. this.opcode('pushProgram', inverse);
  115916. this.opcode('emptyHash');
  115917. this.opcode('blockValue', block.path.original);
  115918. } else {
  115919. this.ambiguousSexpr(block, program, inverse);
  115920. // now that the simple mustache is resolved, we need to
  115921. // evaluate it by executing `blockHelperMissing`
  115922. this.opcode('pushProgram', program);
  115923. this.opcode('pushProgram', inverse);
  115924. this.opcode('emptyHash');
  115925. this.opcode('ambiguousBlockValue');
  115926. }
  115927. this.opcode('append');
  115928. },
  115929. DecoratorBlock: function DecoratorBlock(decorator) {
  115930. var program = decorator.program && this.compileProgram(decorator.program);
  115931. var params = this.setupFullMustacheParams(decorator, program, undefined),
  115932. path = decorator.path;
  115933. this.useDecorators = true;
  115934. this.opcode('registerDecorator', params.length, path.original);
  115935. },
  115936. PartialStatement: function PartialStatement(partial) {
  115937. this.usePartial = true;
  115938. var program = partial.program;
  115939. if (program) {
  115940. program = this.compileProgram(partial.program);
  115941. }
  115942. var params = partial.params;
  115943. if (params.length > 1) {
  115944. throw new _exception2['default']('Unsupported number of partial arguments: ' + params.length, partial);
  115945. } else if (!params.length) {
  115946. if (this.options.explicitPartialContext) {
  115947. this.opcode('pushLiteral', 'undefined');
  115948. } else {
  115949. params.push({ type: 'PathExpression', parts: [], depth: 0 });
  115950. }
  115951. }
  115952. var partialName = partial.name.original,
  115953. isDynamic = partial.name.type === 'SubExpression';
  115954. if (isDynamic) {
  115955. this.accept(partial.name);
  115956. }
  115957. this.setupFullMustacheParams(partial, program, undefined, true);
  115958. var indent = partial.indent || '';
  115959. if (this.options.preventIndent && indent) {
  115960. this.opcode('appendContent', indent);
  115961. indent = '';
  115962. }
  115963. this.opcode('invokePartial', isDynamic, partialName, indent);
  115964. this.opcode('append');
  115965. },
  115966. PartialBlockStatement: function PartialBlockStatement(partialBlock) {
  115967. this.PartialStatement(partialBlock);
  115968. },
  115969. MustacheStatement: function MustacheStatement(mustache) {
  115970. this.SubExpression(mustache);
  115971. if (mustache.escaped && !this.options.noEscape) {
  115972. this.opcode('appendEscaped');
  115973. } else {
  115974. this.opcode('append');
  115975. }
  115976. },
  115977. Decorator: function Decorator(decorator) {
  115978. this.DecoratorBlock(decorator);
  115979. },
  115980. ContentStatement: function ContentStatement(content) {
  115981. if (content.value) {
  115982. this.opcode('appendContent', content.value);
  115983. }
  115984. },
  115985. CommentStatement: function CommentStatement() {},
  115986. SubExpression: function SubExpression(sexpr) {
  115987. transformLiteralToPath(sexpr);
  115988. var type = this.classifySexpr(sexpr);
  115989. if (type === 'simple') {
  115990. this.simpleSexpr(sexpr);
  115991. } else if (type === 'helper') {
  115992. this.helperSexpr(sexpr);
  115993. } else {
  115994. this.ambiguousSexpr(sexpr);
  115995. }
  115996. },
  115997. ambiguousSexpr: function ambiguousSexpr(sexpr, program, inverse) {
  115998. var path = sexpr.path,
  115999. name = path.parts[0],
  116000. isBlock = program != null || inverse != null;
  116001. this.opcode('getContext', path.depth);
  116002. this.opcode('pushProgram', program);
  116003. this.opcode('pushProgram', inverse);
  116004. path.strict = true;
  116005. this.accept(path);
  116006. this.opcode('invokeAmbiguous', name, isBlock);
  116007. },
  116008. simpleSexpr: function simpleSexpr(sexpr) {
  116009. var path = sexpr.path;
  116010. path.strict = true;
  116011. this.accept(path);
  116012. this.opcode('resolvePossibleLambda');
  116013. },
  116014. helperSexpr: function helperSexpr(sexpr, program, inverse) {
  116015. var params = this.setupFullMustacheParams(sexpr, program, inverse),
  116016. path = sexpr.path,
  116017. name = path.parts[0];
  116018. if (this.options.knownHelpers[name]) {
  116019. this.opcode('invokeKnownHelper', params.length, name);
  116020. } else if (this.options.knownHelpersOnly) {
  116021. throw new _exception2['default']('You specified knownHelpersOnly, but used the unknown helper ' + name, sexpr);
  116022. } else {
  116023. path.strict = true;
  116024. path.falsy = true;
  116025. this.accept(path);
  116026. this.opcode('invokeHelper', params.length, path.original, _ast2['default'].helpers.simpleId(path));
  116027. }
  116028. },
  116029. PathExpression: function PathExpression(path) {
  116030. this.addDepth(path.depth);
  116031. this.opcode('getContext', path.depth);
  116032. var name = path.parts[0],
  116033. scoped = _ast2['default'].helpers.scopedId(path),
  116034. blockParamId = !path.depth && !scoped && this.blockParamIndex(name);
  116035. if (blockParamId) {
  116036. this.opcode('lookupBlockParam', blockParamId, path.parts);
  116037. } else if (!name) {
  116038. // Context reference, i.e. `{{foo .}}` or `{{foo ..}}`
  116039. this.opcode('pushContext');
  116040. } else if (path.data) {
  116041. this.options.data = true;
  116042. this.opcode('lookupData', path.depth, path.parts, path.strict);
  116043. } else {
  116044. this.opcode('lookupOnContext', path.parts, path.falsy, path.strict, scoped);
  116045. }
  116046. },
  116047. StringLiteral: function StringLiteral(string) {
  116048. this.opcode('pushString', string.value);
  116049. },
  116050. NumberLiteral: function NumberLiteral(number) {
  116051. this.opcode('pushLiteral', number.value);
  116052. },
  116053. BooleanLiteral: function BooleanLiteral(bool) {
  116054. this.opcode('pushLiteral', bool.value);
  116055. },
  116056. UndefinedLiteral: function UndefinedLiteral() {
  116057. this.opcode('pushLiteral', 'undefined');
  116058. },
  116059. NullLiteral: function NullLiteral() {
  116060. this.opcode('pushLiteral', 'null');
  116061. },
  116062. Hash: function Hash(hash) {
  116063. var pairs = hash.pairs,
  116064. i = 0,
  116065. l = pairs.length;
  116066. this.opcode('pushHash');
  116067. for (; i < l; i++) {
  116068. this.pushParam(pairs[i].value);
  116069. }
  116070. while (i--) {
  116071. this.opcode('assignToHash', pairs[i].key);
  116072. }
  116073. this.opcode('popHash');
  116074. },
  116075. // HELPERS
  116076. opcode: function opcode(name) {
  116077. this.opcodes.push({ opcode: name, args: slice.call(arguments, 1), loc: this.sourceNode[0].loc });
  116078. },
  116079. addDepth: function addDepth(depth) {
  116080. if (!depth) {
  116081. return;
  116082. }
  116083. this.useDepths = true;
  116084. },
  116085. classifySexpr: function classifySexpr(sexpr) {
  116086. var isSimple = _ast2['default'].helpers.simpleId(sexpr.path);
  116087. var isBlockParam = isSimple && !!this.blockParamIndex(sexpr.path.parts[0]);
  116088. // a mustache is an eligible helper if:
  116089. // * its id is simple (a single part, not `this` or `..`)
  116090. var isHelper = !isBlockParam && _ast2['default'].helpers.helperExpression(sexpr);
  116091. // if a mustache is an eligible helper but not a definite
  116092. // helper, it is ambiguous, and will be resolved in a later
  116093. // pass or at runtime.
  116094. var isEligible = !isBlockParam && (isHelper || isSimple);
  116095. // if ambiguous, we can possibly resolve the ambiguity now
  116096. // An eligible helper is one that does not have a complex path, i.e. `this.foo`, `../foo` etc.
  116097. if (isEligible && !isHelper) {
  116098. var _name2 = sexpr.path.parts[0],
  116099. options = this.options;
  116100. if (options.knownHelpers[_name2]) {
  116101. isHelper = true;
  116102. } else if (options.knownHelpersOnly) {
  116103. isEligible = false;
  116104. }
  116105. }
  116106. if (isHelper) {
  116107. return 'helper';
  116108. } else if (isEligible) {
  116109. return 'ambiguous';
  116110. } else {
  116111. return 'simple';
  116112. }
  116113. },
  116114. pushParams: function pushParams(params) {
  116115. for (var i = 0, l = params.length; i < l; i++) {
  116116. this.pushParam(params[i]);
  116117. }
  116118. },
  116119. pushParam: function pushParam(val) {
  116120. var value = val.value != null ? val.value : val.original || '';
  116121. if (this.stringParams) {
  116122. if (value.replace) {
  116123. value = value.replace(/^(\.?\.\/)*/g, '').replace(/\//g, '.');
  116124. }
  116125. if (val.depth) {
  116126. this.addDepth(val.depth);
  116127. }
  116128. this.opcode('getContext', val.depth || 0);
  116129. this.opcode('pushStringParam', value, val.type);
  116130. if (val.type === 'SubExpression') {
  116131. // SubExpressions get evaluated and passed in
  116132. // in string params mode.
  116133. this.accept(val);
  116134. }
  116135. } else {
  116136. if (this.trackIds) {
  116137. var blockParamIndex = undefined;
  116138. if (val.parts && !_ast2['default'].helpers.scopedId(val) && !val.depth) {
  116139. blockParamIndex = this.blockParamIndex(val.parts[0]);
  116140. }
  116141. if (blockParamIndex) {
  116142. var blockParamChild = val.parts.slice(1).join('.');
  116143. this.opcode('pushId', 'BlockParam', blockParamIndex, blockParamChild);
  116144. } else {
  116145. value = val.original || value;
  116146. if (value.replace) {
  116147. value = value.replace(/^this(?:\.|$)/, '').replace(/^\.\//, '').replace(/^\.$/, '');
  116148. }
  116149. this.opcode('pushId', val.type, value);
  116150. }
  116151. }
  116152. this.accept(val);
  116153. }
  116154. },
  116155. setupFullMustacheParams: function setupFullMustacheParams(sexpr, program, inverse, omitEmpty) {
  116156. var params = sexpr.params;
  116157. this.pushParams(params);
  116158. this.opcode('pushProgram', program);
  116159. this.opcode('pushProgram', inverse);
  116160. if (sexpr.hash) {
  116161. this.accept(sexpr.hash);
  116162. } else {
  116163. this.opcode('emptyHash', omitEmpty);
  116164. }
  116165. return params;
  116166. },
  116167. blockParamIndex: function blockParamIndex(name) {
  116168. for (var depth = 0, len = this.options.blockParams.length; depth < len; depth++) {
  116169. var blockParams = this.options.blockParams[depth],
  116170. param = blockParams && _utils.indexOf(blockParams, name);
  116171. if (blockParams && param >= 0) {
  116172. return [depth, param];
  116173. }
  116174. }
  116175. }
  116176. };
  116177. function precompile(input, options, env) {
  116178. if (input == null || typeof input !== 'string' && input.type !== 'Program') {
  116179. throw new _exception2['default']('You must pass a string or Handlebars AST to Handlebars.precompile. You passed ' + input);
  116180. }
  116181. options = options || {};
  116182. if (!('data' in options)) {
  116183. options.data = true;
  116184. }
  116185. if (options.compat) {
  116186. options.useDepths = true;
  116187. }
  116188. var ast = env.parse(input, options),
  116189. environment = new env.Compiler().compile(ast, options);
  116190. return new env.JavaScriptCompiler().compile(environment, options);
  116191. }
  116192. function compile(input, options, env) {
  116193. if (options === undefined) options = {};
  116194. if (input == null || typeof input !== 'string' && input.type !== 'Program') {
  116195. throw new _exception2['default']('You must pass a string or Handlebars AST to Handlebars.compile. You passed ' + input);
  116196. }
  116197. options = _utils.extend({}, options);
  116198. if (!('data' in options)) {
  116199. options.data = true;
  116200. }
  116201. if (options.compat) {
  116202. options.useDepths = true;
  116203. }
  116204. var compiled = undefined;
  116205. function compileInput() {
  116206. var ast = env.parse(input, options),
  116207. environment = new env.Compiler().compile(ast, options),
  116208. templateSpec = new env.JavaScriptCompiler().compile(environment, options, undefined, true);
  116209. return env.template(templateSpec);
  116210. }
  116211. // Template is only compiled on first use and cached after that point.
  116212. function ret(context, execOptions) {
  116213. if (!compiled) {
  116214. compiled = compileInput();
  116215. }
  116216. return compiled.call(this, context, execOptions);
  116217. }
  116218. ret._setup = function (setupOptions) {
  116219. if (!compiled) {
  116220. compiled = compileInput();
  116221. }
  116222. return compiled._setup(setupOptions);
  116223. };
  116224. ret._child = function (i, data, blockParams, depths) {
  116225. if (!compiled) {
  116226. compiled = compileInput();
  116227. }
  116228. return compiled._child(i, data, blockParams, depths);
  116229. };
  116230. return ret;
  116231. }
  116232. function argEquals(a, b) {
  116233. if (a === b) {
  116234. return true;
  116235. }
  116236. if (_utils.isArray(a) && _utils.isArray(b) && a.length === b.length) {
  116237. for (var i = 0; i < a.length; i++) {
  116238. if (!argEquals(a[i], b[i])) {
  116239. return false;
  116240. }
  116241. }
  116242. return true;
  116243. }
  116244. }
  116245. function transformLiteralToPath(sexpr) {
  116246. if (!sexpr.path.parts) {
  116247. var literal = sexpr.path;
  116248. // Casting to string here to make false and 0 literal values play nicely with the rest
  116249. // of the system.
  116250. sexpr.path = {
  116251. type: 'PathExpression',
  116252. data: false,
  116253. depth: 0,
  116254. parts: [literal.original + ''],
  116255. original: literal.original + '',
  116256. loc: literal.loc
  116257. };
  116258. }
  116259. }
  116260. /***/ }),
  116261. /* 42 */
  116262. /***/ (function(module, exports, __webpack_require__) {
  116263. 'use strict';
  116264. var _interopRequireDefault = __webpack_require__(1)['default'];
  116265. exports.__esModule = true;
  116266. var _base = __webpack_require__(4);
  116267. var _exception = __webpack_require__(6);
  116268. var _exception2 = _interopRequireDefault(_exception);
  116269. var _utils = __webpack_require__(5);
  116270. var _codeGen = __webpack_require__(43);
  116271. var _codeGen2 = _interopRequireDefault(_codeGen);
  116272. function Literal(value) {
  116273. this.value = value;
  116274. }
  116275. function JavaScriptCompiler() {}
  116276. JavaScriptCompiler.prototype = {
  116277. // PUBLIC API: You can override these methods in a subclass to provide
  116278. // alternative compiled forms for name lookup and buffering semantics
  116279. nameLookup: function nameLookup(parent, name /* , type*/) {
  116280. if (JavaScriptCompiler.isValidJavaScriptVariableName(name)) {
  116281. return [parent, '.', name];
  116282. } else {
  116283. return [parent, '[', JSON.stringify(name), ']'];
  116284. }
  116285. },
  116286. depthedLookup: function depthedLookup(name) {
  116287. return [this.aliasable('container.lookup'), '(depths, "', name, '")'];
  116288. },
  116289. compilerInfo: function compilerInfo() {
  116290. var revision = _base.COMPILER_REVISION,
  116291. versions = _base.REVISION_CHANGES[revision];
  116292. return [revision, versions];
  116293. },
  116294. appendToBuffer: function appendToBuffer(source, location, explicit) {
  116295. // Force a source as this simplifies the merge logic.
  116296. if (!_utils.isArray(source)) {
  116297. source = [source];
  116298. }
  116299. source = this.source.wrap(source, location);
  116300. if (this.environment.isSimple) {
  116301. return ['return ', source, ';'];
  116302. } else if (explicit) {
  116303. // This is a case where the buffer operation occurs as a child of another
  116304. // construct, generally braces. We have to explicitly output these buffer
  116305. // operations to ensure that the emitted code goes in the correct location.
  116306. return ['buffer += ', source, ';'];
  116307. } else {
  116308. source.appendToBuffer = true;
  116309. return source;
  116310. }
  116311. },
  116312. initializeBuffer: function initializeBuffer() {
  116313. return this.quotedString('');
  116314. },
  116315. // END PUBLIC API
  116316. compile: function compile(environment, options, context, asObject) {
  116317. this.environment = environment;
  116318. this.options = options;
  116319. this.stringParams = this.options.stringParams;
  116320. this.trackIds = this.options.trackIds;
  116321. this.precompile = !asObject;
  116322. this.name = this.environment.name;
  116323. this.isChild = !!context;
  116324. this.context = context || {
  116325. decorators: [],
  116326. programs: [],
  116327. environments: []
  116328. };
  116329. this.preamble();
  116330. this.stackSlot = 0;
  116331. this.stackVars = [];
  116332. this.aliases = {};
  116333. this.registers = { list: [] };
  116334. this.hashes = [];
  116335. this.compileStack = [];
  116336. this.inlineStack = [];
  116337. this.blockParams = [];
  116338. this.compileChildren(environment, options);
  116339. this.useDepths = this.useDepths || environment.useDepths || environment.useDecorators || this.options.compat;
  116340. this.useBlockParams = this.useBlockParams || environment.useBlockParams;
  116341. var opcodes = environment.opcodes,
  116342. opcode = undefined,
  116343. firstLoc = undefined,
  116344. i = undefined,
  116345. l = undefined;
  116346. for (i = 0, l = opcodes.length; i < l; i++) {
  116347. opcode = opcodes[i];
  116348. this.source.currentLocation = opcode.loc;
  116349. firstLoc = firstLoc || opcode.loc;
  116350. this[opcode.opcode].apply(this, opcode.args);
  116351. }
  116352. // Flush any trailing content that might be pending.
  116353. this.source.currentLocation = firstLoc;
  116354. this.pushSource('');
  116355. /* istanbul ignore next */
  116356. if (this.stackSlot || this.inlineStack.length || this.compileStack.length) {
  116357. throw new _exception2['default']('Compile completed with content left on stack');
  116358. }
  116359. if (!this.decorators.isEmpty()) {
  116360. this.useDecorators = true;
  116361. this.decorators.prepend('var decorators = container.decorators;\n');
  116362. this.decorators.push('return fn;');
  116363. if (asObject) {
  116364. this.decorators = Function.apply(this, ['fn', 'props', 'container', 'depth0', 'data', 'blockParams', 'depths', this.decorators.merge()]);
  116365. } else {
  116366. this.decorators.prepend('function(fn, props, container, depth0, data, blockParams, depths) {\n');
  116367. this.decorators.push('}\n');
  116368. this.decorators = this.decorators.merge();
  116369. }
  116370. } else {
  116371. this.decorators = undefined;
  116372. }
  116373. var fn = this.createFunctionContext(asObject);
  116374. if (!this.isChild) {
  116375. var ret = {
  116376. compiler: this.compilerInfo(),
  116377. main: fn
  116378. };
  116379. if (this.decorators) {
  116380. ret.main_d = this.decorators; // eslint-disable-line camelcase
  116381. ret.useDecorators = true;
  116382. }
  116383. var _context = this.context;
  116384. var programs = _context.programs;
  116385. var decorators = _context.decorators;
  116386. for (i = 0, l = programs.length; i < l; i++) {
  116387. if (programs[i]) {
  116388. ret[i] = programs[i];
  116389. if (decorators[i]) {
  116390. ret[i + '_d'] = decorators[i];
  116391. ret.useDecorators = true;
  116392. }
  116393. }
  116394. }
  116395. if (this.environment.usePartial) {
  116396. ret.usePartial = true;
  116397. }
  116398. if (this.options.data) {
  116399. ret.useData = true;
  116400. }
  116401. if (this.useDepths) {
  116402. ret.useDepths = true;
  116403. }
  116404. if (this.useBlockParams) {
  116405. ret.useBlockParams = true;
  116406. }
  116407. if (this.options.compat) {
  116408. ret.compat = true;
  116409. }
  116410. if (!asObject) {
  116411. ret.compiler = JSON.stringify(ret.compiler);
  116412. this.source.currentLocation = { start: { line: 1, column: 0 } };
  116413. ret = this.objectLiteral(ret);
  116414. if (options.srcName) {
  116415. ret = ret.toStringWithSourceMap({ file: options.destName });
  116416. ret.map = ret.map && ret.map.toString();
  116417. } else {
  116418. ret = ret.toString();
  116419. }
  116420. } else {
  116421. ret.compilerOptions = this.options;
  116422. }
  116423. return ret;
  116424. } else {
  116425. return fn;
  116426. }
  116427. },
  116428. preamble: function preamble() {
  116429. // track the last context pushed into place to allow skipping the
  116430. // getContext opcode when it would be a noop
  116431. this.lastContext = 0;
  116432. this.source = new _codeGen2['default'](this.options.srcName);
  116433. this.decorators = new _codeGen2['default'](this.options.srcName);
  116434. },
  116435. createFunctionContext: function createFunctionContext(asObject) {
  116436. var varDeclarations = '';
  116437. var locals = this.stackVars.concat(this.registers.list);
  116438. if (locals.length > 0) {
  116439. varDeclarations += ', ' + locals.join(', ');
  116440. }
  116441. // Generate minimizer alias mappings
  116442. //
  116443. // When using true SourceNodes, this will update all references to the given alias
  116444. // as the source nodes are reused in situ. For the non-source node compilation mode,
  116445. // aliases will not be used, but this case is already being run on the client and
  116446. // we aren't concern about minimizing the template size.
  116447. var aliasCount = 0;
  116448. for (var alias in this.aliases) {
  116449. // eslint-disable-line guard-for-in
  116450. var node = this.aliases[alias];
  116451. if (this.aliases.hasOwnProperty(alias) && node.children && node.referenceCount > 1) {
  116452. varDeclarations += ', alias' + ++aliasCount + '=' + alias;
  116453. node.children[0] = 'alias' + aliasCount;
  116454. }
  116455. }
  116456. var params = ['container', 'depth0', 'helpers', 'partials', 'data'];
  116457. if (this.useBlockParams || this.useDepths) {
  116458. params.push('blockParams');
  116459. }
  116460. if (this.useDepths) {
  116461. params.push('depths');
  116462. }
  116463. // Perform a second pass over the output to merge content when possible
  116464. var source = this.mergeSource(varDeclarations);
  116465. if (asObject) {
  116466. params.push(source);
  116467. return Function.apply(this, params);
  116468. } else {
  116469. return this.source.wrap(['function(', params.join(','), ') {\n ', source, '}']);
  116470. }
  116471. },
  116472. mergeSource: function mergeSource(varDeclarations) {
  116473. var isSimple = this.environment.isSimple,
  116474. appendOnly = !this.forceBuffer,
  116475. appendFirst = undefined,
  116476. sourceSeen = undefined,
  116477. bufferStart = undefined,
  116478. bufferEnd = undefined;
  116479. this.source.each(function (line) {
  116480. if (line.appendToBuffer) {
  116481. if (bufferStart) {
  116482. line.prepend(' + ');
  116483. } else {
  116484. bufferStart = line;
  116485. }
  116486. bufferEnd = line;
  116487. } else {
  116488. if (bufferStart) {
  116489. if (!sourceSeen) {
  116490. appendFirst = true;
  116491. } else {
  116492. bufferStart.prepend('buffer += ');
  116493. }
  116494. bufferEnd.add(';');
  116495. bufferStart = bufferEnd = undefined;
  116496. }
  116497. sourceSeen = true;
  116498. if (!isSimple) {
  116499. appendOnly = false;
  116500. }
  116501. }
  116502. });
  116503. if (appendOnly) {
  116504. if (bufferStart) {
  116505. bufferStart.prepend('return ');
  116506. bufferEnd.add(';');
  116507. } else if (!sourceSeen) {
  116508. this.source.push('return "";');
  116509. }
  116510. } else {
  116511. varDeclarations += ', buffer = ' + (appendFirst ? '' : this.initializeBuffer());
  116512. if (bufferStart) {
  116513. bufferStart.prepend('return buffer + ');
  116514. bufferEnd.add(';');
  116515. } else {
  116516. this.source.push('return buffer;');
  116517. }
  116518. }
  116519. if (varDeclarations) {
  116520. this.source.prepend('var ' + varDeclarations.substring(2) + (appendFirst ? '' : ';\n'));
  116521. }
  116522. return this.source.merge();
  116523. },
  116524. // [blockValue]
  116525. //
  116526. // On stack, before: hash, inverse, program, value
  116527. // On stack, after: return value of blockHelperMissing
  116528. //
  116529. // The purpose of this opcode is to take a block of the form
  116530. // `{{#this.foo}}...{{/this.foo}}`, resolve the value of `foo`, and
  116531. // replace it on the stack with the result of properly
  116532. // invoking blockHelperMissing.
  116533. blockValue: function blockValue(name) {
  116534. var blockHelperMissing = this.aliasable('helpers.blockHelperMissing'),
  116535. params = [this.contextName(0)];
  116536. this.setupHelperArgs(name, 0, params);
  116537. var blockName = this.popStack();
  116538. params.splice(1, 0, blockName);
  116539. this.push(this.source.functionCall(blockHelperMissing, 'call', params));
  116540. },
  116541. // [ambiguousBlockValue]
  116542. //
  116543. // On stack, before: hash, inverse, program, value
  116544. // Compiler value, before: lastHelper=value of last found helper, if any
  116545. // On stack, after, if no lastHelper: same as [blockValue]
  116546. // On stack, after, if lastHelper: value
  116547. ambiguousBlockValue: function ambiguousBlockValue() {
  116548. // We're being a bit cheeky and reusing the options value from the prior exec
  116549. var blockHelperMissing = this.aliasable('helpers.blockHelperMissing'),
  116550. params = [this.contextName(0)];
  116551. this.setupHelperArgs('', 0, params, true);
  116552. this.flushInline();
  116553. var current = this.topStack();
  116554. params.splice(1, 0, current);
  116555. this.pushSource(['if (!', this.lastHelper, ') { ', current, ' = ', this.source.functionCall(blockHelperMissing, 'call', params), '}']);
  116556. },
  116557. // [appendContent]
  116558. //
  116559. // On stack, before: ...
  116560. // On stack, after: ...
  116561. //
  116562. // Appends the string value of `content` to the current buffer
  116563. appendContent: function appendContent(content) {
  116564. if (this.pendingContent) {
  116565. content = this.pendingContent + content;
  116566. } else {
  116567. this.pendingLocation = this.source.currentLocation;
  116568. }
  116569. this.pendingContent = content;
  116570. },
  116571. // [append]
  116572. //
  116573. // On stack, before: value, ...
  116574. // On stack, after: ...
  116575. //
  116576. // Coerces `value` to a String and appends it to the current buffer.
  116577. //
  116578. // If `value` is truthy, or 0, it is coerced into a string and appended
  116579. // Otherwise, the empty string is appended
  116580. append: function append() {
  116581. if (this.isInline()) {
  116582. this.replaceStack(function (current) {
  116583. return [' != null ? ', current, ' : ""'];
  116584. });
  116585. this.pushSource(this.appendToBuffer(this.popStack()));
  116586. } else {
  116587. var local = this.popStack();
  116588. this.pushSource(['if (', local, ' != null) { ', this.appendToBuffer(local, undefined, true), ' }']);
  116589. if (this.environment.isSimple) {
  116590. this.pushSource(['else { ', this.appendToBuffer("''", undefined, true), ' }']);
  116591. }
  116592. }
  116593. },
  116594. // [appendEscaped]
  116595. //
  116596. // On stack, before: value, ...
  116597. // On stack, after: ...
  116598. //
  116599. // Escape `value` and append it to the buffer
  116600. appendEscaped: function appendEscaped() {
  116601. this.pushSource(this.appendToBuffer([this.aliasable('container.escapeExpression'), '(', this.popStack(), ')']));
  116602. },
  116603. // [getContext]
  116604. //
  116605. // On stack, before: ...
  116606. // On stack, after: ...
  116607. // Compiler value, after: lastContext=depth
  116608. //
  116609. // Set the value of the `lastContext` compiler value to the depth
  116610. getContext: function getContext(depth) {
  116611. this.lastContext = depth;
  116612. },
  116613. // [pushContext]
  116614. //
  116615. // On stack, before: ...
  116616. // On stack, after: currentContext, ...
  116617. //
  116618. // Pushes the value of the current context onto the stack.
  116619. pushContext: function pushContext() {
  116620. this.pushStackLiteral(this.contextName(this.lastContext));
  116621. },
  116622. // [lookupOnContext]
  116623. //
  116624. // On stack, before: ...
  116625. // On stack, after: currentContext[name], ...
  116626. //
  116627. // Looks up the value of `name` on the current context and pushes
  116628. // it onto the stack.
  116629. lookupOnContext: function lookupOnContext(parts, falsy, strict, scoped) {
  116630. var i = 0;
  116631. if (!scoped && this.options.compat && !this.lastContext) {
  116632. // The depthed query is expected to handle the undefined logic for the root level that
  116633. // is implemented below, so we evaluate that directly in compat mode
  116634. this.push(this.depthedLookup(parts[i++]));
  116635. } else {
  116636. this.pushContext();
  116637. }
  116638. this.resolvePath('context', parts, i, falsy, strict);
  116639. },
  116640. // [lookupBlockParam]
  116641. //
  116642. // On stack, before: ...
  116643. // On stack, after: blockParam[name], ...
  116644. //
  116645. // Looks up the value of `parts` on the given block param and pushes
  116646. // it onto the stack.
  116647. lookupBlockParam: function lookupBlockParam(blockParamId, parts) {
  116648. this.useBlockParams = true;
  116649. this.push(['blockParams[', blockParamId[0], '][', blockParamId[1], ']']);
  116650. this.resolvePath('context', parts, 1);
  116651. },
  116652. // [lookupData]
  116653. //
  116654. // On stack, before: ...
  116655. // On stack, after: data, ...
  116656. //
  116657. // Push the data lookup operator
  116658. lookupData: function lookupData(depth, parts, strict) {
  116659. if (!depth) {
  116660. this.pushStackLiteral('data');
  116661. } else {
  116662. this.pushStackLiteral('container.data(data, ' + depth + ')');
  116663. }
  116664. this.resolvePath('data', parts, 0, true, strict);
  116665. },
  116666. resolvePath: function resolvePath(type, parts, i, falsy, strict) {
  116667. // istanbul ignore next
  116668. var _this = this;
  116669. if (this.options.strict || this.options.assumeObjects) {
  116670. this.push(strictLookup(this.options.strict && strict, this, parts, type));
  116671. return;
  116672. }
  116673. var len = parts.length;
  116674. for (; i < len; i++) {
  116675. /* eslint-disable no-loop-func */
  116676. this.replaceStack(function (current) {
  116677. var lookup = _this.nameLookup(current, parts[i], type);
  116678. // We want to ensure that zero and false are handled properly if the context (falsy flag)
  116679. // needs to have the special handling for these values.
  116680. if (!falsy) {
  116681. return [' != null ? ', lookup, ' : ', current];
  116682. } else {
  116683. // Otherwise we can use generic falsy handling
  116684. return [' && ', lookup];
  116685. }
  116686. });
  116687. /* eslint-enable no-loop-func */
  116688. }
  116689. },
  116690. // [resolvePossibleLambda]
  116691. //
  116692. // On stack, before: value, ...
  116693. // On stack, after: resolved value, ...
  116694. //
  116695. // If the `value` is a lambda, replace it on the stack by
  116696. // the return value of the lambda
  116697. resolvePossibleLambda: function resolvePossibleLambda() {
  116698. this.push([this.aliasable('container.lambda'), '(', this.popStack(), ', ', this.contextName(0), ')']);
  116699. },
  116700. // [pushStringParam]
  116701. //
  116702. // On stack, before: ...
  116703. // On stack, after: string, currentContext, ...
  116704. //
  116705. // This opcode is designed for use in string mode, which
  116706. // provides the string value of a parameter along with its
  116707. // depth rather than resolving it immediately.
  116708. pushStringParam: function pushStringParam(string, type) {
  116709. this.pushContext();
  116710. this.pushString(type);
  116711. // If it's a subexpression, the string result
  116712. // will be pushed after this opcode.
  116713. if (type !== 'SubExpression') {
  116714. if (typeof string === 'string') {
  116715. this.pushString(string);
  116716. } else {
  116717. this.pushStackLiteral(string);
  116718. }
  116719. }
  116720. },
  116721. emptyHash: function emptyHash(omitEmpty) {
  116722. if (this.trackIds) {
  116723. this.push('{}'); // hashIds
  116724. }
  116725. if (this.stringParams) {
  116726. this.push('{}'); // hashContexts
  116727. this.push('{}'); // hashTypes
  116728. }
  116729. this.pushStackLiteral(omitEmpty ? 'undefined' : '{}');
  116730. },
  116731. pushHash: function pushHash() {
  116732. if (this.hash) {
  116733. this.hashes.push(this.hash);
  116734. }
  116735. this.hash = { values: [], types: [], contexts: [], ids: [] };
  116736. },
  116737. popHash: function popHash() {
  116738. var hash = this.hash;
  116739. this.hash = this.hashes.pop();
  116740. if (this.trackIds) {
  116741. this.push(this.objectLiteral(hash.ids));
  116742. }
  116743. if (this.stringParams) {
  116744. this.push(this.objectLiteral(hash.contexts));
  116745. this.push(this.objectLiteral(hash.types));
  116746. }
  116747. this.push(this.objectLiteral(hash.values));
  116748. },
  116749. // [pushString]
  116750. //
  116751. // On stack, before: ...
  116752. // On stack, after: quotedString(string), ...
  116753. //
  116754. // Push a quoted version of `string` onto the stack
  116755. pushString: function pushString(string) {
  116756. this.pushStackLiteral(this.quotedString(string));
  116757. },
  116758. // [pushLiteral]
  116759. //
  116760. // On stack, before: ...
  116761. // On stack, after: value, ...
  116762. //
  116763. // Pushes a value onto the stack. This operation prevents
  116764. // the compiler from creating a temporary variable to hold
  116765. // it.
  116766. pushLiteral: function pushLiteral(value) {
  116767. this.pushStackLiteral(value);
  116768. },
  116769. // [pushProgram]
  116770. //
  116771. // On stack, before: ...
  116772. // On stack, after: program(guid), ...
  116773. //
  116774. // Push a program expression onto the stack. This takes
  116775. // a compile-time guid and converts it into a runtime-accessible
  116776. // expression.
  116777. pushProgram: function pushProgram(guid) {
  116778. if (guid != null) {
  116779. this.pushStackLiteral(this.programExpression(guid));
  116780. } else {
  116781. this.pushStackLiteral(null);
  116782. }
  116783. },
  116784. // [registerDecorator]
  116785. //
  116786. // On stack, before: hash, program, params..., ...
  116787. // On stack, after: ...
  116788. //
  116789. // Pops off the decorator's parameters, invokes the decorator,
  116790. // and inserts the decorator into the decorators list.
  116791. registerDecorator: function registerDecorator(paramSize, name) {
  116792. var foundDecorator = this.nameLookup('decorators', name, 'decorator'),
  116793. options = this.setupHelperArgs(name, paramSize);
  116794. this.decorators.push(['fn = ', this.decorators.functionCall(foundDecorator, '', ['fn', 'props', 'container', options]), ' || fn;']);
  116795. },
  116796. // [invokeHelper]
  116797. //
  116798. // On stack, before: hash, inverse, program, params..., ...
  116799. // On stack, after: result of helper invocation
  116800. //
  116801. // Pops off the helper's parameters, invokes the helper,
  116802. // and pushes the helper's return value onto the stack.
  116803. //
  116804. // If the helper is not found, `helperMissing` is called.
  116805. invokeHelper: function invokeHelper(paramSize, name, isSimple) {
  116806. var nonHelper = this.popStack(),
  116807. helper = this.setupHelper(paramSize, name),
  116808. simple = isSimple ? [helper.name, ' || '] : '';
  116809. var lookup = ['('].concat(simple, nonHelper);
  116810. if (!this.options.strict) {
  116811. lookup.push(' || ', this.aliasable('helpers.helperMissing'));
  116812. }
  116813. lookup.push(')');
  116814. this.push(this.source.functionCall(lookup, 'call', helper.callParams));
  116815. },
  116816. // [invokeKnownHelper]
  116817. //
  116818. // On stack, before: hash, inverse, program, params..., ...
  116819. // On stack, after: result of helper invocation
  116820. //
  116821. // This operation is used when the helper is known to exist,
  116822. // so a `helperMissing` fallback is not required.
  116823. invokeKnownHelper: function invokeKnownHelper(paramSize, name) {
  116824. var helper = this.setupHelper(paramSize, name);
  116825. this.push(this.source.functionCall(helper.name, 'call', helper.callParams));
  116826. },
  116827. // [invokeAmbiguous]
  116828. //
  116829. // On stack, before: hash, inverse, program, params..., ...
  116830. // On stack, after: result of disambiguation
  116831. //
  116832. // This operation is used when an expression like `{{foo}}`
  116833. // is provided, but we don't know at compile-time whether it
  116834. // is a helper or a path.
  116835. //
  116836. // This operation emits more code than the other options,
  116837. // and can be avoided by passing the `knownHelpers` and
  116838. // `knownHelpersOnly` flags at compile-time.
  116839. invokeAmbiguous: function invokeAmbiguous(name, helperCall) {
  116840. this.useRegister('helper');
  116841. var nonHelper = this.popStack();
  116842. this.emptyHash();
  116843. var helper = this.setupHelper(0, name, helperCall);
  116844. var helperName = this.lastHelper = this.nameLookup('helpers', name, 'helper');
  116845. var lookup = ['(', '(helper = ', helperName, ' || ', nonHelper, ')'];
  116846. if (!this.options.strict) {
  116847. lookup[0] = '(helper = ';
  116848. lookup.push(' != null ? helper : ', this.aliasable('helpers.helperMissing'));
  116849. }
  116850. this.push(['(', lookup, helper.paramsInit ? ['),(', helper.paramsInit] : [], '),', '(typeof helper === ', this.aliasable('"function"'), ' ? ', this.source.functionCall('helper', 'call', helper.callParams), ' : helper))']);
  116851. },
  116852. // [invokePartial]
  116853. //
  116854. // On stack, before: context, ...
  116855. // On stack after: result of partial invocation
  116856. //
  116857. // This operation pops off a context, invokes a partial with that context,
  116858. // and pushes the result of the invocation back.
  116859. invokePartial: function invokePartial(isDynamic, name, indent) {
  116860. var params = [],
  116861. options = this.setupParams(name, 1, params);
  116862. if (isDynamic) {
  116863. name = this.popStack();
  116864. delete options.name;
  116865. }
  116866. if (indent) {
  116867. options.indent = JSON.stringify(indent);
  116868. }
  116869. options.helpers = 'helpers';
  116870. options.partials = 'partials';
  116871. options.decorators = 'container.decorators';
  116872. if (!isDynamic) {
  116873. params.unshift(this.nameLookup('partials', name, 'partial'));
  116874. } else {
  116875. params.unshift(name);
  116876. }
  116877. if (this.options.compat) {
  116878. options.depths = 'depths';
  116879. }
  116880. options = this.objectLiteral(options);
  116881. params.push(options);
  116882. this.push(this.source.functionCall('container.invokePartial', '', params));
  116883. },
  116884. // [assignToHash]
  116885. //
  116886. // On stack, before: value, ..., hash, ...
  116887. // On stack, after: ..., hash, ...
  116888. //
  116889. // Pops a value off the stack and assigns it to the current hash
  116890. assignToHash: function assignToHash(key) {
  116891. var value = this.popStack(),
  116892. context = undefined,
  116893. type = undefined,
  116894. id = undefined;
  116895. if (this.trackIds) {
  116896. id = this.popStack();
  116897. }
  116898. if (this.stringParams) {
  116899. type = this.popStack();
  116900. context = this.popStack();
  116901. }
  116902. var hash = this.hash;
  116903. if (context) {
  116904. hash.contexts[key] = context;
  116905. }
  116906. if (type) {
  116907. hash.types[key] = type;
  116908. }
  116909. if (id) {
  116910. hash.ids[key] = id;
  116911. }
  116912. hash.values[key] = value;
  116913. },
  116914. pushId: function pushId(type, name, child) {
  116915. if (type === 'BlockParam') {
  116916. this.pushStackLiteral('blockParams[' + name[0] + '].path[' + name[1] + ']' + (child ? ' + ' + JSON.stringify('.' + child) : ''));
  116917. } else if (type === 'PathExpression') {
  116918. this.pushString(name);
  116919. } else if (type === 'SubExpression') {
  116920. this.pushStackLiteral('true');
  116921. } else {
  116922. this.pushStackLiteral('null');
  116923. }
  116924. },
  116925. // HELPERS
  116926. compiler: JavaScriptCompiler,
  116927. compileChildren: function compileChildren(environment, options) {
  116928. var children = environment.children,
  116929. child = undefined,
  116930. compiler = undefined;
  116931. for (var i = 0, l = children.length; i < l; i++) {
  116932. child = children[i];
  116933. compiler = new this.compiler(); // eslint-disable-line new-cap
  116934. var existing = this.matchExistingProgram(child);
  116935. if (existing == null) {
  116936. this.context.programs.push(''); // Placeholder to prevent name conflicts for nested children
  116937. var index = this.context.programs.length;
  116938. child.index = index;
  116939. child.name = 'program' + index;
  116940. this.context.programs[index] = compiler.compile(child, options, this.context, !this.precompile);
  116941. this.context.decorators[index] = compiler.decorators;
  116942. this.context.environments[index] = child;
  116943. this.useDepths = this.useDepths || compiler.useDepths;
  116944. this.useBlockParams = this.useBlockParams || compiler.useBlockParams;
  116945. child.useDepths = this.useDepths;
  116946. child.useBlockParams = this.useBlockParams;
  116947. } else {
  116948. child.index = existing.index;
  116949. child.name = 'program' + existing.index;
  116950. this.useDepths = this.useDepths || existing.useDepths;
  116951. this.useBlockParams = this.useBlockParams || existing.useBlockParams;
  116952. }
  116953. }
  116954. },
  116955. matchExistingProgram: function matchExistingProgram(child) {
  116956. for (var i = 0, len = this.context.environments.length; i < len; i++) {
  116957. var environment = this.context.environments[i];
  116958. if (environment && environment.equals(child)) {
  116959. return environment;
  116960. }
  116961. }
  116962. },
  116963. programExpression: function programExpression(guid) {
  116964. var child = this.environment.children[guid],
  116965. programParams = [child.index, 'data', child.blockParams];
  116966. if (this.useBlockParams || this.useDepths) {
  116967. programParams.push('blockParams');
  116968. }
  116969. if (this.useDepths) {
  116970. programParams.push('depths');
  116971. }
  116972. return 'container.program(' + programParams.join(', ') + ')';
  116973. },
  116974. useRegister: function useRegister(name) {
  116975. if (!this.registers[name]) {
  116976. this.registers[name] = true;
  116977. this.registers.list.push(name);
  116978. }
  116979. },
  116980. push: function push(expr) {
  116981. if (!(expr instanceof Literal)) {
  116982. expr = this.source.wrap(expr);
  116983. }
  116984. this.inlineStack.push(expr);
  116985. return expr;
  116986. },
  116987. pushStackLiteral: function pushStackLiteral(item) {
  116988. this.push(new Literal(item));
  116989. },
  116990. pushSource: function pushSource(source) {
  116991. if (this.pendingContent) {
  116992. this.source.push(this.appendToBuffer(this.source.quotedString(this.pendingContent), this.pendingLocation));
  116993. this.pendingContent = undefined;
  116994. }
  116995. if (source) {
  116996. this.source.push(source);
  116997. }
  116998. },
  116999. replaceStack: function replaceStack(callback) {
  117000. var prefix = ['('],
  117001. stack = undefined,
  117002. createdStack = undefined,
  117003. usedLiteral = undefined;
  117004. /* istanbul ignore next */
  117005. if (!this.isInline()) {
  117006. throw new _exception2['default']('replaceStack on non-inline');
  117007. }
  117008. // We want to merge the inline statement into the replacement statement via ','
  117009. var top = this.popStack(true);
  117010. if (top instanceof Literal) {
  117011. // Literals do not need to be inlined
  117012. stack = [top.value];
  117013. prefix = ['(', stack];
  117014. usedLiteral = true;
  117015. } else {
  117016. // Get or create the current stack name for use by the inline
  117017. createdStack = true;
  117018. var _name = this.incrStack();
  117019. prefix = ['((', this.push(_name), ' = ', top, ')'];
  117020. stack = this.topStack();
  117021. }
  117022. var item = callback.call(this, stack);
  117023. if (!usedLiteral) {
  117024. this.popStack();
  117025. }
  117026. if (createdStack) {
  117027. this.stackSlot--;
  117028. }
  117029. this.push(prefix.concat(item, ')'));
  117030. },
  117031. incrStack: function incrStack() {
  117032. this.stackSlot++;
  117033. if (this.stackSlot > this.stackVars.length) {
  117034. this.stackVars.push('stack' + this.stackSlot);
  117035. }
  117036. return this.topStackName();
  117037. },
  117038. topStackName: function topStackName() {
  117039. return 'stack' + this.stackSlot;
  117040. },
  117041. flushInline: function flushInline() {
  117042. var inlineStack = this.inlineStack;
  117043. this.inlineStack = [];
  117044. for (var i = 0, len = inlineStack.length; i < len; i++) {
  117045. var entry = inlineStack[i];
  117046. /* istanbul ignore if */
  117047. if (entry instanceof Literal) {
  117048. this.compileStack.push(entry);
  117049. } else {
  117050. var stack = this.incrStack();
  117051. this.pushSource([stack, ' = ', entry, ';']);
  117052. this.compileStack.push(stack);
  117053. }
  117054. }
  117055. },
  117056. isInline: function isInline() {
  117057. return this.inlineStack.length;
  117058. },
  117059. popStack: function popStack(wrapped) {
  117060. var inline = this.isInline(),
  117061. item = (inline ? this.inlineStack : this.compileStack).pop();
  117062. if (!wrapped && item instanceof Literal) {
  117063. return item.value;
  117064. } else {
  117065. if (!inline) {
  117066. /* istanbul ignore next */
  117067. if (!this.stackSlot) {
  117068. throw new _exception2['default']('Invalid stack pop');
  117069. }
  117070. this.stackSlot--;
  117071. }
  117072. return item;
  117073. }
  117074. },
  117075. topStack: function topStack() {
  117076. var stack = this.isInline() ? this.inlineStack : this.compileStack,
  117077. item = stack[stack.length - 1];
  117078. /* istanbul ignore if */
  117079. if (item instanceof Literal) {
  117080. return item.value;
  117081. } else {
  117082. return item;
  117083. }
  117084. },
  117085. contextName: function contextName(context) {
  117086. if (this.useDepths && context) {
  117087. return 'depths[' + context + ']';
  117088. } else {
  117089. return 'depth' + context;
  117090. }
  117091. },
  117092. quotedString: function quotedString(str) {
  117093. return this.source.quotedString(str);
  117094. },
  117095. objectLiteral: function objectLiteral(obj) {
  117096. return this.source.objectLiteral(obj);
  117097. },
  117098. aliasable: function aliasable(name) {
  117099. var ret = this.aliases[name];
  117100. if (ret) {
  117101. ret.referenceCount++;
  117102. return ret;
  117103. }
  117104. ret = this.aliases[name] = this.source.wrap(name);
  117105. ret.aliasable = true;
  117106. ret.referenceCount = 1;
  117107. return ret;
  117108. },
  117109. setupHelper: function setupHelper(paramSize, name, blockHelper) {
  117110. var params = [],
  117111. paramsInit = this.setupHelperArgs(name, paramSize, params, blockHelper);
  117112. var foundHelper = this.nameLookup('helpers', name, 'helper'),
  117113. callContext = this.aliasable(this.contextName(0) + ' != null ? ' + this.contextName(0) + ' : (container.nullContext || {})');
  117114. return {
  117115. params: params,
  117116. paramsInit: paramsInit,
  117117. name: foundHelper,
  117118. callParams: [callContext].concat(params)
  117119. };
  117120. },
  117121. setupParams: function setupParams(helper, paramSize, params) {
  117122. var options = {},
  117123. contexts = [],
  117124. types = [],
  117125. ids = [],
  117126. objectArgs = !params,
  117127. param = undefined;
  117128. if (objectArgs) {
  117129. params = [];
  117130. }
  117131. options.name = this.quotedString(helper);
  117132. options.hash = this.popStack();
  117133. if (this.trackIds) {
  117134. options.hashIds = this.popStack();
  117135. }
  117136. if (this.stringParams) {
  117137. options.hashTypes = this.popStack();
  117138. options.hashContexts = this.popStack();
  117139. }
  117140. var inverse = this.popStack(),
  117141. program = this.popStack();
  117142. // Avoid setting fn and inverse if neither are set. This allows
  117143. // helpers to do a check for `if (options.fn)`
  117144. if (program || inverse) {
  117145. options.fn = program || 'container.noop';
  117146. options.inverse = inverse || 'container.noop';
  117147. }
  117148. // The parameters go on to the stack in order (making sure that they are evaluated in order)
  117149. // so we need to pop them off the stack in reverse order
  117150. var i = paramSize;
  117151. while (i--) {
  117152. param = this.popStack();
  117153. params[i] = param;
  117154. if (this.trackIds) {
  117155. ids[i] = this.popStack();
  117156. }
  117157. if (this.stringParams) {
  117158. types[i] = this.popStack();
  117159. contexts[i] = this.popStack();
  117160. }
  117161. }
  117162. if (objectArgs) {
  117163. options.args = this.source.generateArray(params);
  117164. }
  117165. if (this.trackIds) {
  117166. options.ids = this.source.generateArray(ids);
  117167. }
  117168. if (this.stringParams) {
  117169. options.types = this.source.generateArray(types);
  117170. options.contexts = this.source.generateArray(contexts);
  117171. }
  117172. if (this.options.data) {
  117173. options.data = 'data';
  117174. }
  117175. if (this.useBlockParams) {
  117176. options.blockParams = 'blockParams';
  117177. }
  117178. return options;
  117179. },
  117180. setupHelperArgs: function setupHelperArgs(helper, paramSize, params, useRegister) {
  117181. var options = this.setupParams(helper, paramSize, params);
  117182. options = this.objectLiteral(options);
  117183. if (useRegister) {
  117184. this.useRegister('options');
  117185. params.push('options');
  117186. return ['options=', options];
  117187. } else if (params) {
  117188. params.push(options);
  117189. return '';
  117190. } else {
  117191. return options;
  117192. }
  117193. }
  117194. };
  117195. (function () {
  117196. 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(' ');
  117197. var compilerWords = JavaScriptCompiler.RESERVED_WORDS = {};
  117198. for (var i = 0, l = reservedWords.length; i < l; i++) {
  117199. compilerWords[reservedWords[i]] = true;
  117200. }
  117201. })();
  117202. JavaScriptCompiler.isValidJavaScriptVariableName = function (name) {
  117203. return !JavaScriptCompiler.RESERVED_WORDS[name] && /^[a-zA-Z_$][0-9a-zA-Z_$]*$/.test(name);
  117204. };
  117205. function strictLookup(requireTerminal, compiler, parts, type) {
  117206. var stack = compiler.popStack(),
  117207. i = 0,
  117208. len = parts.length;
  117209. if (requireTerminal) {
  117210. len--;
  117211. }
  117212. for (; i < len; i++) {
  117213. stack = compiler.nameLookup(stack, parts[i], type);
  117214. }
  117215. if (requireTerminal) {
  117216. return [compiler.aliasable('container.strict'), '(', stack, ', ', compiler.quotedString(parts[i]), ')'];
  117217. } else {
  117218. return stack;
  117219. }
  117220. }
  117221. exports['default'] = JavaScriptCompiler;
  117222. module.exports = exports['default'];
  117223. /***/ }),
  117224. /* 43 */
  117225. /***/ (function(module, exports, __webpack_require__) {
  117226. /* global define */
  117227. 'use strict';
  117228. exports.__esModule = true;
  117229. var _utils = __webpack_require__(5);
  117230. var SourceNode = undefined;
  117231. try {
  117232. /* istanbul ignore next */
  117233. if (false) {
  117234. // We don't support this in AMD environments. For these environments, we asusme that
  117235. // they are running on the browser and thus have no need for the source-map library.
  117236. var SourceMap = require('source-map');
  117237. SourceNode = SourceMap.SourceNode;
  117238. }
  117239. } catch (err) {}
  117240. /* NOP */
  117241. /* istanbul ignore if: tested but not covered in istanbul due to dist build */
  117242. if (!SourceNode) {
  117243. SourceNode = function (line, column, srcFile, chunks) {
  117244. this.src = '';
  117245. if (chunks) {
  117246. this.add(chunks);
  117247. }
  117248. };
  117249. /* istanbul ignore next */
  117250. SourceNode.prototype = {
  117251. add: function add(chunks) {
  117252. if (_utils.isArray(chunks)) {
  117253. chunks = chunks.join('');
  117254. }
  117255. this.src += chunks;
  117256. },
  117257. prepend: function prepend(chunks) {
  117258. if (_utils.isArray(chunks)) {
  117259. chunks = chunks.join('');
  117260. }
  117261. this.src = chunks + this.src;
  117262. },
  117263. toStringWithSourceMap: function toStringWithSourceMap() {
  117264. return { code: this.toString() };
  117265. },
  117266. toString: function toString() {
  117267. return this.src;
  117268. }
  117269. };
  117270. }
  117271. function castChunk(chunk, codeGen, loc) {
  117272. if (_utils.isArray(chunk)) {
  117273. var ret = [];
  117274. for (var i = 0, len = chunk.length; i < len; i++) {
  117275. ret.push(codeGen.wrap(chunk[i], loc));
  117276. }
  117277. return ret;
  117278. } else if (typeof chunk === 'boolean' || typeof chunk === 'number') {
  117279. // Handle primitives that the SourceNode will throw up on
  117280. return chunk + '';
  117281. }
  117282. return chunk;
  117283. }
  117284. function CodeGen(srcFile) {
  117285. this.srcFile = srcFile;
  117286. this.source = [];
  117287. }
  117288. CodeGen.prototype = {
  117289. isEmpty: function isEmpty() {
  117290. return !this.source.length;
  117291. },
  117292. prepend: function prepend(source, loc) {
  117293. this.source.unshift(this.wrap(source, loc));
  117294. },
  117295. push: function push(source, loc) {
  117296. this.source.push(this.wrap(source, loc));
  117297. },
  117298. merge: function merge() {
  117299. var source = this.empty();
  117300. this.each(function (line) {
  117301. source.add([' ', line, '\n']);
  117302. });
  117303. return source;
  117304. },
  117305. each: function each(iter) {
  117306. for (var i = 0, len = this.source.length; i < len; i++) {
  117307. iter(this.source[i]);
  117308. }
  117309. },
  117310. empty: function empty() {
  117311. var loc = this.currentLocation || { start: {} };
  117312. return new SourceNode(loc.start.line, loc.start.column, this.srcFile);
  117313. },
  117314. wrap: function wrap(chunk) {
  117315. var loc = arguments.length <= 1 || arguments[1] === undefined ? this.currentLocation || { start: {} } : arguments[1];
  117316. if (chunk instanceof SourceNode) {
  117317. return chunk;
  117318. }
  117319. chunk = castChunk(chunk, this, loc);
  117320. return new SourceNode(loc.start.line, loc.start.column, this.srcFile, chunk);
  117321. },
  117322. functionCall: function functionCall(fn, type, params) {
  117323. params = this.generateList(params);
  117324. return this.wrap([fn, type ? '.' + type + '(' : '(', params, ')']);
  117325. },
  117326. quotedString: function quotedString(str) {
  117327. 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
  117328. .replace(/\u2029/g, '\\u2029') + '"';
  117329. },
  117330. objectLiteral: function objectLiteral(obj) {
  117331. var pairs = [];
  117332. for (var key in obj) {
  117333. if (obj.hasOwnProperty(key)) {
  117334. var value = castChunk(obj[key], this);
  117335. if (value !== 'undefined') {
  117336. pairs.push([this.quotedString(key), ':', value]);
  117337. }
  117338. }
  117339. }
  117340. var ret = this.generateList(pairs);
  117341. ret.prepend('{');
  117342. ret.add('}');
  117343. return ret;
  117344. },
  117345. generateList: function generateList(entries) {
  117346. var ret = this.empty();
  117347. for (var i = 0, len = entries.length; i < len; i++) {
  117348. if (i) {
  117349. ret.add(',');
  117350. }
  117351. ret.add(castChunk(entries[i], this));
  117352. }
  117353. return ret;
  117354. },
  117355. generateArray: function generateArray(entries) {
  117356. var ret = this.generateList(entries);
  117357. ret.prepend('[');
  117358. ret.add(']');
  117359. return ret;
  117360. }
  117361. };
  117362. exports['default'] = CodeGen;
  117363. module.exports = exports['default'];
  117364. /***/ })
  117365. /******/ ])
  117366. });
  117367. ;
  117368. /***/ }),
  117369. /* 63 */
  117370. /***/ (function(module, exports, __webpack_require__) {
  117371. "use strict";
  117372. Object.defineProperty(exports, "__esModule", { value: true });
  117373. /**
  117374. * The EventManager is in charge of registering user interctions with the viewer.
  117375. * It is used in the TemplateManager
  117376. */
  117377. var EventManager = /** @class */ (function () {
  117378. function EventManager(_templateManager) {
  117379. var _this = this;
  117380. this._templateManager = _templateManager;
  117381. this._callbacksContainer = {};
  117382. this._templateManager.onEventTriggered.add(function (eventData) {
  117383. _this._eventTriggered(eventData);
  117384. });
  117385. }
  117386. /**
  117387. * Register a new callback to a specific template.
  117388. * The best example for the usage can be found in the DefaultViewer
  117389. *
  117390. * @param templateName the templateName to register the event to
  117391. * @param callback The callback to be executed
  117392. * @param eventType the type of event to register
  117393. * @param selector an optional selector. if not defined the parent object in the template will be selected
  117394. */
  117395. EventManager.prototype.registerCallback = function (templateName, callback, eventType, selector) {
  117396. if (!this._callbacksContainer[templateName]) {
  117397. this._callbacksContainer[templateName] = [];
  117398. }
  117399. this._callbacksContainer[templateName].push({
  117400. eventType: eventType,
  117401. callback: callback,
  117402. selector: selector
  117403. });
  117404. };
  117405. /**
  117406. * This will remove a registered event from the defined template.
  117407. * Each one of the variables apart from the template name are optional, but one must be provided.
  117408. *
  117409. * @param templateName the templateName
  117410. * @param callback the callback to remove (optional)
  117411. * @param eventType the event type to remove (optional)
  117412. * @param selector the selector from which to remove the event (optional)
  117413. */
  117414. EventManager.prototype.unregisterCallback = function (templateName, callback, eventType, selector) {
  117415. var callbackDefs = this._callbacksContainer[templateName] || [];
  117416. this._callbacksContainer[templateName] = callbackDefs.filter(function (callbackDef) { return (!callbackDef.eventType || callbackDef.eventType === eventType) && (!callbackDef.selector || callbackDef.selector === selector); });
  117417. };
  117418. EventManager.prototype._eventTriggered = function (data) {
  117419. var templateName = data.template.name;
  117420. var eventType = data.event.type;
  117421. var selector = data.selector;
  117422. var callbackDefs = this._callbacksContainer[templateName] || [];
  117423. callbackDefs.filter(function (callbackDef) { return (!callbackDef.eventType || callbackDef.eventType === eventType) && (!callbackDef.selector || callbackDef.selector === selector); }).forEach(function (callbackDef) {
  117424. callbackDef.callback(data);
  117425. });
  117426. };
  117427. /**
  117428. * Dispose the event manager
  117429. */
  117430. EventManager.prototype.dispose = function () {
  117431. this._callbacksContainer = {};
  117432. };
  117433. return EventManager;
  117434. }());
  117435. exports.EventManager = EventManager;
  117436. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZXZlbnRNYW5hZ2VyLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vLi4vc3JjL3RlbXBsYXRpbmcvZXZlbnRNYW5hZ2VyLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7O0FBR0E7OztHQUdHO0FBQ0g7SUFJSSxzQkFBb0IsZ0JBQWlDO1FBQXJELGlCQUtDO1FBTG1CLHFCQUFnQixHQUFoQixnQkFBZ0IsQ0FBaUI7UUFDakQsSUFBSSxDQUFDLG1CQUFtQixHQUFHLEVBQUUsQ0FBQztRQUM5QixJQUFJLENBQUMsZ0JBQWdCLENBQUMsZ0JBQWdCLENBQUMsR0FBRyxDQUFDLFVBQUEsU0FBUztZQUNoRCxLQUFJLENBQUMsZUFBZSxDQUFDLFNBQVMsQ0FBQyxDQUFDO1FBQ3BDLENBQUMsQ0FBQyxDQUFBO0lBQ04sQ0FBQztJQUVEOzs7Ozs7OztPQVFHO0lBQ0ksdUNBQWdCLEdBQXZCLFVBQXdCLFlBQW9CLEVBQUUsUUFBNEMsRUFBRSxTQUF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EdBQUcsSUFBSSxDQUFDLFFBQVEsQ0FBQztRQUU3QixJQUFJLFlBQVksR0FBRyxJQUFJLENBQUMsbUJBQW1CLENBQUMsWUFBWSxDQUFDLElBQUksRUFBRSxDQUFDO1FBQ2hFLFlBQVksQ0FBQyxNQUFNLENBQUMsVUFBQSxXQUFXLElBQUksT0FBQSxDQUFDLENBQUMsV0FBVyxDQUFDLFNBQVMsSUFBSSxXQUFXLENBQUMsU0FBUyxLQUFLLFNBQVMsQ0FBQyxJQUFJLENBQUMsQ0FBQyxXQUFXLENBQUMsUUFBUSxJQUFJLFdBQVcsQ0FBQyxRQUFRLEtBQUssUUFBUSxDQUFDLEVBQS9ILENBQStILENBQUMsQ0FBQyxPQUFPLENBQUMsVUFBQSxXQUFXO1lBQ25MLFdBQVcsQ0FBQyxRQUFRLENBQUMsSUFBSSxDQUFDLENBQUM7UUFDL0IsQ0FBQyxDQUFDLENBQUM7SUFDUCxDQUFDO0lBRUQ7O09BRUc7SUFDSSw4QkFBTyxHQUFkO1FBQ0ksSUFBSSxDQUFDLG1CQUFtQixHQUFHLEVBQUUsQ0FBQztJQUNsQyxDQUFDO0lBQ0wsbUJBQUM7QUFBRCxDQUFDLEFBOURELElBOERDO0FBOURZLG9DQUFZIn0=
  117437. /***/ }),
  117438. /* 64 */
  117439. /***/ (function(module, exports, __webpack_require__) {
  117440. /*!
  117441. * PEP v0.4.3 | https://github.com/jquery/PEP
  117442. * Copyright jQuery Foundation and other contributors | http://jquery.org/license
  117443. */
  117444. (function (global, factory) {
  117445. true ? module.exports = factory() :
  117446. typeof define === 'function' && define.amd ? define(factory) :
  117447. (global.PointerEventsPolyfill = factory());
  117448. }(this, function () { 'use strict';
  117449. /**
  117450. * This is the constructor for new PointerEvents.
  117451. *
  117452. * New Pointer Events must be given a type, and an optional dictionary of
  117453. * initialization properties.
  117454. *
  117455. * Due to certain platform requirements, events returned from the constructor
  117456. * identify as MouseEvents.
  117457. *
  117458. * @constructor
  117459. * @param {String} inType The type of the event to create.
  117460. * @param {Object} [inDict] An optional dictionary of initial event properties.
  117461. * @return {Event} A new PointerEvent of type `inType`, initialized with properties from `inDict`.
  117462. */
  117463. var MOUSE_PROPS = [
  117464. 'bubbles',
  117465. 'cancelable',
  117466. 'view',
  117467. 'detail',
  117468. 'screenX',
  117469. 'screenY',
  117470. 'clientX',
  117471. 'clientY',
  117472. 'ctrlKey',
  117473. 'altKey',
  117474. 'shiftKey',
  117475. 'metaKey',
  117476. 'button',
  117477. 'relatedTarget',
  117478. 'pageX',
  117479. 'pageY'
  117480. ];
  117481. var MOUSE_DEFAULTS = [
  117482. false,
  117483. false,
  117484. null,
  117485. null,
  117486. 0,
  117487. 0,
  117488. 0,
  117489. 0,
  117490. false,
  117491. false,
  117492. false,
  117493. false,
  117494. 0,
  117495. null,
  117496. 0,
  117497. 0
  117498. ];
  117499. function PointerEvent(inType, inDict) {
  117500. inDict = inDict || Object.create(null);
  117501. var e = document.createEvent('Event');
  117502. e.initEvent(inType, inDict.bubbles || false, inDict.cancelable || false);
  117503. // define inherited MouseEvent properties
  117504. // skip bubbles and cancelable since they're set above in initEvent()
  117505. for (var i = 2, p; i < MOUSE_PROPS.length; i++) {
  117506. p = MOUSE_PROPS[i];
  117507. e[p] = inDict[p] || MOUSE_DEFAULTS[i];
  117508. }
  117509. e.buttons = inDict.buttons || 0;
  117510. // Spec requires that pointers without pressure specified use 0.5 for down
  117511. // state and 0 for up state.
  117512. var pressure = 0;
  117513. if (inDict.pressure && e.buttons) {
  117514. pressure = inDict.pressure;
  117515. } else {
  117516. pressure = e.buttons ? 0.5 : 0;
  117517. }
  117518. // add x/y properties aliased to clientX/Y
  117519. e.x = e.clientX;
  117520. e.y = e.clientY;
  117521. // define the properties of the PointerEvent interface
  117522. e.pointerId = inDict.pointerId || 0;
  117523. e.width = inDict.width || 0;
  117524. e.height = inDict.height || 0;
  117525. e.pressure = pressure;
  117526. e.tiltX = inDict.tiltX || 0;
  117527. e.tiltY = inDict.tiltY || 0;
  117528. e.twist = inDict.twist || 0;
  117529. e.tangentialPressure = inDict.tangentialPressure || 0;
  117530. e.pointerType = inDict.pointerType || '';
  117531. e.hwTimestamp = inDict.hwTimestamp || 0;
  117532. e.isPrimary = inDict.isPrimary || false;
  117533. return e;
  117534. }
  117535. /**
  117536. * This module implements a map of pointer states
  117537. */
  117538. var USE_MAP = window.Map && window.Map.prototype.forEach;
  117539. var PointerMap = USE_MAP ? Map : SparseArrayMap;
  117540. function SparseArrayMap() {
  117541. this.array = [];
  117542. this.size = 0;
  117543. }
  117544. SparseArrayMap.prototype = {
  117545. set: function(k, v) {
  117546. if (v === undefined) {
  117547. return this.delete(k);
  117548. }
  117549. if (!this.has(k)) {
  117550. this.size++;
  117551. }
  117552. this.array[k] = v;
  117553. },
  117554. has: function(k) {
  117555. return this.array[k] !== undefined;
  117556. },
  117557. delete: function(k) {
  117558. if (this.has(k)) {
  117559. delete this.array[k];
  117560. this.size--;
  117561. }
  117562. },
  117563. get: function(k) {
  117564. return this.array[k];
  117565. },
  117566. clear: function() {
  117567. this.array.length = 0;
  117568. this.size = 0;
  117569. },
  117570. // return value, key, map
  117571. forEach: function(callback, thisArg) {
  117572. return this.array.forEach(function(v, k) {
  117573. callback.call(thisArg, v, k, this);
  117574. }, this);
  117575. }
  117576. };
  117577. var CLONE_PROPS = [
  117578. // MouseEvent
  117579. 'bubbles',
  117580. 'cancelable',
  117581. 'view',
  117582. 'detail',
  117583. 'screenX',
  117584. 'screenY',
  117585. 'clientX',
  117586. 'clientY',
  117587. 'ctrlKey',
  117588. 'altKey',
  117589. 'shiftKey',
  117590. 'metaKey',
  117591. 'button',
  117592. 'relatedTarget',
  117593. // DOM Level 3
  117594. 'buttons',
  117595. // PointerEvent
  117596. 'pointerId',
  117597. 'width',
  117598. 'height',
  117599. 'pressure',
  117600. 'tiltX',
  117601. 'tiltY',
  117602. 'pointerType',
  117603. 'hwTimestamp',
  117604. 'isPrimary',
  117605. // event instance
  117606. 'type',
  117607. 'target',
  117608. 'currentTarget',
  117609. 'which',
  117610. 'pageX',
  117611. 'pageY',
  117612. 'timeStamp'
  117613. ];
  117614. var CLONE_DEFAULTS = [
  117615. // MouseEvent
  117616. false,
  117617. false,
  117618. null,
  117619. null,
  117620. 0,
  117621. 0,
  117622. 0,
  117623. 0,
  117624. false,
  117625. false,
  117626. false,
  117627. false,
  117628. 0,
  117629. null,
  117630. // DOM Level 3
  117631. 0,
  117632. // PointerEvent
  117633. 0,
  117634. 0,
  117635. 0,
  117636. 0,
  117637. 0,
  117638. 0,
  117639. '',
  117640. 0,
  117641. false,
  117642. // event instance
  117643. '',
  117644. null,
  117645. null,
  117646. 0,
  117647. 0,
  117648. 0,
  117649. 0
  117650. ];
  117651. var BOUNDARY_EVENTS = {
  117652. 'pointerover': 1,
  117653. 'pointerout': 1,
  117654. 'pointerenter': 1,
  117655. 'pointerleave': 1
  117656. };
  117657. var HAS_SVG_INSTANCE = (typeof SVGElementInstance !== 'undefined');
  117658. /**
  117659. * This module is for normalizing events. Mouse and Touch events will be
  117660. * collected here, and fire PointerEvents that have the same semantics, no
  117661. * matter the source.
  117662. * Events fired:
  117663. * - pointerdown: a pointing is added
  117664. * - pointerup: a pointer is removed
  117665. * - pointermove: a pointer is moved
  117666. * - pointerover: a pointer crosses into an element
  117667. * - pointerout: a pointer leaves an element
  117668. * - pointercancel: a pointer will no longer generate events
  117669. */
  117670. var dispatcher = {
  117671. pointermap: new PointerMap(),
  117672. eventMap: Object.create(null),
  117673. captureInfo: Object.create(null),
  117674. // Scope objects for native events.
  117675. // This exists for ease of testing.
  117676. eventSources: Object.create(null),
  117677. eventSourceList: [],
  117678. /**
  117679. * Add a new event source that will generate pointer events.
  117680. *
  117681. * `inSource` must contain an array of event names named `events`, and
  117682. * functions with the names specified in the `events` array.
  117683. * @param {string} name A name for the event source
  117684. * @param {Object} source A new source of platform events.
  117685. */
  117686. registerSource: function(name, source) {
  117687. var s = source;
  117688. var newEvents = s.events;
  117689. if (newEvents) {
  117690. newEvents.forEach(function(e) {
  117691. if (s[e]) {
  117692. this.eventMap[e] = s[e].bind(s);
  117693. }
  117694. }, this);
  117695. this.eventSources[name] = s;
  117696. this.eventSourceList.push(s);
  117697. }
  117698. },
  117699. register: function(element) {
  117700. var l = this.eventSourceList.length;
  117701. for (var i = 0, es; (i < l) && (es = this.eventSourceList[i]); i++) {
  117702. // call eventsource register
  117703. es.register.call(es, element);
  117704. }
  117705. },
  117706. unregister: function(element) {
  117707. var l = this.eventSourceList.length;
  117708. for (var i = 0, es; (i < l) && (es = this.eventSourceList[i]); i++) {
  117709. // call eventsource register
  117710. es.unregister.call(es, element);
  117711. }
  117712. },
  117713. contains: /*scope.external.contains || */function(container, contained) {
  117714. try {
  117715. return container.contains(contained);
  117716. } catch (ex) {
  117717. // most likely: https://bugzilla.mozilla.org/show_bug.cgi?id=208427
  117718. return false;
  117719. }
  117720. },
  117721. // EVENTS
  117722. down: function(inEvent) {
  117723. inEvent.bubbles = true;
  117724. this.fireEvent('pointerdown', inEvent);
  117725. },
  117726. move: function(inEvent) {
  117727. inEvent.bubbles = true;
  117728. this.fireEvent('pointermove', inEvent);
  117729. },
  117730. up: function(inEvent) {
  117731. inEvent.bubbles = true;
  117732. this.fireEvent('pointerup', inEvent);
  117733. },
  117734. enter: function(inEvent) {
  117735. inEvent.bubbles = false;
  117736. this.fireEvent('pointerenter', inEvent);
  117737. },
  117738. leave: function(inEvent) {
  117739. inEvent.bubbles = false;
  117740. this.fireEvent('pointerleave', inEvent);
  117741. },
  117742. over: function(inEvent) {
  117743. inEvent.bubbles = true;
  117744. this.fireEvent('pointerover', inEvent);
  117745. },
  117746. out: function(inEvent) {
  117747. inEvent.bubbles = true;
  117748. this.fireEvent('pointerout', inEvent);
  117749. },
  117750. cancel: function(inEvent) {
  117751. inEvent.bubbles = true;
  117752. this.fireEvent('pointercancel', inEvent);
  117753. },
  117754. leaveOut: function(event) {
  117755. this.out(event);
  117756. this.propagate(event, this.leave, false);
  117757. },
  117758. enterOver: function(event) {
  117759. this.over(event);
  117760. this.propagate(event, this.enter, true);
  117761. },
  117762. // LISTENER LOGIC
  117763. eventHandler: function(inEvent) {
  117764. // This is used to prevent multiple dispatch of pointerevents from
  117765. // platform events. This can happen when two elements in different scopes
  117766. // are set up to create pointer events, which is relevant to Shadow DOM.
  117767. if (inEvent._handledByPE) {
  117768. return;
  117769. }
  117770. var type = inEvent.type;
  117771. var fn = this.eventMap && this.eventMap[type];
  117772. if (fn) {
  117773. fn(inEvent);
  117774. }
  117775. inEvent._handledByPE = true;
  117776. },
  117777. // set up event listeners
  117778. listen: function(target, events) {
  117779. events.forEach(function(e) {
  117780. this.addEvent(target, e);
  117781. }, this);
  117782. },
  117783. // remove event listeners
  117784. unlisten: function(target, events) {
  117785. events.forEach(function(e) {
  117786. this.removeEvent(target, e);
  117787. }, this);
  117788. },
  117789. addEvent: /*scope.external.addEvent || */function(target, eventName) {
  117790. target.addEventListener(eventName, this.boundHandler);
  117791. },
  117792. removeEvent: /*scope.external.removeEvent || */function(target, eventName) {
  117793. target.removeEventListener(eventName, this.boundHandler);
  117794. },
  117795. // EVENT CREATION AND TRACKING
  117796. /**
  117797. * Creates a new Event of type `inType`, based on the information in
  117798. * `inEvent`.
  117799. *
  117800. * @param {string} inType A string representing the type of event to create
  117801. * @param {Event} inEvent A platform event with a target
  117802. * @return {Event} A PointerEvent of type `inType`
  117803. */
  117804. makeEvent: function(inType, inEvent) {
  117805. // relatedTarget must be null if pointer is captured
  117806. if (this.captureInfo[inEvent.pointerId]) {
  117807. inEvent.relatedTarget = null;
  117808. }
  117809. var e = new PointerEvent(inType, inEvent);
  117810. if (inEvent.preventDefault) {
  117811. e.preventDefault = inEvent.preventDefault;
  117812. }
  117813. e._target = e._target || inEvent.target;
  117814. return e;
  117815. },
  117816. // make and dispatch an event in one call
  117817. fireEvent: function(inType, inEvent) {
  117818. var e = this.makeEvent(inType, inEvent);
  117819. return this.dispatchEvent(e);
  117820. },
  117821. /**
  117822. * Returns a snapshot of inEvent, with writable properties.
  117823. *
  117824. * @param {Event} inEvent An event that contains properties to copy.
  117825. * @return {Object} An object containing shallow copies of `inEvent`'s
  117826. * properties.
  117827. */
  117828. cloneEvent: function(inEvent) {
  117829. var eventCopy = Object.create(null);
  117830. var p;
  117831. for (var i = 0; i < CLONE_PROPS.length; i++) {
  117832. p = CLONE_PROPS[i];
  117833. eventCopy[p] = inEvent[p] || CLONE_DEFAULTS[i];
  117834. // Work around SVGInstanceElement shadow tree
  117835. // Return the <use> element that is represented by the instance for Safari, Chrome, IE.
  117836. // This is the behavior implemented by Firefox.
  117837. if (HAS_SVG_INSTANCE && (p === 'target' || p === 'relatedTarget')) {
  117838. if (eventCopy[p] instanceof SVGElementInstance) {
  117839. eventCopy[p] = eventCopy[p].correspondingUseElement;
  117840. }
  117841. }
  117842. }
  117843. // keep the semantics of preventDefault
  117844. if (inEvent.preventDefault) {
  117845. eventCopy.preventDefault = function() {
  117846. inEvent.preventDefault();
  117847. };
  117848. }
  117849. return eventCopy;
  117850. },
  117851. getTarget: function(inEvent) {
  117852. var capture = this.captureInfo[inEvent.pointerId];
  117853. if (!capture) {
  117854. return inEvent._target;
  117855. }
  117856. if (inEvent._target === capture || !(inEvent.type in BOUNDARY_EVENTS)) {
  117857. return capture;
  117858. }
  117859. },
  117860. propagate: function(event, fn, propagateDown) {
  117861. var target = event.target;
  117862. var targets = [];
  117863. // Order of conditions due to document.contains() missing in IE.
  117864. while (target !== document && !target.contains(event.relatedTarget)) {
  117865. targets.push(target);
  117866. target = target.parentNode;
  117867. // Touch: Do not propagate if node is detached.
  117868. if (!target) {
  117869. return;
  117870. }
  117871. }
  117872. if (propagateDown) {
  117873. targets.reverse();
  117874. }
  117875. targets.forEach(function(target) {
  117876. event.target = target;
  117877. fn.call(this, event);
  117878. }, this);
  117879. },
  117880. setCapture: function(inPointerId, inTarget, skipDispatch) {
  117881. if (this.captureInfo[inPointerId]) {
  117882. this.releaseCapture(inPointerId, skipDispatch);
  117883. }
  117884. this.captureInfo[inPointerId] = inTarget;
  117885. this.implicitRelease = this.releaseCapture.bind(this, inPointerId, skipDispatch);
  117886. document.addEventListener('pointerup', this.implicitRelease);
  117887. document.addEventListener('pointercancel', this.implicitRelease);
  117888. var e = new PointerEvent('gotpointercapture');
  117889. e.pointerId = inPointerId;
  117890. e._target = inTarget;
  117891. if (!skipDispatch) {
  117892. this.asyncDispatchEvent(e);
  117893. }
  117894. },
  117895. releaseCapture: function(inPointerId, skipDispatch) {
  117896. var t = this.captureInfo[inPointerId];
  117897. if (!t) {
  117898. return;
  117899. }
  117900. this.captureInfo[inPointerId] = undefined;
  117901. document.removeEventListener('pointerup', this.implicitRelease);
  117902. document.removeEventListener('pointercancel', this.implicitRelease);
  117903. var e = new PointerEvent('lostpointercapture');
  117904. e.pointerId = inPointerId;
  117905. e._target = t;
  117906. if (!skipDispatch) {
  117907. this.asyncDispatchEvent(e);
  117908. }
  117909. },
  117910. /**
  117911. * Dispatches the event to its target.
  117912. *
  117913. * @param {Event} inEvent The event to be dispatched.
  117914. * @return {Boolean} True if an event handler returns true, false otherwise.
  117915. */
  117916. dispatchEvent: /*scope.external.dispatchEvent || */function(inEvent) {
  117917. var t = this.getTarget(inEvent);
  117918. if (t) {
  117919. return t.dispatchEvent(inEvent);
  117920. }
  117921. },
  117922. asyncDispatchEvent: function(inEvent) {
  117923. requestAnimationFrame(this.dispatchEvent.bind(this, inEvent));
  117924. }
  117925. };
  117926. dispatcher.boundHandler = dispatcher.eventHandler.bind(dispatcher);
  117927. var targeting = {
  117928. shadow: function(inEl) {
  117929. if (inEl) {
  117930. return inEl.shadowRoot || inEl.webkitShadowRoot;
  117931. }
  117932. },
  117933. canTarget: function(shadow) {
  117934. return shadow && Boolean(shadow.elementFromPoint);
  117935. },
  117936. targetingShadow: function(inEl) {
  117937. var s = this.shadow(inEl);
  117938. if (this.canTarget(s)) {
  117939. return s;
  117940. }
  117941. },
  117942. olderShadow: function(shadow) {
  117943. var os = shadow.olderShadowRoot;
  117944. if (!os) {
  117945. var se = shadow.querySelector('shadow');
  117946. if (se) {
  117947. os = se.olderShadowRoot;
  117948. }
  117949. }
  117950. return os;
  117951. },
  117952. allShadows: function(element) {
  117953. var shadows = [];
  117954. var s = this.shadow(element);
  117955. while (s) {
  117956. shadows.push(s);
  117957. s = this.olderShadow(s);
  117958. }
  117959. return shadows;
  117960. },
  117961. searchRoot: function(inRoot, x, y) {
  117962. if (inRoot) {
  117963. var t = inRoot.elementFromPoint(x, y);
  117964. var st, sr;
  117965. // is element a shadow host?
  117966. sr = this.targetingShadow(t);
  117967. while (sr) {
  117968. // find the the element inside the shadow root
  117969. st = sr.elementFromPoint(x, y);
  117970. if (!st) {
  117971. // check for older shadows
  117972. sr = this.olderShadow(sr);
  117973. } else {
  117974. // shadowed element may contain a shadow root
  117975. var ssr = this.targetingShadow(st);
  117976. return this.searchRoot(ssr, x, y) || st;
  117977. }
  117978. }
  117979. // light dom element is the target
  117980. return t;
  117981. }
  117982. },
  117983. owner: function(element) {
  117984. var s = element;
  117985. // walk up until you hit the shadow root or document
  117986. while (s.parentNode) {
  117987. s = s.parentNode;
  117988. }
  117989. // the owner element is expected to be a Document or ShadowRoot
  117990. if (s.nodeType !== Node.DOCUMENT_NODE && s.nodeType !== Node.DOCUMENT_FRAGMENT_NODE) {
  117991. s = document;
  117992. }
  117993. return s;
  117994. },
  117995. findTarget: function(inEvent) {
  117996. var x = inEvent.clientX;
  117997. var y = inEvent.clientY;
  117998. // if the listener is in the shadow root, it is much faster to start there
  117999. var s = this.owner(inEvent.target);
  118000. // if x, y is not in this root, fall back to document search
  118001. if (!s.elementFromPoint(x, y)) {
  118002. s = document;
  118003. }
  118004. return this.searchRoot(s, x, y);
  118005. }
  118006. };
  118007. var forEach = Array.prototype.forEach.call.bind(Array.prototype.forEach);
  118008. var map = Array.prototype.map.call.bind(Array.prototype.map);
  118009. var toArray = Array.prototype.slice.call.bind(Array.prototype.slice);
  118010. var filter = Array.prototype.filter.call.bind(Array.prototype.filter);
  118011. var MO = window.MutationObserver || window.WebKitMutationObserver;
  118012. var SELECTOR = '[touch-action]';
  118013. var OBSERVER_INIT = {
  118014. subtree: true,
  118015. childList: true,
  118016. attributes: true,
  118017. attributeOldValue: true,
  118018. attributeFilter: ['touch-action']
  118019. };
  118020. function Installer(add, remove, changed, binder) {
  118021. this.addCallback = add.bind(binder);
  118022. this.removeCallback = remove.bind(binder);
  118023. this.changedCallback = changed.bind(binder);
  118024. if (MO) {
  118025. this.observer = new MO(this.mutationWatcher.bind(this));
  118026. }
  118027. }
  118028. Installer.prototype = {
  118029. watchSubtree: function(target) {
  118030. // Only watch scopes that can target find, as these are top-level.
  118031. // Otherwise we can see duplicate additions and removals that add noise.
  118032. //
  118033. // TODO(dfreedman): For some instances with ShadowDOMPolyfill, we can see
  118034. // a removal without an insertion when a node is redistributed among
  118035. // shadows. Since it all ends up correct in the document, watching only
  118036. // the document will yield the correct mutations to watch.
  118037. if (this.observer && targeting.canTarget(target)) {
  118038. this.observer.observe(target, OBSERVER_INIT);
  118039. }
  118040. },
  118041. enableOnSubtree: function(target) {
  118042. this.watchSubtree(target);
  118043. if (target === document && document.readyState !== 'complete') {
  118044. this.installOnLoad();
  118045. } else {
  118046. this.installNewSubtree(target);
  118047. }
  118048. },
  118049. installNewSubtree: function(target) {
  118050. forEach(this.findElements(target), this.addElement, this);
  118051. },
  118052. findElements: function(target) {
  118053. if (target.querySelectorAll) {
  118054. return target.querySelectorAll(SELECTOR);
  118055. }
  118056. return [];
  118057. },
  118058. removeElement: function(el) {
  118059. this.removeCallback(el);
  118060. },
  118061. addElement: function(el) {
  118062. this.addCallback(el);
  118063. },
  118064. elementChanged: function(el, oldValue) {
  118065. this.changedCallback(el, oldValue);
  118066. },
  118067. concatLists: function(accum, list) {
  118068. return accum.concat(toArray(list));
  118069. },
  118070. // register all touch-action = none nodes on document load
  118071. installOnLoad: function() {
  118072. document.addEventListener('readystatechange', function() {
  118073. if (document.readyState === 'complete') {
  118074. this.installNewSubtree(document);
  118075. }
  118076. }.bind(this));
  118077. },
  118078. isElement: function(n) {
  118079. return n.nodeType === Node.ELEMENT_NODE;
  118080. },
  118081. flattenMutationTree: function(inNodes) {
  118082. // find children with touch-action
  118083. var tree = map(inNodes, this.findElements, this);
  118084. // make sure the added nodes are accounted for
  118085. tree.push(filter(inNodes, this.isElement));
  118086. // flatten the list
  118087. return tree.reduce(this.concatLists, []);
  118088. },
  118089. mutationWatcher: function(mutations) {
  118090. mutations.forEach(this.mutationHandler, this);
  118091. },
  118092. mutationHandler: function(m) {
  118093. if (m.type === 'childList') {
  118094. var added = this.flattenMutationTree(m.addedNodes);
  118095. added.forEach(this.addElement, this);
  118096. var removed = this.flattenMutationTree(m.removedNodes);
  118097. removed.forEach(this.removeElement, this);
  118098. } else if (m.type === 'attributes') {
  118099. this.elementChanged(m.target, m.oldValue);
  118100. }
  118101. }
  118102. };
  118103. function shadowSelector(v) {
  118104. return 'body /shadow-deep/ ' + selector(v);
  118105. }
  118106. function selector(v) {
  118107. return '[touch-action="' + v + '"]';
  118108. }
  118109. function rule(v) {
  118110. return '{ -ms-touch-action: ' + v + '; touch-action: ' + v + '; }';
  118111. }
  118112. var attrib2css = [
  118113. 'none',
  118114. 'auto',
  118115. 'pan-x',
  118116. 'pan-y',
  118117. {
  118118. rule: 'pan-x pan-y',
  118119. selectors: [
  118120. 'pan-x pan-y',
  118121. 'pan-y pan-x'
  118122. ]
  118123. }
  118124. ];
  118125. var styles = '';
  118126. // only install stylesheet if the browser has touch action support
  118127. var hasNativePE = window.PointerEvent || window.MSPointerEvent;
  118128. // only add shadow selectors if shadowdom is supported
  118129. var hasShadowRoot = !window.ShadowDOMPolyfill && document.head.createShadowRoot;
  118130. function applyAttributeStyles() {
  118131. if (hasNativePE) {
  118132. attrib2css.forEach(function(r) {
  118133. if (String(r) === r) {
  118134. styles += selector(r) + rule(r) + '\n';
  118135. if (hasShadowRoot) {
  118136. styles += shadowSelector(r) + rule(r) + '\n';
  118137. }
  118138. } else {
  118139. styles += r.selectors.map(selector) + rule(r.rule) + '\n';
  118140. if (hasShadowRoot) {
  118141. styles += r.selectors.map(shadowSelector) + rule(r.rule) + '\n';
  118142. }
  118143. }
  118144. });
  118145. var el = document.createElement('style');
  118146. el.textContent = styles;
  118147. document.head.appendChild(el);
  118148. }
  118149. }
  118150. var pointermap = dispatcher.pointermap;
  118151. // radius around touchend that swallows mouse events
  118152. var DEDUP_DIST = 25;
  118153. // left, middle, right, back, forward
  118154. var BUTTON_TO_BUTTONS = [1, 4, 2, 8, 16];
  118155. var HAS_BUTTONS = false;
  118156. try {
  118157. HAS_BUTTONS = new MouseEvent('test', { buttons: 1 }).buttons === 1;
  118158. } catch (e) {}
  118159. // handler block for native mouse events
  118160. var mouseEvents = {
  118161. POINTER_ID: 1,
  118162. POINTER_TYPE: 'mouse',
  118163. events: [
  118164. 'mousedown',
  118165. 'mousemove',
  118166. 'mouseup',
  118167. 'mouseover',
  118168. 'mouseout'
  118169. ],
  118170. register: function(target) {
  118171. dispatcher.listen(target, this.events);
  118172. },
  118173. unregister: function(target) {
  118174. dispatcher.unlisten(target, this.events);
  118175. },
  118176. lastTouches: [],
  118177. // collide with the global mouse listener
  118178. isEventSimulatedFromTouch: function(inEvent) {
  118179. var lts = this.lastTouches;
  118180. var x = inEvent.clientX;
  118181. var y = inEvent.clientY;
  118182. for (var i = 0, l = lts.length, t; i < l && (t = lts[i]); i++) {
  118183. // simulated mouse events will be swallowed near a primary touchend
  118184. var dx = Math.abs(x - t.x);
  118185. var dy = Math.abs(y - t.y);
  118186. if (dx <= DEDUP_DIST && dy <= DEDUP_DIST) {
  118187. return true;
  118188. }
  118189. }
  118190. },
  118191. prepareEvent: function(inEvent) {
  118192. var e = dispatcher.cloneEvent(inEvent);
  118193. // forward mouse preventDefault
  118194. var pd = e.preventDefault;
  118195. e.preventDefault = function() {
  118196. inEvent.preventDefault();
  118197. pd();
  118198. };
  118199. e.pointerId = this.POINTER_ID;
  118200. e.isPrimary = true;
  118201. e.pointerType = this.POINTER_TYPE;
  118202. return e;
  118203. },
  118204. prepareButtonsForMove: function(e, inEvent) {
  118205. var p = pointermap.get(this.POINTER_ID);
  118206. // Update buttons state after possible out-of-document mouseup.
  118207. if (inEvent.which === 0 || !p) {
  118208. e.buttons = 0;
  118209. } else {
  118210. e.buttons = p.buttons;
  118211. }
  118212. inEvent.buttons = e.buttons;
  118213. },
  118214. mousedown: function(inEvent) {
  118215. if (!this.isEventSimulatedFromTouch(inEvent)) {
  118216. var p = pointermap.get(this.POINTER_ID);
  118217. var e = this.prepareEvent(inEvent);
  118218. if (!HAS_BUTTONS) {
  118219. e.buttons = BUTTON_TO_BUTTONS[e.button];
  118220. if (p) { e.buttons |= p.buttons; }
  118221. inEvent.buttons = e.buttons;
  118222. }
  118223. pointermap.set(this.POINTER_ID, inEvent);
  118224. if (!p || p.buttons === 0) {
  118225. dispatcher.down(e);
  118226. } else {
  118227. dispatcher.move(e);
  118228. }
  118229. }
  118230. },
  118231. mousemove: function(inEvent) {
  118232. if (!this.isEventSimulatedFromTouch(inEvent)) {
  118233. var e = this.prepareEvent(inEvent);
  118234. if (!HAS_BUTTONS) { this.prepareButtonsForMove(e, inEvent); }
  118235. e.button = -1;
  118236. pointermap.set(this.POINTER_ID, inEvent);
  118237. dispatcher.move(e);
  118238. }
  118239. },
  118240. mouseup: function(inEvent) {
  118241. if (!this.isEventSimulatedFromTouch(inEvent)) {
  118242. var p = pointermap.get(this.POINTER_ID);
  118243. var e = this.prepareEvent(inEvent);
  118244. if (!HAS_BUTTONS) {
  118245. var up = BUTTON_TO_BUTTONS[e.button];
  118246. // Produces wrong state of buttons in Browsers without `buttons` support
  118247. // when a mouse button that was pressed outside the document is released
  118248. // inside and other buttons are still pressed down.
  118249. e.buttons = p ? p.buttons & ~up : 0;
  118250. inEvent.buttons = e.buttons;
  118251. }
  118252. pointermap.set(this.POINTER_ID, inEvent);
  118253. // Support: Firefox <=44 only
  118254. // FF Ubuntu includes the lifted button in the `buttons` property on
  118255. // mouseup.
  118256. // https://bugzilla.mozilla.org/show_bug.cgi?id=1223366
  118257. e.buttons &= ~BUTTON_TO_BUTTONS[e.button];
  118258. if (e.buttons === 0) {
  118259. dispatcher.up(e);
  118260. } else {
  118261. dispatcher.move(e);
  118262. }
  118263. }
  118264. },
  118265. mouseover: function(inEvent) {
  118266. if (!this.isEventSimulatedFromTouch(inEvent)) {
  118267. var e = this.prepareEvent(inEvent);
  118268. if (!HAS_BUTTONS) { this.prepareButtonsForMove(e, inEvent); }
  118269. e.button = -1;
  118270. pointermap.set(this.POINTER_ID, inEvent);
  118271. dispatcher.enterOver(e);
  118272. }
  118273. },
  118274. mouseout: function(inEvent) {
  118275. if (!this.isEventSimulatedFromTouch(inEvent)) {
  118276. var e = this.prepareEvent(inEvent);
  118277. if (!HAS_BUTTONS) { this.prepareButtonsForMove(e, inEvent); }
  118278. e.button = -1;
  118279. dispatcher.leaveOut(e);
  118280. }
  118281. },
  118282. cancel: function(inEvent) {
  118283. var e = this.prepareEvent(inEvent);
  118284. dispatcher.cancel(e);
  118285. this.deactivateMouse();
  118286. },
  118287. deactivateMouse: function() {
  118288. pointermap.delete(this.POINTER_ID);
  118289. }
  118290. };
  118291. var captureInfo = dispatcher.captureInfo;
  118292. var findTarget = targeting.findTarget.bind(targeting);
  118293. var allShadows = targeting.allShadows.bind(targeting);
  118294. var pointermap$1 = dispatcher.pointermap;
  118295. // This should be long enough to ignore compat mouse events made by touch
  118296. var DEDUP_TIMEOUT = 2500;
  118297. var CLICK_COUNT_TIMEOUT = 200;
  118298. var ATTRIB = 'touch-action';
  118299. var INSTALLER;
  118300. // handler block for native touch events
  118301. var touchEvents = {
  118302. events: [
  118303. 'touchstart',
  118304. 'touchmove',
  118305. 'touchend',
  118306. 'touchcancel'
  118307. ],
  118308. register: function(target) {
  118309. INSTALLER.enableOnSubtree(target);
  118310. },
  118311. unregister: function() {
  118312. // TODO(dfreedman): is it worth it to disconnect the MO?
  118313. },
  118314. elementAdded: function(el) {
  118315. var a = el.getAttribute(ATTRIB);
  118316. var st = this.touchActionToScrollType(a);
  118317. if (st) {
  118318. el._scrollType = st;
  118319. dispatcher.listen(el, this.events);
  118320. // set touch-action on shadows as well
  118321. allShadows(el).forEach(function(s) {
  118322. s._scrollType = st;
  118323. dispatcher.listen(s, this.events);
  118324. }, this);
  118325. }
  118326. },
  118327. elementRemoved: function(el) {
  118328. el._scrollType = undefined;
  118329. dispatcher.unlisten(el, this.events);
  118330. // remove touch-action from shadow
  118331. allShadows(el).forEach(function(s) {
  118332. s._scrollType = undefined;
  118333. dispatcher.unlisten(s, this.events);
  118334. }, this);
  118335. },
  118336. elementChanged: function(el, oldValue) {
  118337. var a = el.getAttribute(ATTRIB);
  118338. var st = this.touchActionToScrollType(a);
  118339. var oldSt = this.touchActionToScrollType(oldValue);
  118340. // simply update scrollType if listeners are already established
  118341. if (st && oldSt) {
  118342. el._scrollType = st;
  118343. allShadows(el).forEach(function(s) {
  118344. s._scrollType = st;
  118345. }, this);
  118346. } else if (oldSt) {
  118347. this.elementRemoved(el);
  118348. } else if (st) {
  118349. this.elementAdded(el);
  118350. }
  118351. },
  118352. scrollTypes: {
  118353. EMITTER: 'none',
  118354. XSCROLLER: 'pan-x',
  118355. YSCROLLER: 'pan-y',
  118356. SCROLLER: /^(?:pan-x pan-y)|(?:pan-y pan-x)|auto$/
  118357. },
  118358. touchActionToScrollType: function(touchAction) {
  118359. var t = touchAction;
  118360. var st = this.scrollTypes;
  118361. if (t === 'none') {
  118362. return 'none';
  118363. } else if (t === st.XSCROLLER) {
  118364. return 'X';
  118365. } else if (t === st.YSCROLLER) {
  118366. return 'Y';
  118367. } else if (st.SCROLLER.exec(t)) {
  118368. return 'XY';
  118369. }
  118370. },
  118371. POINTER_TYPE: 'touch',
  118372. firstTouch: null,
  118373. isPrimaryTouch: function(inTouch) {
  118374. return this.firstTouch === inTouch.identifier;
  118375. },
  118376. setPrimaryTouch: function(inTouch) {
  118377. // set primary touch if there no pointers, or the only pointer is the mouse
  118378. if (pointermap$1.size === 0 || (pointermap$1.size === 1 && pointermap$1.has(1))) {
  118379. this.firstTouch = inTouch.identifier;
  118380. this.firstXY = { X: inTouch.clientX, Y: inTouch.clientY };
  118381. this.scrolling = false;
  118382. this.cancelResetClickCount();
  118383. }
  118384. },
  118385. removePrimaryPointer: function(inPointer) {
  118386. if (inPointer.isPrimary) {
  118387. this.firstTouch = null;
  118388. this.firstXY = null;
  118389. this.resetClickCount();
  118390. }
  118391. },
  118392. clickCount: 0,
  118393. resetId: null,
  118394. resetClickCount: function() {
  118395. var fn = function() {
  118396. this.clickCount = 0;
  118397. this.resetId = null;
  118398. }.bind(this);
  118399. this.resetId = setTimeout(fn, CLICK_COUNT_TIMEOUT);
  118400. },
  118401. cancelResetClickCount: function() {
  118402. if (this.resetId) {
  118403. clearTimeout(this.resetId);
  118404. }
  118405. },
  118406. typeToButtons: function(type) {
  118407. var ret = 0;
  118408. if (type === 'touchstart' || type === 'touchmove') {
  118409. ret = 1;
  118410. }
  118411. return ret;
  118412. },
  118413. touchToPointer: function(inTouch) {
  118414. var cte = this.currentTouchEvent;
  118415. var e = dispatcher.cloneEvent(inTouch);
  118416. // We reserve pointerId 1 for Mouse.
  118417. // Touch identifiers can start at 0.
  118418. // Add 2 to the touch identifier for compatibility.
  118419. var id = e.pointerId = inTouch.identifier + 2;
  118420. e.target = captureInfo[id] || findTarget(e);
  118421. e.bubbles = true;
  118422. e.cancelable = true;
  118423. e.detail = this.clickCount;
  118424. e.button = 0;
  118425. e.buttons = this.typeToButtons(cte.type);
  118426. e.width = (inTouch.radiusX || inTouch.webkitRadiusX || 0) * 2;
  118427. e.height = (inTouch.radiusY || inTouch.webkitRadiusY || 0) * 2;
  118428. e.pressure = inTouch.force || inTouch.webkitForce || 0.5;
  118429. e.isPrimary = this.isPrimaryTouch(inTouch);
  118430. e.pointerType = this.POINTER_TYPE;
  118431. // forward modifier keys
  118432. e.altKey = cte.altKey;
  118433. e.ctrlKey = cte.ctrlKey;
  118434. e.metaKey = cte.metaKey;
  118435. e.shiftKey = cte.shiftKey;
  118436. // forward touch preventDefaults
  118437. var self = this;
  118438. e.preventDefault = function() {
  118439. self.scrolling = false;
  118440. self.firstXY = null;
  118441. cte.preventDefault();
  118442. };
  118443. return e;
  118444. },
  118445. processTouches: function(inEvent, inFunction) {
  118446. var tl = inEvent.changedTouches;
  118447. this.currentTouchEvent = inEvent;
  118448. for (var i = 0, t; i < tl.length; i++) {
  118449. t = tl[i];
  118450. inFunction.call(this, this.touchToPointer(t));
  118451. }
  118452. },
  118453. // For single axis scrollers, determines whether the element should emit
  118454. // pointer events or behave as a scroller
  118455. shouldScroll: function(inEvent) {
  118456. if (this.firstXY) {
  118457. var ret;
  118458. var scrollAxis = inEvent.currentTarget._scrollType;
  118459. if (scrollAxis === 'none') {
  118460. // this element is a touch-action: none, should never scroll
  118461. ret = false;
  118462. } else if (scrollAxis === 'XY') {
  118463. // this element should always scroll
  118464. ret = true;
  118465. } else {
  118466. var t = inEvent.changedTouches[0];
  118467. // check the intended scroll axis, and other axis
  118468. var a = scrollAxis;
  118469. var oa = scrollAxis === 'Y' ? 'X' : 'Y';
  118470. var da = Math.abs(t['client' + a] - this.firstXY[a]);
  118471. var doa = Math.abs(t['client' + oa] - this.firstXY[oa]);
  118472. // if delta in the scroll axis > delta other axis, scroll instead of
  118473. // making events
  118474. ret = da >= doa;
  118475. }
  118476. this.firstXY = null;
  118477. return ret;
  118478. }
  118479. },
  118480. findTouch: function(inTL, inId) {
  118481. for (var i = 0, l = inTL.length, t; i < l && (t = inTL[i]); i++) {
  118482. if (t.identifier === inId) {
  118483. return true;
  118484. }
  118485. }
  118486. },
  118487. // In some instances, a touchstart can happen without a touchend. This
  118488. // leaves the pointermap in a broken state.
  118489. // Therefore, on every touchstart, we remove the touches that did not fire a
  118490. // touchend event.
  118491. // To keep state globally consistent, we fire a
  118492. // pointercancel for this "abandoned" touch
  118493. vacuumTouches: function(inEvent) {
  118494. var tl = inEvent.touches;
  118495. // pointermap.size should be < tl.length here, as the touchstart has not
  118496. // been processed yet.
  118497. if (pointermap$1.size >= tl.length) {
  118498. var d = [];
  118499. pointermap$1.forEach(function(value, key) {
  118500. // Never remove pointerId == 1, which is mouse.
  118501. // Touch identifiers are 2 smaller than their pointerId, which is the
  118502. // index in pointermap.
  118503. if (key !== 1 && !this.findTouch(tl, key - 2)) {
  118504. var p = value.out;
  118505. d.push(p);
  118506. }
  118507. }, this);
  118508. d.forEach(this.cancelOut, this);
  118509. }
  118510. },
  118511. touchstart: function(inEvent) {
  118512. this.vacuumTouches(inEvent);
  118513. this.setPrimaryTouch(inEvent.changedTouches[0]);
  118514. this.dedupSynthMouse(inEvent);
  118515. if (!this.scrolling) {
  118516. this.clickCount++;
  118517. this.processTouches(inEvent, this.overDown);
  118518. }
  118519. },
  118520. overDown: function(inPointer) {
  118521. pointermap$1.set(inPointer.pointerId, {
  118522. target: inPointer.target,
  118523. out: inPointer,
  118524. outTarget: inPointer.target
  118525. });
  118526. dispatcher.enterOver(inPointer);
  118527. dispatcher.down(inPointer);
  118528. },
  118529. touchmove: function(inEvent) {
  118530. if (!this.scrolling) {
  118531. if (this.shouldScroll(inEvent)) {
  118532. this.scrolling = true;
  118533. this.touchcancel(inEvent);
  118534. } else {
  118535. inEvent.preventDefault();
  118536. this.processTouches(inEvent, this.moveOverOut);
  118537. }
  118538. }
  118539. },
  118540. moveOverOut: function(inPointer) {
  118541. var event = inPointer;
  118542. var pointer = pointermap$1.get(event.pointerId);
  118543. // a finger drifted off the screen, ignore it
  118544. if (!pointer) {
  118545. return;
  118546. }
  118547. var outEvent = pointer.out;
  118548. var outTarget = pointer.outTarget;
  118549. dispatcher.move(event);
  118550. if (outEvent && outTarget !== event.target) {
  118551. outEvent.relatedTarget = event.target;
  118552. event.relatedTarget = outTarget;
  118553. // recover from retargeting by shadow
  118554. outEvent.target = outTarget;
  118555. if (event.target) {
  118556. dispatcher.leaveOut(outEvent);
  118557. dispatcher.enterOver(event);
  118558. } else {
  118559. // clean up case when finger leaves the screen
  118560. event.target = outTarget;
  118561. event.relatedTarget = null;
  118562. this.cancelOut(event);
  118563. }
  118564. }
  118565. pointer.out = event;
  118566. pointer.outTarget = event.target;
  118567. },
  118568. touchend: function(inEvent) {
  118569. this.dedupSynthMouse(inEvent);
  118570. this.processTouches(inEvent, this.upOut);
  118571. },
  118572. upOut: function(inPointer) {
  118573. if (!this.scrolling) {
  118574. dispatcher.up(inPointer);
  118575. dispatcher.leaveOut(inPointer);
  118576. }
  118577. this.cleanUpPointer(inPointer);
  118578. },
  118579. touchcancel: function(inEvent) {
  118580. this.processTouches(inEvent, this.cancelOut);
  118581. },
  118582. cancelOut: function(inPointer) {
  118583. dispatcher.cancel(inPointer);
  118584. dispatcher.leaveOut(inPointer);
  118585. this.cleanUpPointer(inPointer);
  118586. },
  118587. cleanUpPointer: function(inPointer) {
  118588. pointermap$1.delete(inPointer.pointerId);
  118589. this.removePrimaryPointer(inPointer);
  118590. },
  118591. // prevent synth mouse events from creating pointer events
  118592. dedupSynthMouse: function(inEvent) {
  118593. var lts = mouseEvents.lastTouches;
  118594. var t = inEvent.changedTouches[0];
  118595. // only the primary finger will synth mouse events
  118596. if (this.isPrimaryTouch(t)) {
  118597. // remember x/y of last touch
  118598. var lt = { x: t.clientX, y: t.clientY };
  118599. lts.push(lt);
  118600. var fn = (function(lts, lt) {
  118601. var i = lts.indexOf(lt);
  118602. if (i > -1) {
  118603. lts.splice(i, 1);
  118604. }
  118605. }).bind(null, lts, lt);
  118606. setTimeout(fn, DEDUP_TIMEOUT);
  118607. }
  118608. }
  118609. };
  118610. INSTALLER = new Installer(touchEvents.elementAdded, touchEvents.elementRemoved,
  118611. touchEvents.elementChanged, touchEvents);
  118612. var pointermap$2 = dispatcher.pointermap;
  118613. var HAS_BITMAP_TYPE = window.MSPointerEvent &&
  118614. typeof window.MSPointerEvent.MSPOINTER_TYPE_MOUSE === 'number';
  118615. var msEvents = {
  118616. events: [
  118617. 'MSPointerDown',
  118618. 'MSPointerMove',
  118619. 'MSPointerUp',
  118620. 'MSPointerOut',
  118621. 'MSPointerOver',
  118622. 'MSPointerCancel',
  118623. 'MSGotPointerCapture',
  118624. 'MSLostPointerCapture'
  118625. ],
  118626. register: function(target) {
  118627. dispatcher.listen(target, this.events);
  118628. },
  118629. unregister: function(target) {
  118630. dispatcher.unlisten(target, this.events);
  118631. },
  118632. POINTER_TYPES: [
  118633. '',
  118634. 'unavailable',
  118635. 'touch',
  118636. 'pen',
  118637. 'mouse'
  118638. ],
  118639. prepareEvent: function(inEvent) {
  118640. var e = inEvent;
  118641. if (HAS_BITMAP_TYPE) {
  118642. e = dispatcher.cloneEvent(inEvent);
  118643. e.pointerType = this.POINTER_TYPES[inEvent.pointerType];
  118644. }
  118645. return e;
  118646. },
  118647. cleanup: function(id) {
  118648. pointermap$2.delete(id);
  118649. },
  118650. MSPointerDown: function(inEvent) {
  118651. pointermap$2.set(inEvent.pointerId, inEvent);
  118652. var e = this.prepareEvent(inEvent);
  118653. dispatcher.down(e);
  118654. },
  118655. MSPointerMove: function(inEvent) {
  118656. var e = this.prepareEvent(inEvent);
  118657. dispatcher.move(e);
  118658. },
  118659. MSPointerUp: function(inEvent) {
  118660. var e = this.prepareEvent(inEvent);
  118661. dispatcher.up(e);
  118662. this.cleanup(inEvent.pointerId);
  118663. },
  118664. MSPointerOut: function(inEvent) {
  118665. var e = this.prepareEvent(inEvent);
  118666. dispatcher.leaveOut(e);
  118667. },
  118668. MSPointerOver: function(inEvent) {
  118669. var e = this.prepareEvent(inEvent);
  118670. dispatcher.enterOver(e);
  118671. },
  118672. MSPointerCancel: function(inEvent) {
  118673. var e = this.prepareEvent(inEvent);
  118674. dispatcher.cancel(e);
  118675. this.cleanup(inEvent.pointerId);
  118676. },
  118677. MSLostPointerCapture: function(inEvent) {
  118678. var e = dispatcher.makeEvent('lostpointercapture', inEvent);
  118679. dispatcher.dispatchEvent(e);
  118680. },
  118681. MSGotPointerCapture: function(inEvent) {
  118682. var e = dispatcher.makeEvent('gotpointercapture', inEvent);
  118683. dispatcher.dispatchEvent(e);
  118684. }
  118685. };
  118686. function applyPolyfill() {
  118687. // only activate if this platform does not have pointer events
  118688. if (!window.PointerEvent) {
  118689. window.PointerEvent = PointerEvent;
  118690. if (window.navigator.msPointerEnabled) {
  118691. var tp = window.navigator.msMaxTouchPoints;
  118692. Object.defineProperty(window.navigator, 'maxTouchPoints', {
  118693. value: tp,
  118694. enumerable: true
  118695. });
  118696. dispatcher.registerSource('ms', msEvents);
  118697. } else {
  118698. Object.defineProperty(window.navigator, 'maxTouchPoints', {
  118699. value: 0,
  118700. enumerable: true
  118701. });
  118702. dispatcher.registerSource('mouse', mouseEvents);
  118703. if (window.ontouchstart !== undefined) {
  118704. dispatcher.registerSource('touch', touchEvents);
  118705. }
  118706. }
  118707. dispatcher.register(document);
  118708. }
  118709. }
  118710. var n = window.navigator;
  118711. var s;
  118712. var r;
  118713. var h;
  118714. function assertActive(id) {
  118715. if (!dispatcher.pointermap.has(id)) {
  118716. var error = new Error('InvalidPointerId');
  118717. error.name = 'InvalidPointerId';
  118718. throw error;
  118719. }
  118720. }
  118721. function assertConnected(elem) {
  118722. var parent = elem.parentNode;
  118723. while (parent && parent !== elem.ownerDocument) {
  118724. parent = parent.parentNode;
  118725. }
  118726. if (!parent) {
  118727. var error = new Error('InvalidStateError');
  118728. error.name = 'InvalidStateError';
  118729. throw error;
  118730. }
  118731. }
  118732. function inActiveButtonState(id) {
  118733. var p = dispatcher.pointermap.get(id);
  118734. return p.buttons !== 0;
  118735. }
  118736. if (n.msPointerEnabled) {
  118737. s = function(pointerId) {
  118738. assertActive(pointerId);
  118739. assertConnected(this);
  118740. if (inActiveButtonState(pointerId)) {
  118741. dispatcher.setCapture(pointerId, this, true);
  118742. this.msSetPointerCapture(pointerId);
  118743. }
  118744. };
  118745. r = function(pointerId) {
  118746. assertActive(pointerId);
  118747. dispatcher.releaseCapture(pointerId, true);
  118748. this.msReleasePointerCapture(pointerId);
  118749. };
  118750. } else {
  118751. s = function setPointerCapture(pointerId) {
  118752. assertActive(pointerId);
  118753. assertConnected(this);
  118754. if (inActiveButtonState(pointerId)) {
  118755. dispatcher.setCapture(pointerId, this);
  118756. }
  118757. };
  118758. r = function releasePointerCapture(pointerId) {
  118759. assertActive(pointerId);
  118760. dispatcher.releaseCapture(pointerId);
  118761. };
  118762. }
  118763. h = function hasPointerCapture(pointerId) {
  118764. return !!dispatcher.captureInfo[pointerId];
  118765. };
  118766. function applyPolyfill$1() {
  118767. if (window.Element && !Element.prototype.setPointerCapture) {
  118768. Object.defineProperties(Element.prototype, {
  118769. 'setPointerCapture': {
  118770. value: s
  118771. },
  118772. 'releasePointerCapture': {
  118773. value: r
  118774. },
  118775. 'hasPointerCapture': {
  118776. value: h
  118777. }
  118778. });
  118779. }
  118780. }
  118781. applyAttributeStyles();
  118782. applyPolyfill();
  118783. applyPolyfill$1();
  118784. var pointerevents = {
  118785. dispatcher: dispatcher,
  118786. Installer: Installer,
  118787. PointerEvent: PointerEvent,
  118788. PointerMap: PointerMap,
  118789. targetFinding: targeting
  118790. };
  118791. return pointerevents;
  118792. }));
  118793. /***/ }),
  118794. /* 65 */
  118795. /***/ (function(module, exports, __webpack_require__) {
  118796. "use strict";
  118797. Object.defineProperty(exports, "__esModule", { value: true });
  118798. var defaultViewer_1 = __webpack_require__(8);
  118799. var mappers_1 = __webpack_require__(3);
  118800. var globals_1 = __webpack_require__(4);
  118801. /**
  118802. * Will attach an init function the the DOMContentLoaded event.
  118803. * The init function will be removed automatically after the event was triggered.
  118804. */
  118805. function initListeners() {
  118806. document.addEventListener("DOMContentLoaded", init);
  118807. function init(event) {
  118808. document.removeEventListener("DOMContentLoaded", init);
  118809. if (globals_1.viewerGlobals.disableInit)
  118810. return;
  118811. InitTags();
  118812. }
  118813. }
  118814. exports.initListeners = initListeners;
  118815. /**
  118816. * Select all HTML tags on the page that match the selector and initialize a viewer
  118817. *
  118818. * @param selector the selector to initialize the viewer on (default is 'babylon')
  118819. */
  118820. function InitTags(selector) {
  118821. if (selector === void 0) { selector = 'babylon'; }
  118822. var elements = document.querySelectorAll(selector);
  118823. for (var i = 0; i < elements.length; ++i) {
  118824. var element = elements.item(i);
  118825. // get the html configuration
  118826. var configMapper = mappers_1.mapperManager.getMapper('dom');
  118827. var config = configMapper.map(element);
  118828. var viewer = new defaultViewer_1.DefaultViewer(element, config);
  118829. }
  118830. }
  118831. exports.InitTags = InitTags;
  118832. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5pdGlhbGl6ZXIuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi9zcmMvaW5pdGlhbGl6ZXIudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFBQSx3REFBdUQ7QUFDdkQsbURBQXdEO0FBQ3hELG1EQUF3RDtBQUd4RDs7O0dBR0c7QUFDSDtJQUNJLFFBQVEsQ0FBQyxnQkFBZ0IsQ0FBQyxrQkFBa0IsRUFBRSxJQUFJLENBQUMsQ0FBQztJQUNwRCxjQUFjLEtBQUs7UUFDZixRQUFRLENBQUMsbUJBQW1CLENBQUMsa0JBQWtCLEVBQUUsSUFBSSxDQUFDLENBQUM7UUFDdkQsSUFBSSx1QkFBYSxDQUFDLFdBQVc7WUFBRSxPQUFPO1FBQ3RDLFFBQVEsRUFBRSxDQUFDO0lBQ2YsQ0FBQztBQUNMLENBQUM7QUFQRCxzQ0FPQztBQUVEOzs7O0dBSUc7QUFDSCxrQkFBeUIsUUFBNEI7SUFBNUIseUJBQUEsRUFBQSxvQkFBNEI7SUFDakQsSUFBSSxRQUFRLEdBQUcsUUFBUSxDQUFDLGdCQUFnQixDQUFDLFFBQVEsQ0FBQyxDQUFDO0lBQ25ELEtBQUssSUFBSSxDQUFDLEdBQUcsQ0FBQyxFQUFFLENBQUMsR0FBRyxRQUFRLENBQUMsTUFBTSxFQUFFLEVBQUUsQ0FBQ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